@librechat/agents 3.0.0-rc7 → 3.0.0-rc9

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 (48) hide show
  1. package/dist/cjs/graphs/Graph.cjs +0 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +103 -19
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/esm/graphs/Graph.mjs +0 -1
  6. package/dist/esm/graphs/Graph.mjs.map +1 -1
  7. package/dist/esm/graphs/MultiAgentGraph.mjs +103 -19
  8. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  9. package/dist/types/graphs/MultiAgentGraph.d.ts +11 -1
  10. package/package.json +5 -1
  11. package/src/graphs/Graph.ts +0 -1
  12. package/src/graphs/MultiAgentGraph.ts +120 -21
  13. package/src/scripts/multi-agent-chain.ts +278 -0
  14. package/src/scripts/multi-agent-document-review-chain.ts +197 -0
  15. package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
  16. package/src/scripts/test-tools-before-handoff.ts +233 -0
  17. package/dist/types/scripts/abort.d.ts +0 -1
  18. package/dist/types/scripts/ant_web_search.d.ts +0 -1
  19. package/dist/types/scripts/args.d.ts +0 -7
  20. package/dist/types/scripts/caching.d.ts +0 -1
  21. package/dist/types/scripts/cli.d.ts +0 -1
  22. package/dist/types/scripts/cli2.d.ts +0 -1
  23. package/dist/types/scripts/cli3.d.ts +0 -1
  24. package/dist/types/scripts/cli4.d.ts +0 -1
  25. package/dist/types/scripts/cli5.d.ts +0 -1
  26. package/dist/types/scripts/code_exec.d.ts +0 -1
  27. package/dist/types/scripts/code_exec_files.d.ts +0 -1
  28. package/dist/types/scripts/code_exec_simple.d.ts +0 -1
  29. package/dist/types/scripts/content.d.ts +0 -1
  30. package/dist/types/scripts/empty_input.d.ts +0 -1
  31. package/dist/types/scripts/handoff-test.d.ts +0 -1
  32. package/dist/types/scripts/image.d.ts +0 -1
  33. package/dist/types/scripts/memory.d.ts +0 -1
  34. package/dist/types/scripts/multi-agent-conditional.d.ts +0 -1
  35. package/dist/types/scripts/multi-agent-parallel.d.ts +0 -1
  36. package/dist/types/scripts/multi-agent-sequence.d.ts +0 -1
  37. package/dist/types/scripts/multi-agent-supervisor.d.ts +0 -1
  38. package/dist/types/scripts/multi-agent-test.d.ts +0 -1
  39. package/dist/types/scripts/search.d.ts +0 -1
  40. package/dist/types/scripts/simple.d.ts +0 -1
  41. package/dist/types/scripts/stream.d.ts +0 -1
  42. package/dist/types/scripts/test-custom-prompt-key.d.ts +0 -2
  43. package/dist/types/scripts/test-handoff-input.d.ts +0 -1
  44. package/dist/types/scripts/test-multi-agent-list-handoff.d.ts +0 -2
  45. package/dist/types/scripts/thinking.d.ts +0 -1
  46. package/dist/types/scripts/tools.d.ts +0 -1
  47. package/dist/types/specs/spec.utils.d.ts +0 -1
  48. package/src/scripts/multi-agent-example-output.md +0 -110
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.0.00-rc7",
3
+ "version": "3.0.00-rc9",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -57,11 +57,14 @@
57
57
  "abort": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/abort.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
58
58
  "start:cli2": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/cli2.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
59
59
  "multi-agent-test": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-test.ts",
60
+ "test-tools-before-handoff": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-tools-before-handoff.ts",
60
61
  "multi-agent-parallel": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-parallel.ts",
62
+ "multi-agent-chain": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-chain.ts",
61
63
  "multi-agent-sequence": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-sequence.ts",
62
64
  "multi-agent-conditional": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-conditional.ts",
63
65
  "multi-agent-supervisor": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-supervisor.ts",
64
66
  "multi-agent-list-handoff": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-multi-agent-list-handoff.ts",
67
+ "multi-agent-hybrid-flow": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-hybrid-flow.ts",
65
68
  "test-handoff-input": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-handoff-input.ts",
66
69
  "test-custom-prompt-key": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-custom-prompt-key.ts",
67
70
  "script2": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/proto/example_test.ts",
@@ -115,6 +118,7 @@
115
118
  "devDependencies": {
116
119
  "@anthropic-ai/vertex-sdk": "^0.12.0",
117
120
  "@eslint/compat": "^1.2.7",
121
+ "@langchain/tavily": "^0.1.5",
118
122
  "@rollup/plugin-alias": "^5.1.0",
119
123
  "@rollup/plugin-commonjs": "^28.0.3",
120
124
  "@rollup/plugin-json": "^6.1.0",
@@ -380,7 +380,6 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
380
380
  currentTools?: t.GraphTools;
381
381
  currentToolMap?: t.ToolMap;
382
382
  }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {
383
- // return new ToolNode<t.BaseGraphState>(this.tools);
384
383
  return new CustomToolNode<t.BaseGraphState>({
385
384
  tools: (currentTools as t.GenericTool[] | undefined) ?? [],
386
385
  toolMap: currentToolMap,
@@ -23,7 +23,17 @@ import { Constants } from '@/common';
23
23
 
24
24
  /**
25
25
  * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows
26
- * with handoffs, fan-in/fan-out, and other composable patterns
26
+ * with handoffs, fan-in/fan-out, and other composable patterns.
27
+ *
28
+ * Key behavior:
29
+ * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination
30
+ * - Agents with ONLY direct edges: Always follow their direct edges
31
+ * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)
32
+ * - If handoff occurs: Only the handoff destination executes
33
+ * - If no handoff: Direct edges execute (potentially in parallel)
34
+ *
35
+ * This enables the common pattern where an agent either delegates (handoff)
36
+ * OR continues its workflow (direct edges), but not both simultaneously.
27
37
  */
28
38
  export class MultiAgentGraph extends StandardGraph {
29
39
  private edges: t.GraphEdge[];
@@ -125,14 +135,6 @@ export class MultiAgentGraph extends StandardGraph {
125
135
  agentContext.tools = [];
126
136
  }
127
137
  agentContext.tools.push(...handoffTools);
128
-
129
- // Update tool map
130
- for (const tool of handoffTools) {
131
- if (!agentContext.toolMap) {
132
- agentContext.toolMap = new Map();
133
- }
134
- agentContext.toolMap.set(tool.name, tool);
135
- }
136
138
  }
137
139
  }
138
140
 
@@ -336,41 +338,123 @@ export class MultiAgentGraph extends StandardGraph {
336
338
  }
337
339
  }
338
340
 
339
- /** If agent has handoff destinations, add END to possible ends
340
- * If agent only has direct destinations, it naturally ends without explicit END
341
- */
342
- const destinations = new Set([...handoffDestinations]);
341
+ /** Check if this agent has BOTH handoff and direct edges */
342
+ const hasHandoffEdges = handoffDestinations.size > 0;
343
+ const hasDirectEdges = directDestinations.size > 0;
344
+ const needsCommandRouting = hasHandoffEdges && hasDirectEdges;
345
+
346
+ /** Collect all possible destinations for this agent */
347
+ const allDestinations = new Set([
348
+ ...handoffDestinations,
349
+ ...directDestinations,
350
+ ]);
343
351
  if (handoffDestinations.size > 0 || directDestinations.size === 0) {
344
- destinations.add(END);
352
+ allDestinations.add(END);
345
353
  }
346
354
 
347
355
  /** Agent subgraph (includes agent + tools) */
348
356
  const agentSubgraph = this.createAgentSubgraph(agentId);
349
357
 
350
- /** Wrapper function that handles agentMessages channel */
358
+ /** Wrapper function that handles agentMessages channel and conditional routing */
351
359
  const agentWrapper = async (
352
360
  state: t.MultiAgentGraphState
353
- ): Promise<t.MultiAgentGraphState> => {
361
+ ): Promise<t.MultiAgentGraphState | Command> => {
362
+ let result: t.MultiAgentGraphState;
363
+
354
364
  if (state.agentMessages != null && state.agentMessages.length > 0) {
365
+ /**
366
+ * When using agentMessages (excludeResults=true), we need to update
367
+ * the token map to account for the new prompt message
368
+ */
369
+ const agentContext = this.agentContexts.get(agentId);
370
+ if (agentContext && agentContext.tokenCounter) {
371
+ // The agentMessages contains:
372
+ // 1. Filtered messages (0 to startIndex) - already have token counts
373
+ // 2. New prompt message - needs token counting
374
+
375
+ const freshTokenMap: Record<string, number> = {};
376
+
377
+ // Copy existing token counts for filtered messages (0 to startIndex)
378
+ for (let i = 0; i < this.startIndex; i++) {
379
+ const tokenCount = agentContext.indexTokenCountMap[i];
380
+ if (tokenCount !== undefined) {
381
+ freshTokenMap[i] = tokenCount;
382
+ }
383
+ }
384
+
385
+ // Calculate tokens only for the new prompt message (last message)
386
+ const promptMessageIndex = state.agentMessages.length - 1;
387
+ if (promptMessageIndex >= this.startIndex) {
388
+ const promptMessage = state.agentMessages[promptMessageIndex];
389
+ freshTokenMap[promptMessageIndex] =
390
+ agentContext.tokenCounter(promptMessage);
391
+ }
392
+
393
+ // Update the agent's token map with instructions added
394
+ agentContext.updateTokenMapWithInstructions(freshTokenMap);
395
+ }
396
+
355
397
  /** Temporary state with messages replaced by `agentMessages` */
356
398
  const transformedState: t.MultiAgentGraphState = {
357
399
  ...state,
358
400
  messages: state.agentMessages,
359
401
  };
360
- const result = await agentSubgraph.invoke(transformedState);
361
- return {
402
+ result = await agentSubgraph.invoke(transformedState);
403
+ result = {
362
404
  ...result,
363
405
  /** Clear agentMessages for next agent */
364
406
  agentMessages: [],
365
407
  };
366
408
  } else {
367
- return await agentSubgraph.invoke(state);
409
+ result = await agentSubgraph.invoke(state);
410
+ }
411
+
412
+ /** If agent has both handoff and direct edges, use Command for exclusive routing */
413
+ if (needsCommandRouting) {
414
+ /** Check if a handoff occurred */
415
+ const lastMessage = result.messages[
416
+ result.messages.length - 1
417
+ ] as BaseMessage | null;
418
+ if (
419
+ lastMessage != null &&
420
+ lastMessage.getType() === 'tool' &&
421
+ typeof lastMessage.name === 'string' &&
422
+ lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)
423
+ ) {
424
+ /** Handoff occurred - extract destination and navigate there exclusively */
425
+ const handoffDest = lastMessage.name.replace(
426
+ Constants.LC_TRANSFER_TO_,
427
+ ''
428
+ );
429
+ return new Command({
430
+ update: result,
431
+ goto: handoffDest,
432
+ });
433
+ } else {
434
+ /** No handoff - proceed with direct edges */
435
+ const directDests = Array.from(directDestinations);
436
+ if (directDests.length === 1) {
437
+ return new Command({
438
+ update: result,
439
+ goto: directDests[0],
440
+ });
441
+ } else if (directDests.length > 1) {
442
+ /** Multiple direct destinations - they'll run in parallel */
443
+ return new Command({
444
+ update: result,
445
+ goto: directDests,
446
+ });
447
+ }
448
+ }
368
449
  }
450
+
451
+ /** No special routing needed - return state normally */
452
+ return result;
369
453
  };
370
454
 
371
455
  /** Wrapped agent as a node with its possible destinations */
372
456
  builder.addNode(agentId, agentWrapper, {
373
- ends: Array.from(destinations),
457
+ ends: Array.from(allDestinations),
374
458
  });
375
459
  }
376
460
 
@@ -482,10 +566,25 @@ export class MultiAgentGraph extends StandardGraph {
482
566
  /** @ts-ignore */
483
567
  builder.addEdge(wrapperNodeId, destination);
484
568
  } else {
485
- /** No prompt instructions, add direct edges */
569
+ /** No prompt instructions, add direct edges (skip if source uses Command routing) */
486
570
  for (const edge of edges) {
487
571
  const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
488
572
  for (const source of sources) {
573
+ /** Check if this source node has both handoff and direct edges */
574
+ const sourceHandoffEdges = this.handoffEdges.filter((e) => {
575
+ const eSources = Array.isArray(e.from) ? e.from : [e.from];
576
+ return eSources.includes(source);
577
+ });
578
+ const sourceDirectEdges = this.directEdges.filter((e) => {
579
+ const eSources = Array.isArray(e.from) ? e.from : [e.from];
580
+ return eSources.includes(source);
581
+ });
582
+
583
+ /** Skip adding edge if source uses Command routing (has both types) */
584
+ if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {
585
+ continue;
586
+ }
587
+
489
588
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
490
589
  /** @ts-ignore */
491
590
  builder.addEdge(source, destination);
@@ -0,0 +1,278 @@
1
+ import { config } from 'dotenv';
2
+ config();
3
+
4
+ import {
5
+ HumanMessage,
6
+ BaseMessage,
7
+ getBufferString,
8
+ } from '@langchain/core/messages';
9
+ import { Run } from '@/run';
10
+ import { Providers, GraphEvents } from '@/common';
11
+ import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
12
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
13
+ import type * as t from '@/types';
14
+
15
+ /**
16
+ * Helper function to create sequential chain edges with buffer string prompts
17
+ *
18
+ * @param agentIds - Array of agent IDs in order of execution
19
+ * @returns Array of edges configured for sequential chain with buffer prompts
20
+ */
21
+ function createSequentialChainEdges(agentIds: string[]): t.GraphEdge[] {
22
+ const edges: t.GraphEdge[] = [];
23
+
24
+ for (let i = 0; i < agentIds.length - 1; i++) {
25
+ const fromAgent = agentIds[i];
26
+ const toAgent = agentIds[i + 1];
27
+
28
+ edges.push({
29
+ from: fromAgent,
30
+ to: toAgent,
31
+ edgeType: 'direct',
32
+ // Use a prompt function to create the buffer string from all previous results
33
+ prompt: (messages: BaseMessage[], startIndex: number) => {
34
+ // Get only the messages from this run (after startIndex)
35
+ const runMessages = messages.slice(startIndex);
36
+
37
+ // Create buffer string from run messages
38
+ const bufferString = getBufferString(runMessages);
39
+
40
+ // Format the prompt for the next agent
41
+ return `Based on the following conversation and analysis from previous agents, please provide your insights:\n\n${bufferString}\n\nPlease add your specific expertise and perspective to this discussion.`;
42
+ },
43
+ // Critical: exclude previous results so only the prompt is passed
44
+ excludeResults: true,
45
+ description: `Sequential chain from ${fromAgent} to ${toAgent}`,
46
+ });
47
+ }
48
+
49
+ return edges;
50
+ }
51
+
52
+ const conversationHistory: BaseMessage[] = [];
53
+
54
+ /**
55
+ * Example of sequential agent chain mimicking the old chain behavior
56
+ *
57
+ * Graph structure:
58
+ * START -> researcher -> analyst -> reviewer -> summarizer -> END
59
+ *
60
+ * Each agent receives a buffer string of all previous results
61
+ */
62
+ async function testSequentialAgentChain() {
63
+ console.log('Testing Sequential Agent Chain (Old Chain Pattern)...\n');
64
+
65
+ // Set up content aggregator
66
+ const { contentParts, aggregateContent } = createContentAggregator();
67
+
68
+ // Define four agents with specific roles
69
+ const agents: t.AgentInputs[] = [
70
+ {
71
+ agentId: 'researcher',
72
+ provider: Providers.ANTHROPIC,
73
+ clientOptions: {
74
+ modelName: 'claude-3-5-sonnet-latest',
75
+ apiKey: process.env.ANTHROPIC_API_KEY,
76
+ },
77
+ instructions: `You are a Research Agent specializing in gathering initial information.
78
+ Your role is to:
79
+ 1. Identify key aspects of the user's query
80
+ 2. List important factors to consider
81
+ 3. Provide initial research findings
82
+
83
+ Format your response with clear sections and bullet points.
84
+ Start with "RESEARCH FINDINGS:" and be thorough but concise.`,
85
+ maxContextTokens: 8000,
86
+ },
87
+ {
88
+ agentId: 'analyst',
89
+ provider: Providers.ANTHROPIC,
90
+ clientOptions: {
91
+ modelName: 'claude-3-5-sonnet-latest',
92
+ apiKey: process.env.ANTHROPIC_API_KEY,
93
+ },
94
+ instructions: `You are an Analysis Agent that builds upon research findings.
95
+ Your role is to:
96
+ 1. Analyze the research provided by the previous agent
97
+ 2. Identify patterns, risks, and opportunities
98
+ 3. Provide deeper analytical insights
99
+
100
+ Start with "ANALYSIS:" and structure your response with clear categories.
101
+ Reference specific points from the research when relevant.`,
102
+ maxContextTokens: 8000,
103
+ },
104
+ {
105
+ agentId: 'reviewer',
106
+ provider: Providers.ANTHROPIC,
107
+ clientOptions: {
108
+ modelName: 'claude-3-5-sonnet-latest',
109
+ apiKey: process.env.ANTHROPIC_API_KEY,
110
+ },
111
+ instructions: `You are a Critical Review Agent that evaluates the work done so far.
112
+ Your role is to:
113
+ 1. Review the research and analysis from previous agents
114
+ 2. Identify any gaps or areas that need more attention
115
+ 3. Suggest improvements or additional considerations
116
+
117
+ Start with "CRITICAL REVIEW:" and be constructive in your feedback.
118
+ Highlight both strengths and areas for improvement.`,
119
+ maxContextTokens: 8000,
120
+ },
121
+ {
122
+ agentId: 'summarizer',
123
+ provider: Providers.ANTHROPIC,
124
+ clientOptions: {
125
+ modelName: 'claude-3-5-sonnet-latest',
126
+ apiKey: process.env.ANTHROPIC_API_KEY,
127
+ },
128
+ instructions: `You are a Summary Agent that creates the final comprehensive output.
129
+ Your role is to:
130
+ 1. Synthesize all insights from the researcher, analyst, and reviewer
131
+ 2. Create a cohesive, actionable summary
132
+ 3. Provide clear recommendations or conclusions
133
+
134
+ Start with "EXECUTIVE SUMMARY:" followed by key sections.
135
+ End with "KEY RECOMMENDATIONS:" or "CONCLUSIONS:" as appropriate.`,
136
+ maxContextTokens: 8000,
137
+ },
138
+ ];
139
+
140
+ // Create sequential chain edges using our helper function
141
+ const agentIds = agents.map((a) => a.agentId);
142
+ const edges = createSequentialChainEdges(agentIds);
143
+
144
+ // Track agent progression
145
+ let currentAgent = '';
146
+
147
+ // Create custom handlers
148
+ const customHandlers = {
149
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
150
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
151
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
152
+ [GraphEvents.ON_RUN_STEP]: {
153
+ handle: (
154
+ event: GraphEvents.ON_RUN_STEP,
155
+ data: t.StreamEventData
156
+ ): void => {
157
+ const runStepData = data as any;
158
+ if (runStepData?.name) {
159
+ currentAgent = runStepData.name;
160
+ console.log(`\n→ ${currentAgent} is processing...`);
161
+ }
162
+ aggregateContent({ event, data: data as t.RunStep });
163
+ },
164
+ },
165
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
166
+ handle: (
167
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
168
+ data: t.StreamEventData
169
+ ): void => {
170
+ const runStepData = data as any;
171
+ if (runStepData?.name) {
172
+ console.log(`✓ ${runStepData.name} completed`);
173
+ }
174
+ aggregateContent({
175
+ event,
176
+ data: data as unknown as { result: t.ToolEndEvent },
177
+ });
178
+ },
179
+ },
180
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
181
+ handle: (
182
+ event: GraphEvents.ON_RUN_STEP_DELTA,
183
+ data: t.StreamEventData
184
+ ): void => {
185
+ aggregateContent({ event, data: data as t.RunStepDeltaEvent });
186
+ },
187
+ },
188
+ [GraphEvents.ON_MESSAGE_DELTA]: {
189
+ handle: (
190
+ event: GraphEvents.ON_MESSAGE_DELTA,
191
+ data: t.StreamEventData
192
+ ): void => {
193
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
194
+ },
195
+ },
196
+ };
197
+
198
+ // Create multi-agent run configuration
199
+ const runConfig: t.RunConfig = {
200
+ runId: `sequential-chain-${Date.now()}`,
201
+ graphConfig: {
202
+ type: 'multi-agent',
203
+ agents,
204
+ edges,
205
+ },
206
+ customHandlers,
207
+ returnContent: true,
208
+ };
209
+
210
+ try {
211
+ // Create and execute the run
212
+ const run = await Run.create(runConfig);
213
+
214
+ // Test with a complex question that benefits from multiple perspectives
215
+ const userMessage =
216
+ 'I want to launch a new mobile app for personal finance management. What should I consider?';
217
+ conversationHistory.push(new HumanMessage(userMessage));
218
+
219
+ console.log(`User: "${userMessage}"\n`);
220
+ console.log('Starting sequential agent chain...\n');
221
+
222
+ const config = {
223
+ configurable: {
224
+ thread_id: 'sequential-chain-1',
225
+ },
226
+ streamMode: 'values',
227
+ version: 'v2' as const,
228
+ };
229
+
230
+ // Process with streaming
231
+ const inputs = {
232
+ messages: conversationHistory,
233
+ };
234
+
235
+ const finalContentParts = await run.processStream(inputs, config);
236
+ const finalMessages = run.getRunMessages();
237
+
238
+ if (finalMessages) {
239
+ conversationHistory.push(...finalMessages);
240
+ }
241
+
242
+ console.log('\n\n=== Final Output ===');
243
+ console.log('Sequential chain completed successfully!');
244
+ console.log(`Total content parts: ${contentParts.length}`);
245
+
246
+ // Display the buffer accumulation
247
+ console.log('\n=== Agent Outputs (Buffer Accumulation) ===');
248
+
249
+ const aiMessages = conversationHistory.filter(
250
+ (msg) => msg._getType() === 'ai'
251
+ );
252
+
253
+ aiMessages.forEach((msg, index) => {
254
+ console.log(`\n--- Agent ${index + 1}: ${agentIds[index]} ---`);
255
+ console.log(msg.content);
256
+
257
+ // Show buffer preview for next agent (except last)
258
+ if (index < aiMessages.length - 1) {
259
+ const bufferSoFar = getBufferString(aiMessages.slice(0, index + 1));
260
+ console.log(
261
+ `\n[Buffer passed to ${agentIds[index + 1]}]: ${bufferSoFar.slice(0, 150)}...`
262
+ );
263
+ }
264
+ });
265
+
266
+ // Demonstrate that each agent built upon previous results
267
+ console.log('\n=== Chain Analysis ===');
268
+ console.log('1. Researcher provided initial findings');
269
+ console.log('2. Analyst built upon research with deeper insights');
270
+ console.log('3. Reviewer critiqued and identified gaps');
271
+ console.log('4. Summarizer synthesized everything into actionable output');
272
+ } catch (error) {
273
+ console.error('Error in sequential agent chain test:', error);
274
+ }
275
+ }
276
+
277
+ // Run the test
278
+ testSequentialAgentChain();