@illuma-ai/agents 1.1.21 → 1.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +105 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/cjs/utils/llm.cjs.map +1 -1
  8. package/dist/esm/graphs/Graph.mjs +12 -1
  9. package/dist/esm/graphs/Graph.mjs.map +1 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs +105 -1
  11. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  12. package/dist/esm/run.mjs +20 -9
  13. package/dist/esm/run.mjs.map +1 -1
  14. package/dist/esm/utils/llm.mjs.map +1 -1
  15. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  16. package/package.json +1 -1
  17. package/src/graphs/Graph.ts +13 -1
  18. package/src/graphs/MultiAgentGraph.ts +128 -1
  19. package/src/graphs/__tests__/multi-agent-delegate.test.ts +205 -0
  20. package/src/run.ts +20 -11
  21. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  22. package/src/utils/llm.ts +1 -0
  23. package/src/agents/AgentContext.js +0 -782
  24. package/src/agents/AgentContext.test.js +0 -421
  25. package/src/agents/__tests__/AgentContext.test.js +0 -678
  26. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  27. package/src/common/enum.js +0 -192
  28. package/src/common/index.js +0 -3
  29. package/src/events.js +0 -166
  30. package/src/graphs/Graph.js +0 -1857
  31. package/src/graphs/MultiAgentGraph.js +0 -1092
  32. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  33. package/src/graphs/__tests__/structured-output.test.js +0 -144
  34. package/src/graphs/contextManagement.e2e.test.js +0 -718
  35. package/src/graphs/contextManagement.test.js +0 -485
  36. package/src/graphs/handoffValidation.test.js +0 -276
  37. package/src/graphs/index.js +0 -3
  38. package/src/index.js +0 -28
  39. package/src/instrumentation.js +0 -21
  40. package/src/llm/anthropic/index.js +0 -319
  41. package/src/llm/anthropic/types.js +0 -46
  42. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  43. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  44. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  45. package/src/llm/anthropic/utils/tools.js +0 -25
  46. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  47. package/src/llm/bedrock/index.js +0 -303
  48. package/src/llm/bedrock/types.js +0 -2
  49. package/src/llm/bedrock/utils/index.js +0 -6
  50. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  51. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  52. package/src/llm/fake.js +0 -92
  53. package/src/llm/google/index.js +0 -215
  54. package/src/llm/google/types.js +0 -12
  55. package/src/llm/google/utils/common.js +0 -670
  56. package/src/llm/google/utils/tools.js +0 -111
  57. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  58. package/src/llm/openai/index.js +0 -1033
  59. package/src/llm/openai/types.js +0 -2
  60. package/src/llm/openai/utils/index.js +0 -756
  61. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  62. package/src/llm/openrouter/index.js +0 -261
  63. package/src/llm/openrouter/reasoning.test.js +0 -181
  64. package/src/llm/providers.js +0 -36
  65. package/src/llm/text.js +0 -65
  66. package/src/llm/vertexai/index.js +0 -402
  67. package/src/messages/__tests__/tools.test.js +0 -392
  68. package/src/messages/cache.js +0 -404
  69. package/src/messages/cache.test.js +0 -1167
  70. package/src/messages/content.js +0 -48
  71. package/src/messages/content.test.js +0 -314
  72. package/src/messages/core.js +0 -359
  73. package/src/messages/ensureThinkingBlock.test.js +0 -997
  74. package/src/messages/format.js +0 -973
  75. package/src/messages/formatAgentMessages.test.js +0 -2278
  76. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  77. package/src/messages/formatMessage.test.js +0 -608
  78. package/src/messages/ids.js +0 -18
  79. package/src/messages/index.js +0 -9
  80. package/src/messages/labelContentByAgent.test.js +0 -725
  81. package/src/messages/prune.js +0 -438
  82. package/src/messages/reducer.js +0 -60
  83. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  84. package/src/messages/summarize.js +0 -146
  85. package/src/messages/summarize.test.js +0 -332
  86. package/src/messages/tools.js +0 -90
  87. package/src/mockStream.js +0 -81
  88. package/src/prompts/collab.js +0 -7
  89. package/src/prompts/index.js +0 -3
  90. package/src/prompts/taskmanager.js +0 -58
  91. package/src/run.js +0 -427
  92. package/src/schemas/index.js +0 -3
  93. package/src/schemas/schema-preparation.test.js +0 -370
  94. package/src/schemas/validate.js +0 -314
  95. package/src/schemas/validate.test.js +0 -264
  96. package/src/scripts/abort.js +0 -127
  97. package/src/scripts/ant_web_search.js +0 -130
  98. package/src/scripts/ant_web_search_edge_case.js +0 -133
  99. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  100. package/src/scripts/args.js +0 -41
  101. package/src/scripts/bedrock-cache-debug.js +0 -186
  102. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  103. package/src/scripts/bedrock-merge-test.js +0 -80
  104. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  105. package/src/scripts/caching.js +0 -106
  106. package/src/scripts/cli.js +0 -152
  107. package/src/scripts/cli2.js +0 -119
  108. package/src/scripts/cli3.js +0 -163
  109. package/src/scripts/cli4.js +0 -165
  110. package/src/scripts/cli5.js +0 -165
  111. package/src/scripts/code_exec.js +0 -171
  112. package/src/scripts/code_exec_files.js +0 -180
  113. package/src/scripts/code_exec_multi_session.js +0 -185
  114. package/src/scripts/code_exec_ptc.js +0 -265
  115. package/src/scripts/code_exec_session.js +0 -217
  116. package/src/scripts/code_exec_simple.js +0 -120
  117. package/src/scripts/content.js +0 -111
  118. package/src/scripts/empty_input.js +0 -125
  119. package/src/scripts/handoff-test.js +0 -96
  120. package/src/scripts/image.js +0 -138
  121. package/src/scripts/memory.js +0 -83
  122. package/src/scripts/multi-agent-chain.js +0 -271
  123. package/src/scripts/multi-agent-conditional.js +0 -185
  124. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  125. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  126. package/src/scripts/multi-agent-parallel-start.js +0 -214
  127. package/src/scripts/multi-agent-parallel.js +0 -346
  128. package/src/scripts/multi-agent-sequence.js +0 -184
  129. package/src/scripts/multi-agent-supervisor.js +0 -324
  130. package/src/scripts/multi-agent-test.js +0 -147
  131. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  132. package/src/scripts/parallel-full-metadata-test.js +0 -176
  133. package/src/scripts/parallel-tools-test.js +0 -256
  134. package/src/scripts/programmatic_exec.js +0 -277
  135. package/src/scripts/programmatic_exec_agent.js +0 -168
  136. package/src/scripts/search.js +0 -118
  137. package/src/scripts/sequential-full-metadata-test.js +0 -143
  138. package/src/scripts/simple.js +0 -174
  139. package/src/scripts/single-agent-metadata-test.js +0 -152
  140. package/src/scripts/stream.js +0 -113
  141. package/src/scripts/test-custom-prompt-key.js +0 -132
  142. package/src/scripts/test-handoff-input.js +0 -143
  143. package/src/scripts/test-handoff-preamble.js +0 -227
  144. package/src/scripts/test-handoff-steering.js +0 -353
  145. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  146. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  147. package/src/scripts/test-parallel-handoffs.js +0 -229
  148. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  149. package/src/scripts/test-thinking-handoff.js +0 -132
  150. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  151. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  152. package/src/scripts/test-tools-before-handoff.js +0 -187
  153. package/src/scripts/test_code_api.js +0 -263
  154. package/src/scripts/thinking-bedrock.js +0 -128
  155. package/src/scripts/thinking-vertexai.js +0 -130
  156. package/src/scripts/thinking.js +0 -134
  157. package/src/scripts/tool_search.js +0 -114
  158. package/src/scripts/tools.js +0 -125
  159. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  160. package/src/specs/agent-handoffs.test.js +0 -924
  161. package/src/specs/anthropic.simple.test.js +0 -287
  162. package/src/specs/azure.simple.test.js +0 -381
  163. package/src/specs/cache.simple.test.js +0 -282
  164. package/src/specs/custom-event-await.test.js +0 -148
  165. package/src/specs/deepseek.simple.test.js +0 -189
  166. package/src/specs/emergency-prune.test.js +0 -308
  167. package/src/specs/moonshot.simple.test.js +0 -237
  168. package/src/specs/observability.integration.test.js +0 -1337
  169. package/src/specs/openai.simple.test.js +0 -233
  170. package/src/specs/openrouter.simple.test.js +0 -202
  171. package/src/specs/prune.test.js +0 -733
  172. package/src/specs/reasoning.test.js +0 -144
  173. package/src/specs/spec.utils.js +0 -4
  174. package/src/specs/thinking-handoff.test.js +0 -486
  175. package/src/specs/thinking-prune.test.js +0 -600
  176. package/src/specs/token-distribution-edge-case.test.js +0 -246
  177. package/src/specs/token-memoization.test.js +0 -32
  178. package/src/specs/tokens.test.js +0 -49
  179. package/src/specs/tool-error.test.js +0 -139
  180. package/src/splitStream.js +0 -204
  181. package/src/splitStream.test.js +0 -504
  182. package/src/stream.js +0 -650
  183. package/src/stream.test.js +0 -225
  184. package/src/test/mockTools.js +0 -340
  185. package/src/tools/BrowserTools.js +0 -245
  186. package/src/tools/Calculator.js +0 -38
  187. package/src/tools/Calculator.test.js +0 -225
  188. package/src/tools/CodeExecutor.js +0 -233
  189. package/src/tools/ProgrammaticToolCalling.js +0 -602
  190. package/src/tools/StreamingToolCallBuffer.js +0 -179
  191. package/src/tools/ToolNode.js +0 -930
  192. package/src/tools/ToolSearch.js +0 -904
  193. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  194. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  195. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  196. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  197. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  198. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  199. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  200. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  201. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  202. package/src/tools/__tests__/handlers.test.js +0 -799
  203. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  204. package/src/tools/handlers.js +0 -306
  205. package/src/tools/schema.js +0 -25
  206. package/src/tools/search/anthropic.js +0 -34
  207. package/src/tools/search/content.js +0 -116
  208. package/src/tools/search/content.test.js +0 -133
  209. package/src/tools/search/firecrawl.js +0 -173
  210. package/src/tools/search/format.js +0 -198
  211. package/src/tools/search/highlights.js +0 -241
  212. package/src/tools/search/index.js +0 -3
  213. package/src/tools/search/jina-reranker.test.js +0 -106
  214. package/src/tools/search/rerankers.js +0 -165
  215. package/src/tools/search/schema.js +0 -102
  216. package/src/tools/search/search.js +0 -561
  217. package/src/tools/search/serper-scraper.js +0 -126
  218. package/src/tools/search/test.js +0 -129
  219. package/src/tools/search/tool.js +0 -453
  220. package/src/tools/search/types.js +0 -2
  221. package/src/tools/search/utils.js +0 -59
  222. package/src/types/graph.js +0 -24
  223. package/src/types/graph.test.js +0 -192
  224. package/src/types/index.js +0 -7
  225. package/src/types/llm.js +0 -2
  226. package/src/types/messages.js +0 -2
  227. package/src/types/run.js +0 -2
  228. package/src/types/stream.js +0 -2
  229. package/src/types/tools.js +0 -2
  230. package/src/utils/contextAnalytics.js +0 -79
  231. package/src/utils/contextAnalytics.test.js +0 -166
  232. package/src/utils/events.js +0 -26
  233. package/src/utils/graph.js +0 -11
  234. package/src/utils/handlers.js +0 -65
  235. package/src/utils/index.js +0 -10
  236. package/src/utils/llm.js +0 -21
  237. package/src/utils/llmConfig.js +0 -205
  238. package/src/utils/logging.js +0 -37
  239. package/src/utils/misc.js +0 -51
  240. package/src/utils/run.js +0 -69
  241. package/src/utils/schema.js +0 -21
  242. package/src/utils/title.js +0 -119
  243. package/src/utils/tokens.js +0 -92
  244. package/src/utils/toonFormat.js +0 -379
@@ -1,171 +0,0 @@
1
- import { config } from 'dotenv';
2
- config();
3
- import { HumanMessage, getBufferString, } from '@langchain/core/messages';
4
- import { Run } from '@/run';
5
- import { Providers, GraphEvents } from '@/common';
6
- import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
7
- /**
8
- * Create edges for a document review chain where each agent adds their expertise
9
- */
10
- function createDocumentReviewChain(agentIds) {
11
- const edges = [];
12
- for (let i = 0; i < agentIds.length - 1; i++) {
13
- edges.push({
14
- from: agentIds[i],
15
- to: agentIds[i + 1],
16
- edgeType: 'sequence',
17
- prompt: (messages, startIndex) => {
18
- const runMessages = messages.slice(startIndex);
19
- const bufferString = getBufferString(runMessages);
20
- // Custom prompt that maintains context of document review
21
- return `You are reviewing a document. Here is the analysis so far from previous reviewers:\n\n${bufferString}\n\nPlease add your specific review based on your expertise. Build upon previous insights without repeating them.`;
22
- },
23
- excludeResults: true,
24
- });
25
- }
26
- return edges;
27
- }
28
- async function testDocumentReviewChain() {
29
- console.log('Testing Document Review Chain...\n');
30
- const { contentParts, aggregateContent } = createContentAggregator();
31
- // Define specialized document reviewers
32
- const agents = [
33
- {
34
- agentId: 'grammar_checker',
35
- provider: Providers.ANTHROPIC,
36
- clientOptions: {
37
- modelName: 'claude-haiku-4-5',
38
- apiKey: process.env.ANTHROPIC_API_KEY,
39
- },
40
- instructions: `You are a Grammar and Style Checker.
41
- Focus on:
42
- - Grammar errors
43
- - Spelling mistakes
44
- - Sentence structure
45
- - Writing clarity
46
-
47
- Start with "GRAMMAR & STYLE CHECK:" and list issues found.`,
48
- maxContextTokens: 4000,
49
- },
50
- {
51
- agentId: 'fact_checker',
52
- provider: Providers.ANTHROPIC,
53
- clientOptions: {
54
- modelName: 'claude-haiku-4-5',
55
- apiKey: process.env.ANTHROPIC_API_KEY,
56
- },
57
- instructions: `You are a Fact Checker.
58
- Focus on:
59
- - Accuracy of claims
60
- - Data verification needs
61
- - Source requirements
62
- - Logical consistency
63
-
64
- Start with "FACT CHECK:" and note any claims that need verification.`,
65
- maxContextTokens: 4000,
66
- },
67
- {
68
- agentId: 'tone_reviewer',
69
- provider: Providers.ANTHROPIC,
70
- clientOptions: {
71
- modelName: 'claude-haiku-4-5',
72
- apiKey: process.env.ANTHROPIC_API_KEY,
73
- },
74
- instructions: `You are a Tone and Audience Reviewer.
75
- Focus on:
76
- - Appropriate tone for target audience
77
- - Consistency of voice
78
- - Engagement level
79
- - Cultural sensitivity
80
-
81
- Start with "TONE & AUDIENCE REVIEW:" and provide specific feedback.`,
82
- maxContextTokens: 4000,
83
- },
84
- {
85
- agentId: 'final_editor',
86
- provider: Providers.ANTHROPIC,
87
- clientOptions: {
88
- modelName: 'claude-haiku-4-5',
89
- apiKey: process.env.ANTHROPIC_API_KEY,
90
- },
91
- instructions: `You are the Final Editor.
92
- Based on all previous reviews:
93
- 1. Summarize key issues found
94
- 2. Prioritize changes needed
95
- 3. Provide final recommendation (approve/revise/reject)
96
-
97
- Start with "FINAL EDITORIAL DECISION:" and be decisive.`,
98
- maxContextTokens: 4000,
99
- },
100
- ];
101
- const agentIds = agents.map((a) => a.agentId);
102
- const edges = createDocumentReviewChain(agentIds);
103
- // Custom handlers (simplified)
104
- const customHandlers = {
105
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
106
- [GraphEvents.ON_RUN_STEP]: {
107
- handle: (event, data) => {
108
- const runStepData = data;
109
- if (runStepData?.name) {
110
- console.log(`\n✍️ ${runStepData.name} reviewing...`);
111
- }
112
- aggregateContent({ event, data: data });
113
- },
114
- },
115
- };
116
- const runConfig = {
117
- runId: `doc-review-chain-${Date.now()}`,
118
- graphConfig: {
119
- type: 'multi-agent',
120
- agents,
121
- edges,
122
- },
123
- customHandlers,
124
- returnContent: true,
125
- skipCleanup: true,
126
- };
127
- try {
128
- const run = await Run.create(runConfig);
129
- // Sample document to review
130
- const documentToReview = `
131
- The Impact of Artificial Intelligence on Modern Business
132
-
133
- Artificial Intelligence (AI) is revolutionizing how businesses operate in 2024. Studies show that 85% of companies have implemented some form of AI, leading to average productivity gains of 40%.
134
-
135
- Key benefits includes:
136
- - Automated decision-making reducing human error by 90%
137
- - Cost savings of up to $1 billion annually for large corporations
138
- - Enhanced customer experiences through 24/7 AI support
139
-
140
- However, challenges remain. Many organizations struggles with data privacy concerns and the need for specialized talent. The future of AI in business looks bright, but companies must carefully navigate these obstacles to fully realize it's potential.
141
- `;
142
- const userMessage = `Please review this document:\n\n${documentToReview}`;
143
- const messages = [new HumanMessage(userMessage)];
144
- console.log('Document submitted for review...\n');
145
- const config = {
146
- configurable: { thread_id: 'doc-review-1' },
147
- streamMode: 'values',
148
- version: 'v2',
149
- };
150
- await run.processStream({ messages }, config);
151
- console.log('\n=== Review Chain Complete ===');
152
- // Show how each reviewer built upon previous feedback
153
- const runMessages = run.getRunMessages();
154
- if (runMessages) {
155
- console.log('\nReview progression:');
156
- runMessages.forEach((msg, i) => {
157
- if (msg._getType() === 'ai') {
158
- console.log(`\nStep ${i + 1}: ${agentIds[Math.floor(i / 2)]}`);
159
- console.log('---');
160
- console.log(msg.content.toString().slice(0, 200) + '...');
161
- }
162
- });
163
- }
164
- }
165
- catch (error) {
166
- console.error('Error in document review chain:', error);
167
- }
168
- }
169
- // Run the test
170
- // testDocumentReviewChain();
171
- //# sourceMappingURL=multi-agent-document-review-chain.js.map
@@ -1,264 +0,0 @@
1
- import { config } from 'dotenv';
2
- config();
3
- import { HumanMessage } from '@langchain/core/messages';
4
- import { Run } from '@/run';
5
- import { Providers, GraphEvents, Constants } from '@/common';
6
- import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
7
- import { ToolEndHandler, ModelEndHandler } from '@/events';
8
- const conversationHistory = [];
9
- /**
10
- * Example of hybrid multi-agent system combining handoff and sequential patterns
11
- *
12
- * Graph structure:
13
- * START -> primary_agent -> agent_b -> agent_c -> END
14
- * |
15
- * └─> standalone_agent -> END
16
- *
17
- * Because primary_agent has BOTH handoff and direct edges:
18
- * - Uses Command-based routing for exclusive execution
19
- * - The primary agent can either:
20
- * 1. Handoff to standalone_agent (direct edge to agent_b is cancelled)
21
- * 2. OR continue to agent_b -> agent_c (if no handoff occurs)
22
- *
23
- * This is automatic behavior when an agent has both edge types.
24
- */
25
- async function testHybridMultiAgent() {
26
- console.log('Testing Hybrid Multi-Agent System (Sequential + Handoff)...\n');
27
- // Define agents
28
- const agents = [
29
- {
30
- agentId: 'primary_agent',
31
- provider: Providers.OPENAI,
32
- clientOptions: {
33
- modelName: 'gpt-4.1-mini',
34
- apiKey: process.env.OPENAI_API_KEY,
35
- },
36
- instructions: `You are the Primary Agent in a hybrid workflow.
37
-
38
- You have TWO options:
39
- 1. If the request requires specialized expertise (complex analysis, deep technical knowledge, etc.),
40
- use the "transfer_to_standalone_agent" tool to hand off to the Standalone Specialist
41
- 2. If the request is straightforward and can be handled through standard processing,
42
- just provide your initial response and it will automatically continue to Agent B
43
-
44
- Be decisive - either handoff immediately or provide your response.
45
- Start your response with "PRIMARY AGENT:" if you're handling it yourself.`,
46
- maxContextTokens: 8000,
47
- },
48
- {
49
- agentId: 'standalone_agent',
50
- provider: Providers.OPENAI,
51
- clientOptions: {
52
- modelName: 'gpt-4.1',
53
- apiKey: process.env.OPENAI_API_KEY,
54
- },
55
- instructions: `You are a Standalone Specialist Agent.
56
- You only receive requests that require specialized expertise.
57
-
58
- Provide a comprehensive, expert-level response to the request.
59
- Start your response with "STANDALONE SPECIALIST:"
60
- End with "Specialized analysis complete."`,
61
- maxContextTokens: 8000,
62
- },
63
- {
64
- agentId: 'agent_b',
65
- provider: Providers.OPENAI,
66
- clientOptions: {
67
- modelName: 'gpt-4.1',
68
- apiKey: process.env.OPENAI_API_KEY,
69
- },
70
- instructions: `You are Agent B in a sequential workflow.
71
- You receive requests that the Primary Agent decided to handle through standard processing.
72
-
73
- Your job is to:
74
- 1. Build upon the Primary Agent's initial response
75
- 2. Add additional processing or analysis (keep it brief, 2-3 sentences)
76
- 3. Prepare the information for final processing by Agent C
77
-
78
- Start your response with "AGENT B:" and end with "Passing to final processing..."`,
79
- maxContextTokens: 8000,
80
- },
81
- {
82
- agentId: 'agent_c',
83
- provider: Providers.OPENAI,
84
- clientOptions: {
85
- modelName: 'gpt-4.1',
86
- apiKey: process.env.OPENAI_API_KEY,
87
- },
88
- instructions: `You are Agent C, the final agent in the sequential workflow.
89
-
90
- Your job is to:
91
- 1. Review all previous processing from Primary Agent and Agent B
92
- 2. Provide a final summary or conclusion
93
- 3. Complete the standard workflow
94
-
95
- Start your response with "AGENT C:" and end with "Standard workflow complete."`,
96
- maxContextTokens: 8000,
97
- },
98
- ];
99
- // Define edges combining handoff and direct patterns
100
- const edges = [
101
- // Handoff edge: primary can transfer to standalone
102
- {
103
- from: 'primary_agent',
104
- to: 'standalone_agent',
105
- edgeType: 'transfer',
106
- description: 'Transfer to standalone specialist for complex requests',
107
- prompt: 'Specific instructions for the specialist',
108
- },
109
- // Direct edge - exclusive with handoffs (automatic when agent has both types)
110
- {
111
- from: 'primary_agent',
112
- to: 'agent_b',
113
- edgeType: 'sequence',
114
- description: 'Continue to Agent B only if no handoff occurs',
115
- },
116
- // Direct edge: agent_b automatically continues to agent_c
117
- {
118
- from: 'agent_b',
119
- to: 'agent_c',
120
- edgeType: 'sequence',
121
- description: 'Automatic progression from B to C',
122
- },
123
- ];
124
- try {
125
- // Test with different queries
126
- const testQueries = [
127
- {
128
- query: 'What is the capital of France?',
129
- expectedPath: 'sequential',
130
- description: 'Simple query - should go through sequential flow',
131
- },
132
- // {
133
- // query: 'Design a distributed microservices architecture for a real-time trading platform with sub-millisecond latency requirements',
134
- // expectedPath: 'handoff',
135
- // description: 'Complex query - should handoff to specialist',
136
- // },
137
- ];
138
- const config = {
139
- configurable: {
140
- thread_id: 'hybrid-conversation-1',
141
- },
142
- streamMode: 'values',
143
- version: 'v2',
144
- };
145
- for (const test of testQueries) {
146
- console.log(`\n${'='.repeat(70)}`);
147
- console.log(`TEST: ${test.description}`);
148
- console.log(`QUERY: "${test.query}"`);
149
- console.log(`EXPECTED PATH: ${test.expectedPath}`);
150
- console.log('='.repeat(70));
151
- // Reset state
152
- conversationHistory.length = 0;
153
- conversationHistory.push(new HumanMessage(test.query));
154
- // Create separate content aggregator for each test
155
- const { contentParts, aggregateContent } = createContentAggregator();
156
- // Track agent progression for this test
157
- let currentAgent = '';
158
- let handoffOccurred = false;
159
- // Create custom handlers for this test
160
- const customHandlers = {
161
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
162
- [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
163
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
164
- [GraphEvents.ON_RUN_STEP]: {
165
- handle: (event, data) => {
166
- const runStepData = data;
167
- if (runStepData?.name) {
168
- currentAgent = runStepData.name;
169
- console.log(`\n[${currentAgent}] Processing...`);
170
- }
171
- aggregateContent({ event, data: data });
172
- },
173
- },
174
- [GraphEvents.ON_RUN_STEP_COMPLETED]: {
175
- handle: (event, data) => {
176
- const runStepData = data;
177
- if (runStepData?.name) {
178
- console.log(`✓ ${runStepData.name} completed`);
179
- }
180
- aggregateContent({
181
- event,
182
- data: data,
183
- });
184
- },
185
- },
186
- [GraphEvents.ON_MESSAGE_DELTA]: {
187
- handle: (event, data) => {
188
- // console.dir(data, { depth: null });
189
- aggregateContent({ event, data: data });
190
- },
191
- },
192
- [GraphEvents.TOOL_START]: {
193
- handle: (_event, data, metadata) => {
194
- const toolData = data;
195
- if (toolData?.name?.startsWith(Constants.LC_TRANSFER_TO_)) {
196
- const specialist = toolData.name.replace(Constants.LC_TRANSFER_TO_, '');
197
- console.log(`\n🔀 Transferring to ${specialist}...`);
198
- handoffOccurred = true;
199
- }
200
- },
201
- },
202
- };
203
- // Create a new run configuration for each test
204
- const runConfig = {
205
- runId: `hybrid-multi-agent-${test.expectedPath}-${Date.now()}`,
206
- graphConfig: {
207
- type: 'multi-agent',
208
- agents,
209
- edges,
210
- },
211
- customHandlers,
212
- returnContent: true,
213
- skipCleanup: true,
214
- };
215
- // Create and execute a new run for this test
216
- const run = await Run.create(runConfig);
217
- console.log('\nProcessing request...');
218
- // Process with streaming
219
- const inputs = {
220
- messages: conversationHistory,
221
- };
222
- const finalContentParts = await run.processStream(inputs, config);
223
- const finalMessages = run.getRunMessages();
224
- if (finalMessages) {
225
- conversationHistory.push(...finalMessages);
226
- }
227
- // Show path taken
228
- console.log(`\n${'─'.repeat(70)}`);
229
- console.log('PATH ANALYSIS:');
230
- console.log(`- Query type: ${test.expectedPath}`);
231
- console.log(`- Handoff occurred: ${handoffOccurred ? 'YES' : 'NO'}`);
232
- console.log(`- Sequential path runs: ${handoffOccurred ? 'NO (exclusive routing)' : 'YES'}`);
233
- console.log(`- Result: ${(test.expectedPath === 'handoff' &&
234
- handoffOccurred &&
235
- !test.query.includes('continue')) ||
236
- (test.expectedPath === 'sequential' && !handoffOccurred)
237
- ? '✅ CORRECT'
238
- : '❌ INCORRECT'}`);
239
- console.log('─'.repeat(70));
240
- // Display the responses
241
- const aiMessages = conversationHistory.filter((msg) => msg._getType() === 'ai');
242
- console.log('\n--- Agent Responses ---');
243
- aiMessages.forEach((msg, index) => {
244
- console.log(`\nResponse ${index + 1}:`);
245
- console.log(msg.content);
246
- });
247
- }
248
- // Final summary
249
- console.log(`\n${'='.repeat(70)}`);
250
- console.log('HYBRID WORKFLOW TEST COMPLETE');
251
- console.log('='.repeat(70));
252
- console.log('\nThis test demonstrates automatic exclusive routing:');
253
- console.log('- When an agent has BOTH handoff and direct edges');
254
- console.log('- It uses Command-based routing for exclusive execution');
255
- console.log('- Either handoff OR direct edges execute, never both');
256
- console.log('\nThis prevents duplicate processing in delegation scenarios!');
257
- }
258
- catch (error) {
259
- console.error('Error in hybrid multi-agent test:', error);
260
- }
261
- }
262
- // Run the test
263
- testHybridMultiAgent();
264
- //# sourceMappingURL=multi-agent-hybrid-flow.js.map
@@ -1,214 +0,0 @@
1
- import { config } from 'dotenv';
2
- config();
3
- import { HumanMessage } from '@langchain/core/messages';
4
- import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
5
- import { ToolEndHandler } from '@/events';
6
- import { Providers, GraphEvents } from '@/common';
7
- import { sleep } from '@/utils/run';
8
- import { Run } from '@/run';
9
- const conversationHistory = [];
10
- /**
11
- * Example of parallel multi-agent system that starts with parallel execution immediately
12
- *
13
- * Graph structure:
14
- * START -> [analyst1, analyst2] -> END (parallel from start, both run simultaneously)
15
- *
16
- * This demonstrates getting a parallel stream from the very beginning,
17
- * with two agents running simultaneously. Useful for testing how different
18
- * models respond to the same input.
19
- */
20
- async function testParallelFromStart() {
21
- console.log('Testing Parallel From Start Multi-Agent System...\n');
22
- // Set up content aggregator
23
- const { contentParts, aggregateContent, stepMap } = createContentAggregator();
24
- // Define two agents - both have NO incoming edges, so they run in parallel from the start
25
- const agents = [
26
- {
27
- agentId: 'analyst1',
28
- provider: Providers.ANTHROPIC,
29
- clientOptions: {
30
- modelName: 'claude-haiku-4-5',
31
- apiKey: process.env.ANTHROPIC_API_KEY,
32
- },
33
- instructions: `You are a CREATIVE ANALYST. Analyze the user's query from a creative and innovative perspective. Focus on novel ideas, unconventional approaches, and imaginative possibilities. Keep your response concise (100-150 words). Start with "🎨 CREATIVE:"`,
34
- },
35
- {
36
- agentId: 'analyst2',
37
- provider: Providers.ANTHROPIC,
38
- clientOptions: {
39
- modelName: 'claude-haiku-4-5',
40
- apiKey: process.env.ANTHROPIC_API_KEY,
41
- },
42
- instructions: `You are a PRACTICAL ANALYST. Analyze the user's query from a logical and practical perspective. Focus on feasibility, metrics, and actionable steps. Keep your response concise (100-150 words). Start with "📊 PRACTICAL:"`,
43
- },
44
- ];
45
- // No edges needed - both agents have no incoming edges, so both are start nodes
46
- // They will run in parallel and end when both complete
47
- const edges = [];
48
- // Track which agents are active and their timing
49
- const activeAgents = new Set();
50
- const agentTimings = {};
51
- const startTime = Date.now();
52
- // Create custom handlers with extensive metadata logging
53
- const customHandlers = {
54
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
55
- [GraphEvents.CHAT_MODEL_END]: {
56
- handle: (_event, _data, metadata) => {
57
- console.log('\n====== CHAT_MODEL_END METADATA ======');
58
- console.dir(metadata, { depth: null });
59
- const nodeName = metadata?.langgraph_node;
60
- if (nodeName) {
61
- const elapsed = Date.now() - startTime;
62
- agentTimings[nodeName] = agentTimings[nodeName] || {};
63
- agentTimings[nodeName].end = elapsed;
64
- console.log(`⏱️ [${nodeName}] COMPLETED at ${elapsed}ms`);
65
- }
66
- },
67
- },
68
- [GraphEvents.CHAT_MODEL_START]: {
69
- handle: (_event, _data, metadata) => {
70
- console.log('\n====== CHAT_MODEL_START METADATA ======');
71
- console.dir(metadata, { depth: null });
72
- const nodeName = metadata?.langgraph_node;
73
- if (nodeName) {
74
- const elapsed = Date.now() - startTime;
75
- agentTimings[nodeName] = agentTimings[nodeName] || {};
76
- agentTimings[nodeName].start = elapsed;
77
- activeAgents.add(nodeName);
78
- console.log(`⏱️ [${nodeName}] STARTED at ${elapsed}ms`);
79
- }
80
- },
81
- },
82
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
83
- [GraphEvents.ON_RUN_STEP_COMPLETED]: {
84
- handle: (event, data, metadata) => {
85
- console.log('\n====== ON_RUN_STEP_COMPLETED ======');
86
- console.log('DATA:');
87
- console.dir(data, { depth: null });
88
- console.log('METADATA:');
89
- console.dir(metadata, { depth: null });
90
- aggregateContent({
91
- event,
92
- data: data,
93
- });
94
- },
95
- },
96
- [GraphEvents.ON_RUN_STEP]: {
97
- handle: (event, data, metadata) => {
98
- console.log('\n====== ON_RUN_STEP ======');
99
- console.log('DATA:');
100
- console.dir(data, { depth: null });
101
- console.log('METADATA:');
102
- console.dir(metadata, { depth: null });
103
- aggregateContent({ event, data: data });
104
- },
105
- },
106
- [GraphEvents.ON_RUN_STEP_DELTA]: {
107
- handle: (event, data, metadata) => {
108
- console.log('\n====== ON_RUN_STEP_DELTA ======');
109
- console.log('DATA:');
110
- console.dir(data, { depth: null });
111
- console.log('METADATA:');
112
- console.dir(metadata, { depth: null });
113
- aggregateContent({ event, data: data });
114
- },
115
- },
116
- [GraphEvents.ON_MESSAGE_DELTA]: {
117
- handle: (event, data, metadata) => {
118
- // Only log first delta per agent to avoid spam
119
- console.log('\n====== ON_MESSAGE_DELTA ======');
120
- console.log('DATA:');
121
- console.dir(data, { depth: null });
122
- console.log('METADATA:');
123
- console.dir(metadata, { depth: null });
124
- aggregateContent({ event, data: data });
125
- },
126
- },
127
- };
128
- // Create multi-agent run configuration
129
- const runConfig = {
130
- runId: `parallel-start-${Date.now()}`,
131
- graphConfig: {
132
- type: 'multi-agent',
133
- agents,
134
- edges,
135
- },
136
- customHandlers,
137
- returnContent: true,
138
- skipCleanup: true,
139
- };
140
- try {
141
- // Create and execute the run
142
- const run = await Run.create(runConfig);
143
- // Debug: Log the graph structure
144
- console.log('=== DEBUG: Graph Structure ===');
145
- const graph = run.Graph;
146
- console.log('Graph exists:', !!graph);
147
- if (graph) {
148
- console.log('Graph type:', graph.constructor.name);
149
- console.log('AgentContexts exists:', !!graph.agentContexts);
150
- if (graph.agentContexts) {
151
- console.log('AgentContexts size:', graph.agentContexts.size);
152
- for (const [agentId, context] of graph.agentContexts) {
153
- console.log(`\nAgent: ${agentId}`);
154
- console.log(`Tools: ${context.tools?.map((t) => t.name || 'unnamed').join(', ') || 'none'}`);
155
- }
156
- }
157
- }
158
- console.log('=== END DEBUG ===\n');
159
- const userMessage = `What are the best approaches to learning a new programming language?`;
160
- conversationHistory.push(new HumanMessage(userMessage));
161
- console.log('Invoking parallel-from-start multi-agent graph...\n');
162
- console.log('Both analyst1 and analyst2 should start simultaneously!\n');
163
- const config = {
164
- configurable: {
165
- thread_id: 'parallel-start-conversation-1',
166
- },
167
- streamMode: 'values',
168
- version: 'v2',
169
- };
170
- // Process with streaming
171
- const inputs = {
172
- messages: conversationHistory,
173
- };
174
- const finalContentParts = await run.processStream(inputs, config);
175
- const finalMessages = run.getRunMessages();
176
- if (finalMessages) {
177
- conversationHistory.push(...finalMessages);
178
- }
179
- console.log('\n\n========== TIMING SUMMARY ==========');
180
- for (const [agent, timing] of Object.entries(agentTimings)) {
181
- const duration = timing.end && timing.start ? timing.end - timing.start : 'N/A';
182
- console.log(`${agent}: started=${timing.start}ms, ended=${timing.end}ms, duration=${duration}ms`);
183
- }
184
- // Check if parallel
185
- const agents = Object.keys(agentTimings);
186
- if (agents.length >= 2) {
187
- const [a1, a2] = agents;
188
- const t1 = agentTimings[a1];
189
- const t2 = agentTimings[a2];
190
- if (t1.start && t2.start && t1.end && t2.end) {
191
- const overlap = Math.min(t1.end, t2.end) - Math.max(t1.start, t2.start);
192
- if (overlap > 0) {
193
- console.log(`\n✅ PARALLEL EXECUTION CONFIRMED: ${overlap}ms overlap`);
194
- }
195
- else {
196
- console.log(`\n❌ SEQUENTIAL EXECUTION: no overlap`);
197
- }
198
- }
199
- }
200
- console.log('====================================\n');
201
- console.log('Final content parts:', contentParts.length, 'parts');
202
- console.log('\n=== Content Parts (clean, no metadata) ===');
203
- console.dir(contentParts, { depth: null });
204
- console.log('\n=== Step Map (separate from content) ===');
205
- console.dir(Object.fromEntries(stepMap), { depth: null });
206
- await sleep(3000);
207
- }
208
- catch (error) {
209
- console.error('Error in parallel-from-start multi-agent test:', error);
210
- }
211
- }
212
- // Run the test
213
- testParallelFromStart();
214
- //# sourceMappingURL=multi-agent-parallel-start.js.map