illuma-agents 1.0.2 → 1.0.4

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