@librechat/agents 2.4.321 → 3.0.0-rc1

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