@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,346 +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 with fan-in/fan-out pattern
12
- *
13
- * Graph structure:
14
- * START -> researcher
15
- * researcher -> [analyst1, analyst2, analyst3] (fan-out)
16
- * [analyst1, analyst2, analyst3] -> summarizer (fan-in)
17
- * summarizer -> END
18
- */
19
- async function testParallelMultiAgent() {
20
- console.log('Testing Parallel Multi-Agent System (Fan-in/Fan-out)...\n');
21
- // Note: You may see "Run ID not found in run map" errors during parallel execution.
22
- // This is a known issue with LangGraph's event streaming when nodes run in parallel.
23
- // The errors can be safely ignored - the parallel execution still works correctly.
24
- // Set up content aggregator
25
- const { contentParts, aggregateContent } = createContentAggregator();
26
- // Define specialized agents
27
- const agents = [
28
- {
29
- agentId: 'researcher',
30
- provider: Providers.ANTHROPIC,
31
- clientOptions: {
32
- modelName: 'claude-haiku-4-5',
33
- apiKey: process.env.ANTHROPIC_API_KEY,
34
- },
35
- instructions: `You are a research coordinator in a multi-agent analysis workflow. Your sole job is to:
36
-
37
- 1. Analyze the incoming request and break it down into exactly 3 distinct research areas
38
- 2. Create specific, actionable analysis tasks for each specialist team
39
- 3. Format your output as clear directives (not analysis yourself)
40
- 4. Keep your response under 200 words - you are NOT doing the analysis, just coordinating it
41
-
42
- Example format:
43
- "ANALYSIS COORDINATION:
44
- Financial Team: [specific financial analysis task]
45
- Technical Team: [specific technical analysis task]
46
- Market Team: [specific market analysis task]
47
-
48
- Proceed with parallel analysis."
49
-
50
- Do NOT provide any actual analysis - your job is purely coordination and task assignment.`,
51
- },
52
- {
53
- agentId: 'analyst1',
54
- provider: Providers.ANTHROPIC,
55
- clientOptions: {
56
- modelName: 'claude-haiku-4-5',
57
- apiKey: process.env.ANTHROPIC_API_KEY,
58
- },
59
- instructions: `You are a FINANCIAL AND ECONOMIC ANALYST in a parallel analysis workflow.
60
-
61
- CRITICAL: You must provide detailed, substantive financial analysis (minimum 300 words). Focus specifically on:
62
-
63
- • Economic impact metrics (GDP, productivity, employment effects)
64
- • Monetary policy implications and inflation considerations
65
- • Investment flows and capital market disruptions
66
- • Financial sector transformation and banking impacts
67
- • Government fiscal policy and tax revenue effects
68
- • International trade and currency implications
69
- • Risk assessment and financial stability concerns
70
-
71
- Provide concrete data, projections, and financial reasoning. Never give empty responses, brief acknowledgments, or defer to other analysts. This is your domain expertise - deliver comprehensive financial analysis.
72
-
73
- Start your response with "FINANCIAL ANALYSIS:" and provide detailed insights.`,
74
- },
75
- {
76
- agentId: 'analyst2',
77
- provider: Providers.ANTHROPIC,
78
- clientOptions: {
79
- modelName: 'claude-haiku-4-5',
80
- apiKey: process.env.ANTHROPIC_API_KEY,
81
- },
82
- instructions: `You are a TECHNICAL AND IMPLEMENTATION ANALYST in a parallel analysis workflow.
83
-
84
- CRITICAL: You must provide detailed, substantive technical analysis (minimum 300 words). Focus specifically on:
85
-
86
- • AI infrastructure requirements and scalability challenges
87
- • Computing power, data center, and energy demands
88
- • Network connectivity and bandwidth requirements
89
- • Technical barriers to widespread AI adoption
90
- • Implementation timelines and deployment phases
91
- • Skills gap analysis and workforce technical requirements
92
- • Security vulnerabilities and technical risk mitigation
93
- • Integration challenges with existing systems
94
-
95
- Provide concrete technical assessments, infrastructure projections, and implementation roadmaps. Never give empty responses, brief acknowledgments, or defer to other analysts. This is your technical expertise domain.
96
-
97
- Start your response with "TECHNICAL ANALYSIS:" and provide detailed technical insights.`,
98
- },
99
- {
100
- agentId: 'analyst3',
101
- provider: Providers.ANTHROPIC,
102
- clientOptions: {
103
- modelName: 'claude-haiku-4-5',
104
- apiKey: process.env.ANTHROPIC_API_KEY,
105
- },
106
- instructions: `You are a MARKET AND INDUSTRY ANALYST in a parallel analysis workflow.
107
-
108
- CRITICAL: You must provide detailed, substantive market analysis (minimum 300 words). Focus specifically on:
109
-
110
- • Industry disruption patterns and transformation timelines
111
- • Competitive landscape shifts and market consolidation
112
- • Consumer adoption rates and behavior changes
113
- • New business models and market opportunities
114
- • Geographic market variations and regional impacts
115
- • Regulatory environment and policy implications
116
- • Market size projections and growth trajectories
117
- • Sector-specific impacts (healthcare, finance, manufacturing, etc.)
118
-
119
- Provide concrete market assessments, competitive analysis, and industry projections. Never give empty responses, brief acknowledgments, or defer to other analysts. This is your market expertise domain.
120
-
121
- Start your response with "MARKET ANALYSIS:" and provide detailed market insights.`,
122
- },
123
- {
124
- agentId: 'summarizer',
125
- provider: Providers.ANTHROPIC,
126
- clientOptions: {
127
- modelName: 'claude-haiku-4-5',
128
- apiKey: process.env.ANTHROPIC_API_KEY,
129
- },
130
- instructions: `You are the SYNTHESIS AND SUMMARY EXPERT in a multi-agent workflow.
131
-
132
- Your job is to:
133
- 1. Receive and analyze the outputs from all three specialist analysts
134
- 2. Identify key themes, conflicts, and complementary insights across analyses
135
- 3. Synthesize findings into a coherent, comprehensive executive summary
136
- 4. Highlight critical interdependencies between financial, technical, and market factors
137
- 5. Provide integrated conclusions and strategic recommendations
138
-
139
- Structure your summary as:
140
- - EXECUTIVE SUMMARY (key findings)
141
- - INTEGRATED INSIGHTS (how the three analyses connect)
142
- - CRITICAL INTERDEPENDENCIES (financial-technical-market intersections)
143
- - STRATEGIC RECOMMENDATIONS (actionable next steps)
144
- - RISK ASSESSMENT (combined risk factors from all domains)
145
-
146
- Minimum 400 words. Create value through integration, not just concatenation of the three analyses.`,
147
- },
148
- ];
149
- // Define direct edges (fan-out and fan-in)
150
- const edges = [
151
- {
152
- from: 'researcher',
153
- to: ['analyst1', 'analyst2', 'analyst3'], // Fan-out to multiple analysts
154
- description: 'Distribute research to specialist analysts',
155
- edgeType: 'sequence', // Explicitly set as direct for automatic transition (enables parallel execution)
156
- },
157
- {
158
- from: ['analyst1', 'analyst2', 'analyst3'], // Fan-in from multiple sources
159
- to: 'summarizer',
160
- description: 'Aggregate analysis results',
161
- edgeType: 'sequence', // Fan-in is also direct
162
- // Add prompt when all analysts have provided input
163
- // prompt: (messages, runStartIndex) => {
164
- // // Check if we have analysis content from all three analysts
165
- // // Look for the specific headers each analyst uses
166
- // const aiMessages = messages.filter(
167
- // (msg, index) => msg.getType() === 'ai' && index >= runStartIndex
168
- // );
169
- // const messageContent = aiMessages.map((msg) => msg.content).join('\n');
170
- // const hasFinancialAnalysis = messageContent.includes(
171
- // 'FINANCIAL ANALYSIS:'
172
- // );
173
- // const hasTechnicalAnalysis = messageContent.includes(
174
- // 'TECHNICAL ANALYSIS:'
175
- // );
176
- // const hasMarketAnalysis = messageContent.includes('MARKET ANALYSIS:');
177
- // console.log(
178
- // `Checking for analyses - Financial: ${hasFinancialAnalysis}, Technical: ${hasTechnicalAnalysis}, Market: ${hasMarketAnalysis}`
179
- // );
180
- // if (hasFinancialAnalysis && hasTechnicalAnalysis && hasMarketAnalysis) {
181
- // return 'Based on the comprehensive analyses from all three specialist teams above, please synthesize their insights into a cohesive executive summary. Focus on the key findings, common themes, and strategic implications across the financial, technical, and market perspectives.';
182
- // }
183
- // return undefined; // No prompt if we haven't received all analyst inputs
184
- // },
185
- prompt: 'Based on the comprehensive analyses from all three specialist teams below, please synthesize their insights into a cohesive executive summary. Focus on the key findings, common themes, and strategic implications across the financial, technical, and market perspectives.\n\n{results}',
186
- },
187
- ];
188
- // Track which agents are active
189
- const activeAgents = new Set();
190
- const startTime = Date.now();
191
- let messageCount = 0;
192
- // Create custom handlers with extensive metadata logging
193
- const customHandlers = {
194
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
195
- [GraphEvents.CHAT_MODEL_END]: {
196
- handle: (_event, _data, metadata) => {
197
- console.log('\n====== CHAT_MODEL_END METADATA ======');
198
- console.dir(metadata, { depth: null });
199
- const elapsed = Date.now() - startTime;
200
- const nodeName = metadata?.langgraph_node;
201
- console.log(`⏱️ [${nodeName || 'unknown'}] COMPLETED at ${elapsed}ms`);
202
- },
203
- },
204
- [GraphEvents.CHAT_MODEL_START]: {
205
- handle: (_event, _data, metadata) => {
206
- console.log('\n====== CHAT_MODEL_START METADATA ======');
207
- console.dir(metadata, { depth: null });
208
- const elapsed = Date.now() - startTime;
209
- const nodeName = metadata?.langgraph_node;
210
- console.log(`⏱️ [${nodeName || 'unknown'}] STARTED at ${elapsed}ms`);
211
- },
212
- },
213
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
214
- [GraphEvents.ON_RUN_STEP_COMPLETED]: {
215
- handle: (event, data, metadata) => {
216
- console.log('\n====== ON_RUN_STEP_COMPLETED ======');
217
- console.log('DATA:');
218
- console.dir(data, { depth: null });
219
- console.log('METADATA:');
220
- console.dir(metadata, { depth: null });
221
- const runStepData = data;
222
- if (runStepData?.name) {
223
- activeAgents.delete(runStepData.name);
224
- console.log(`[${runStepData.name}] Completed analysis`);
225
- }
226
- aggregateContent({
227
- event,
228
- data: data,
229
- });
230
- },
231
- },
232
- [GraphEvents.ON_RUN_STEP]: {
233
- handle: (event, data, metadata) => {
234
- console.log('\n====== ON_RUN_STEP ======');
235
- console.log('DATA:');
236
- console.dir(data, { depth: null });
237
- console.log('METADATA:');
238
- console.dir(metadata, { depth: null });
239
- const runStepData = data;
240
- if (runStepData?.name) {
241
- activeAgents.add(runStepData.name);
242
- console.log(`[${runStepData.name}] Starting analysis...`);
243
- }
244
- aggregateContent({ event, data: data });
245
- },
246
- },
247
- [GraphEvents.ON_RUN_STEP_DELTA]: {
248
- handle: (event, data, metadata) => {
249
- console.log('\n====== ON_RUN_STEP_DELTA ======');
250
- console.log('DATA:');
251
- console.dir(data, { depth: null });
252
- console.log('METADATA:');
253
- console.dir(metadata, { depth: null });
254
- aggregateContent({ event, data: data });
255
- },
256
- },
257
- [GraphEvents.ON_MESSAGE_DELTA]: {
258
- handle: (event, data, metadata) => {
259
- messageCount++;
260
- // Only log first few message deltas per agent to avoid spam
261
- if (messageCount <= 5) {
262
- console.log('\n====== ON_MESSAGE_DELTA ======');
263
- console.log('DATA:');
264
- console.dir(data, { depth: null });
265
- console.log('METADATA:');
266
- console.dir(metadata, { depth: null });
267
- }
268
- aggregateContent({ event, data: data });
269
- },
270
- },
271
- };
272
- // Create multi-agent run configuration
273
- const runConfig = {
274
- runId: `parallel-multi-agent-${Date.now()}`,
275
- graphConfig: {
276
- type: 'multi-agent',
277
- agents,
278
- edges,
279
- // Add compile options to help with parallel execution
280
- compileOptions: {
281
- // checkpointer: new MemorySaver(), // Uncomment if needed
282
- },
283
- },
284
- customHandlers,
285
- returnContent: true,
286
- skipCleanup: true,
287
- };
288
- try {
289
- // Create and execute the run
290
- const run = await Run.create(runConfig);
291
- // Debug: Log the graph structure
292
- console.log('=== DEBUG: Graph Structure ===');
293
- const graph = run.Graph;
294
- console.log('Graph exists:', !!graph);
295
- if (graph) {
296
- console.log('Graph type:', graph.constructor.name);
297
- console.log('AgentContexts exists:', !!graph.agentContexts);
298
- if (graph.agentContexts) {
299
- console.log('AgentContexts size:', graph.agentContexts.size);
300
- for (const [agentId, context] of graph.agentContexts) {
301
- console.log(`\nAgent: ${agentId}`);
302
- console.log(`Tools: ${context.tools?.map((t) => t.name || 'unnamed').join(', ') || 'none'}`);
303
- }
304
- }
305
- }
306
- console.log('=== END DEBUG ===\n');
307
- const userMessage = `EXECUTE PARALLEL ANALYSIS WORKFLOW:
308
-
309
- Step 1: Researcher - identify 3 key analysis areas for AI economic impact
310
- Step 2: IMMEDIATELY send to ALL THREE analysts simultaneously:
311
- - analyst1 (financial): Provide detailed economic impact analysis
312
- - analyst2 (technical): Provide detailed technical implementation analysis
313
- - analyst3 (market): Provide detailed market disruption analysis
314
- Step 3: Summarizer - compile all three analyses
315
-
316
- IMPORTANT: Each analyst must produce substantive analysis (200+ words), not just acknowledgments or empty responses. This is a multi-agent workflow test requiring actual parallel execution.`;
317
- conversationHistory.push(new HumanMessage(userMessage));
318
- console.log('Invoking parallel multi-agent graph...\n');
319
- const config = {
320
- configurable: {
321
- thread_id: 'parallel-conversation-1',
322
- },
323
- streamMode: 'values',
324
- version: 'v2',
325
- };
326
- // Process with streaming
327
- const inputs = {
328
- messages: conversationHistory,
329
- };
330
- const finalContentParts = await run.processStream(inputs, config);
331
- const finalMessages = run.getRunMessages();
332
- if (finalMessages) {
333
- conversationHistory.push(...finalMessages);
334
- }
335
- console.log('\n\nActive agents during execution:', activeAgents.size);
336
- console.log('Final content parts:', contentParts.length, 'parts');
337
- console.dir(contentParts, { depth: null });
338
- await sleep(3000);
339
- }
340
- catch (error) {
341
- console.error('Error in parallel multi-agent test:', error);
342
- }
343
- }
344
- // Run the test
345
- testParallelMultiAgent();
346
- //# sourceMappingURL=multi-agent-parallel.js.map
@@ -1,184 +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 } from '@/common';
6
- import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
7
- import { ToolEndHandler, ModelEndHandler } from '@/events';
8
- const conversationHistory = [];
9
- /**
10
- * Example of simple sequential multi-agent system
11
- *
12
- * Graph structure:
13
- * START -> agent_a -> agent_b -> agent_c -> END
14
- *
15
- * No conditions, no tools, just automatic sequential flow
16
- */
17
- async function testSequentialMultiAgent() {
18
- console.log('Testing Sequential Multi-Agent System (A → B → C)...\n');
19
- // Set up content aggregator
20
- const { contentParts, aggregateContent, stepMap } = createContentAggregator();
21
- // Define three simple agents
22
- const agents = [
23
- {
24
- agentId: 'agent_a',
25
- provider: Providers.ANTHROPIC,
26
- clientOptions: {
27
- modelName: 'claude-haiku-4-5',
28
- apiKey: process.env.ANTHROPIC_API_KEY,
29
- },
30
- instructions: `You are Agent A, the first agent in a sequential workflow.
31
- Your job is to:
32
- 1. Receive the initial user request
33
- 2. Process it and add your perspective (keep it brief, 2-3 sentences)
34
- 3. Pass it along to Agent B
35
-
36
- Start your response with "AGENT A:" and end with "Passing to Agent B..."`,
37
- maxContextTokens: 8000,
38
- },
39
- {
40
- agentId: 'agent_b',
41
- provider: Providers.ANTHROPIC,
42
- clientOptions: {
43
- modelName: 'claude-haiku-4-5',
44
- apiKey: process.env.ANTHROPIC_API_KEY,
45
- },
46
- instructions: `You are Agent B, the second agent in a sequential workflow.
47
- Your job is to:
48
- 1. Receive the context from Agent A
49
- 2. Add your own analysis or perspective (keep it brief, 2-3 sentences)
50
- 3. Pass it along to Agent C
51
-
52
- Start your response with "AGENT B:" and end with "Passing to Agent C..."`,
53
- maxContextTokens: 8000,
54
- },
55
- {
56
- agentId: 'agent_c',
57
- provider: Providers.ANTHROPIC,
58
- clientOptions: {
59
- modelName: 'claude-haiku-4-5',
60
- apiKey: process.env.ANTHROPIC_API_KEY,
61
- },
62
- instructions: `You are Agent C, the final agent in a sequential workflow.
63
- Your job is to:
64
- 1. Receive the context from Agents A and B
65
- 2. Provide a final summary or conclusion based on all previous inputs
66
- 3. Complete the workflow
67
-
68
- Start your response with "AGENT C:" and end with "Workflow complete."`,
69
- maxContextTokens: 8000,
70
- },
71
- ];
72
- // Define sequential edges using 'direct' type to avoid tool creation
73
- // This creates automatic transitions without requiring agents to call tools
74
- const edges = [
75
- {
76
- from: 'agent_a',
77
- to: 'agent_b',
78
- edgeType: 'sequence', // This creates direct edges without tools
79
- description: 'Automatic transition from A to B',
80
- },
81
- {
82
- from: 'agent_b',
83
- to: 'agent_c',
84
- edgeType: 'sequence', // This creates direct edges without tools
85
- description: 'Automatic transition from B to C',
86
- },
87
- ];
88
- // Track agent progression
89
- let currentAgent = '';
90
- // Create custom handlers
91
- const customHandlers = {
92
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
93
- [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
94
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
95
- [GraphEvents.ON_RUN_STEP]: {
96
- handle: (event, data) => {
97
- const runStepData = data;
98
- if (runStepData?.name) {
99
- currentAgent = runStepData.name;
100
- console.log(`\n→ ${currentAgent} is processing...`);
101
- }
102
- aggregateContent({ event, data: data });
103
- },
104
- },
105
- [GraphEvents.ON_RUN_STEP_COMPLETED]: {
106
- handle: (event, data) => {
107
- const runStepData = data;
108
- if (runStepData?.name) {
109
- console.log(`✓ ${runStepData.name} completed`);
110
- }
111
- aggregateContent({
112
- event,
113
- data: data,
114
- });
115
- },
116
- },
117
- [GraphEvents.ON_RUN_STEP_DELTA]: {
118
- handle: (event, data) => {
119
- aggregateContent({ event, data: data });
120
- },
121
- },
122
- [GraphEvents.ON_MESSAGE_DELTA]: {
123
- handle: (event, data) => {
124
- aggregateContent({ event, data: data });
125
- },
126
- },
127
- };
128
- // Create multi-agent run configuration
129
- const runConfig = {
130
- runId: `sequential-multi-agent-${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
- // Test with a simple question
144
- const userMessage = 'What are the key considerations for building a recommendation system?';
145
- conversationHistory.push(new HumanMessage(userMessage));
146
- console.log(`User: "${userMessage}"\n`);
147
- console.log('Starting sequential workflow...\n');
148
- const config = {
149
- configurable: {
150
- thread_id: 'sequential-conversation-1',
151
- },
152
- streamMode: 'values',
153
- version: 'v2',
154
- };
155
- // Process with streaming
156
- const inputs = {
157
- messages: conversationHistory,
158
- };
159
- const finalContentParts = await run.processStream(inputs, config);
160
- const finalMessages = run.getRunMessages();
161
- if (finalMessages) {
162
- conversationHistory.push(...finalMessages);
163
- }
164
- console.log('\n\n=== Final Output ===');
165
- console.log('Sequential flow completed successfully!');
166
- console.log(`Total content parts: ${contentParts.length}`);
167
- console.log('\n=== Content Parts (clean, no metadata) ===');
168
- console.dir(contentParts, { depth: null });
169
- console.log('\n=== Step Map (separate from content) ===');
170
- console.dir(Object.fromEntries(stepMap), { depth: null });
171
- // Display the sequential responses
172
- const aiMessages = conversationHistory.filter((msg) => msg._getType() === 'ai');
173
- aiMessages.forEach((msg, index) => {
174
- console.log(`\n--- Response ${index + 1} ---`);
175
- console.log(msg.content);
176
- });
177
- }
178
- catch (error) {
179
- console.error('Error in sequential multi-agent test:', error);
180
- }
181
- }
182
- // Run the test
183
- testSequentialMultiAgent();
184
- //# sourceMappingURL=multi-agent-sequence.js.map