@librechat/agents 3.0.0-rc1 → 3.0.0-rc10

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 (78) hide show
  1. package/dist/cjs/common/enum.cjs +1 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +0 -1
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/graphs/MultiAgentGraph.cjs +229 -44
  6. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  7. package/dist/cjs/llm/openai/index.cjs +33 -0
  8. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  9. package/dist/cjs/run.cjs +28 -15
  10. package/dist/cjs/run.cjs.map +1 -1
  11. package/dist/cjs/stream.cjs +1 -1
  12. package/dist/cjs/stream.cjs.map +1 -1
  13. package/dist/esm/common/enum.mjs +1 -0
  14. package/dist/esm/common/enum.mjs.map +1 -1
  15. package/dist/esm/graphs/Graph.mjs +0 -1
  16. package/dist/esm/graphs/Graph.mjs.map +1 -1
  17. package/dist/esm/graphs/MultiAgentGraph.mjs +230 -45
  18. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  19. package/dist/esm/llm/openai/index.mjs +33 -0
  20. package/dist/esm/llm/openai/index.mjs.map +1 -1
  21. package/dist/esm/run.mjs +28 -15
  22. package/dist/esm/run.mjs.map +1 -1
  23. package/dist/esm/stream.mjs +1 -1
  24. package/dist/esm/stream.mjs.map +1 -1
  25. package/dist/types/common/enum.d.ts +2 -1
  26. package/dist/types/graphs/MultiAgentGraph.d.ts +12 -2
  27. package/dist/types/llm/openai/index.d.ts +10 -0
  28. package/dist/types/run.d.ts +1 -1
  29. package/dist/types/types/graph.d.ts +38 -4
  30. package/dist/types/types/llm.d.ts +1 -0
  31. package/dist/types/types/run.d.ts +5 -1
  32. package/package.json +10 -2
  33. package/src/common/enum.ts +1 -0
  34. package/src/graphs/Graph.ts +0 -1
  35. package/src/graphs/MultiAgentGraph.ts +267 -50
  36. package/src/llm/openai/index.ts +41 -0
  37. package/src/run.ts +38 -27
  38. package/src/scripts/multi-agent-chain.ts +278 -0
  39. package/src/scripts/multi-agent-document-review-chain.ts +197 -0
  40. package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
  41. package/src/scripts/multi-agent-parallel.ts +27 -23
  42. package/src/scripts/multi-agent-supervisor.ts +362 -0
  43. package/src/scripts/test-custom-prompt-key.ts +145 -0
  44. package/src/scripts/test-handoff-input.ts +170 -0
  45. package/src/scripts/test-multi-agent-list-handoff.ts +261 -0
  46. package/src/scripts/test-tools-before-handoff.ts +233 -0
  47. package/src/stream.ts +4 -1
  48. package/src/types/graph.ts +51 -5
  49. package/src/types/llm.ts +1 -0
  50. package/src/types/run.ts +6 -1
  51. package/dist/types/scripts/abort.d.ts +0 -1
  52. package/dist/types/scripts/ant_web_search.d.ts +0 -1
  53. package/dist/types/scripts/args.d.ts +0 -7
  54. package/dist/types/scripts/caching.d.ts +0 -1
  55. package/dist/types/scripts/cli.d.ts +0 -1
  56. package/dist/types/scripts/cli2.d.ts +0 -1
  57. package/dist/types/scripts/cli3.d.ts +0 -1
  58. package/dist/types/scripts/cli4.d.ts +0 -1
  59. package/dist/types/scripts/cli5.d.ts +0 -1
  60. package/dist/types/scripts/code_exec.d.ts +0 -1
  61. package/dist/types/scripts/code_exec_files.d.ts +0 -1
  62. package/dist/types/scripts/code_exec_simple.d.ts +0 -1
  63. package/dist/types/scripts/content.d.ts +0 -1
  64. package/dist/types/scripts/empty_input.d.ts +0 -1
  65. package/dist/types/scripts/handoff-test.d.ts +0 -1
  66. package/dist/types/scripts/image.d.ts +0 -1
  67. package/dist/types/scripts/memory.d.ts +0 -1
  68. package/dist/types/scripts/multi-agent-conditional.d.ts +0 -1
  69. package/dist/types/scripts/multi-agent-parallel.d.ts +0 -1
  70. package/dist/types/scripts/multi-agent-sequence.d.ts +0 -1
  71. package/dist/types/scripts/multi-agent-test.d.ts +0 -1
  72. package/dist/types/scripts/search.d.ts +0 -1
  73. package/dist/types/scripts/simple.d.ts +0 -1
  74. package/dist/types/scripts/stream.d.ts +0 -1
  75. package/dist/types/scripts/thinking.d.ts +0 -1
  76. package/dist/types/scripts/tools.d.ts +0 -1
  77. package/dist/types/specs/spec.utils.d.ts +0 -1
  78. package/src/scripts/multi-agent-example-output.md +0 -110
@@ -0,0 +1,310 @@
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, Constants } 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 hybrid multi-agent system combining handoff and sequential patterns
15
+ *
16
+ * Graph structure:
17
+ * START -> primary_agent -> agent_b -> agent_c -> END
18
+ * |
19
+ * └─> standalone_agent -> END
20
+ *
21
+ * Because primary_agent has BOTH handoff and direct edges:
22
+ * - Uses Command-based routing for exclusive execution
23
+ * - The primary agent can either:
24
+ * 1. Handoff to standalone_agent (direct edge to agent_b is cancelled)
25
+ * 2. OR continue to agent_b -> agent_c (if no handoff occurs)
26
+ *
27
+ * This is automatic behavior when an agent has both edge types.
28
+ */
29
+ async function testHybridMultiAgent() {
30
+ console.log('Testing Hybrid Multi-Agent System (Sequential + Handoff)...\n');
31
+
32
+ // Define agents
33
+ const agents: t.AgentInputs[] = [
34
+ {
35
+ agentId: 'primary_agent',
36
+ provider: Providers.OPENAI,
37
+ clientOptions: {
38
+ modelName: 'gpt-4.1-mini',
39
+ apiKey: process.env.OPENAI_API_KEY,
40
+ },
41
+ instructions: `You are the Primary Agent in a hybrid workflow.
42
+
43
+ You have TWO options:
44
+ 1. If the request requires specialized expertise (complex analysis, deep technical knowledge, etc.),
45
+ use the "transfer_to_standalone_agent" tool to hand off to the Standalone Specialist
46
+ 2. If the request is straightforward and can be handled through standard processing,
47
+ just provide your initial response and it will automatically continue to Agent B
48
+
49
+ Be decisive - either handoff immediately or provide your response.
50
+ Start your response with "PRIMARY AGENT:" if you're handling it yourself.`,
51
+ maxContextTokens: 8000,
52
+ },
53
+ {
54
+ agentId: 'standalone_agent',
55
+ provider: Providers.OPENAI,
56
+ clientOptions: {
57
+ modelName: 'gpt-4.1',
58
+ apiKey: process.env.OPENAI_API_KEY,
59
+ },
60
+ instructions: `You are a Standalone Specialist Agent.
61
+ You only receive requests that require specialized expertise.
62
+
63
+ Provide a comprehensive, expert-level response to the request.
64
+ Start your response with "STANDALONE SPECIALIST:"
65
+ End with "Specialized analysis complete."`,
66
+ maxContextTokens: 8000,
67
+ },
68
+ {
69
+ agentId: 'agent_b',
70
+ provider: Providers.OPENAI,
71
+ clientOptions: {
72
+ modelName: 'gpt-4.1',
73
+ apiKey: process.env.OPENAI_API_KEY,
74
+ },
75
+ instructions: `You are Agent B in a sequential workflow.
76
+ You receive requests that the Primary Agent decided to handle through standard processing.
77
+
78
+ Your job is to:
79
+ 1. Build upon the Primary Agent's initial response
80
+ 2. Add additional processing or analysis (keep it brief, 2-3 sentences)
81
+ 3. Prepare the information for final processing by Agent C
82
+
83
+ Start your response with "AGENT B:" and end with "Passing to final processing..."`,
84
+ maxContextTokens: 8000,
85
+ },
86
+ {
87
+ agentId: 'agent_c',
88
+ provider: Providers.OPENAI,
89
+ clientOptions: {
90
+ modelName: 'gpt-4.1',
91
+ apiKey: process.env.OPENAI_API_KEY,
92
+ },
93
+ instructions: `You are Agent C, the final agent in the sequential workflow.
94
+
95
+ Your job is to:
96
+ 1. Review all previous processing from Primary Agent and Agent B
97
+ 2. Provide a final summary or conclusion
98
+ 3. Complete the standard workflow
99
+
100
+ Start your response with "AGENT C:" and end with "Standard workflow complete."`,
101
+ maxContextTokens: 8000,
102
+ },
103
+ ];
104
+
105
+ // Define edges combining handoff and direct patterns
106
+ const edges: t.GraphEdge[] = [
107
+ // Handoff edge: primary can transfer to standalone
108
+ {
109
+ from: 'primary_agent',
110
+ to: 'standalone_agent',
111
+ edgeType: 'handoff',
112
+ description: 'Transfer to standalone specialist for complex requests',
113
+ prompt: 'Specific instructions for the specialist',
114
+ },
115
+ // Direct edge - exclusive with handoffs (automatic when agent has both types)
116
+ {
117
+ from: 'primary_agent',
118
+ to: 'agent_b',
119
+ edgeType: 'direct',
120
+ description: 'Continue to Agent B only if no handoff occurs',
121
+ },
122
+ // Direct edge: agent_b automatically continues to agent_c
123
+ {
124
+ from: 'agent_b',
125
+ to: 'agent_c',
126
+ edgeType: 'direct',
127
+ description: 'Automatic progression from B to C',
128
+ },
129
+ ];
130
+
131
+ try {
132
+ // Test with different queries
133
+ const testQueries = [
134
+ {
135
+ query: 'What is the capital of France?',
136
+ expectedPath: 'sequential',
137
+ description: 'Simple query - should go through sequential flow',
138
+ },
139
+ // {
140
+ // query: 'Design a distributed microservices architecture for a real-time trading platform with sub-millisecond latency requirements',
141
+ // expectedPath: 'handoff',
142
+ // description: 'Complex query - should handoff to specialist',
143
+ // },
144
+ ];
145
+
146
+ const config = {
147
+ configurable: {
148
+ thread_id: 'hybrid-conversation-1',
149
+ },
150
+ streamMode: 'values',
151
+ version: 'v2' as const,
152
+ };
153
+
154
+ for (const test of testQueries) {
155
+ console.log(`\n${'='.repeat(70)}`);
156
+ console.log(`TEST: ${test.description}`);
157
+ console.log(`QUERY: "${test.query}"`);
158
+ console.log(`EXPECTED PATH: ${test.expectedPath}`);
159
+ console.log('='.repeat(70));
160
+
161
+ // Reset state
162
+ conversationHistory.length = 0;
163
+ conversationHistory.push(new HumanMessage(test.query));
164
+
165
+ // Create separate content aggregator for each test
166
+ const { contentParts, aggregateContent } = createContentAggregator();
167
+
168
+ // Track agent progression for this test
169
+ let currentAgent = '';
170
+ let handoffOccurred = false;
171
+
172
+ // Create custom handlers for this test
173
+ const customHandlers = {
174
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
175
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
176
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
177
+ [GraphEvents.ON_RUN_STEP]: {
178
+ handle: (
179
+ event: GraphEvents.ON_RUN_STEP,
180
+ data: t.StreamEventData
181
+ ): void => {
182
+ const runStepData = data as any;
183
+ if (runStepData?.name) {
184
+ currentAgent = runStepData.name;
185
+ console.log(`\n[${currentAgent}] Processing...`);
186
+ }
187
+ aggregateContent({ event, data: data as t.RunStep });
188
+ },
189
+ },
190
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
191
+ handle: (
192
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
193
+ data: t.StreamEventData
194
+ ): void => {
195
+ const runStepData = data as any;
196
+ if (runStepData?.name) {
197
+ console.log(`āœ“ ${runStepData.name} completed`);
198
+ }
199
+ aggregateContent({
200
+ event,
201
+ data: data as unknown as { result: t.ToolEndEvent },
202
+ });
203
+ },
204
+ },
205
+ [GraphEvents.ON_MESSAGE_DELTA]: {
206
+ handle: (
207
+ event: GraphEvents.ON_MESSAGE_DELTA,
208
+ data: t.StreamEventData
209
+ ): void => {
210
+ // console.dir(data, { depth: null });
211
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
212
+ },
213
+ },
214
+ [GraphEvents.TOOL_START]: {
215
+ handle: (
216
+ _event: string,
217
+ data: t.StreamEventData,
218
+ metadata?: Record<string, unknown>
219
+ ): void => {
220
+ const toolData = data as any;
221
+ if (toolData?.name?.startsWith(Constants.LC_TRANSFER_TO_)) {
222
+ const specialist = toolData.name.replace(
223
+ Constants.LC_TRANSFER_TO_,
224
+ ''
225
+ );
226
+ console.log(`\nšŸ”€ Transferring to ${specialist}...`);
227
+ handoffOccurred = true;
228
+ }
229
+ },
230
+ },
231
+ };
232
+
233
+ // Create a new run configuration for each test
234
+ const runConfig: t.RunConfig = {
235
+ runId: `hybrid-multi-agent-${test.expectedPath}-${Date.now()}`,
236
+ graphConfig: {
237
+ type: 'multi-agent',
238
+ agents,
239
+ edges,
240
+ },
241
+ customHandlers,
242
+ returnContent: true,
243
+ };
244
+
245
+ // Create and execute a new run for this test
246
+ const run = await Run.create(runConfig);
247
+
248
+ console.log('\nProcessing request...');
249
+
250
+ // Process with streaming
251
+ const inputs = {
252
+ messages: conversationHistory,
253
+ };
254
+
255
+ const finalContentParts = await run.processStream(inputs, config);
256
+ const finalMessages = run.getRunMessages();
257
+
258
+ if (finalMessages) {
259
+ conversationHistory.push(...finalMessages);
260
+ }
261
+
262
+ // Show path taken
263
+ console.log(`\n${'─'.repeat(70)}`);
264
+ console.log('PATH ANALYSIS:');
265
+ console.log(`- Query type: ${test.expectedPath}`);
266
+ console.log(`- Handoff occurred: ${handoffOccurred ? 'YES' : 'NO'}`);
267
+ console.log(
268
+ `- Sequential path runs: ${handoffOccurred ? 'NO (exclusive routing)' : 'YES'}`
269
+ );
270
+ console.log(
271
+ `- Result: ${
272
+ (test.expectedPath === 'handoff' &&
273
+ handoffOccurred &&
274
+ !test.query.includes('continue')) ||
275
+ (test.expectedPath === 'sequential' && !handoffOccurred)
276
+ ? 'āœ… CORRECT'
277
+ : 'āŒ INCORRECT'
278
+ }`
279
+ );
280
+ console.log('─'.repeat(70));
281
+
282
+ // Display the responses
283
+ const aiMessages = conversationHistory.filter(
284
+ (msg) => msg._getType() === 'ai'
285
+ );
286
+ console.log('\n--- Agent Responses ---');
287
+ aiMessages.forEach((msg, index) => {
288
+ console.log(`\nResponse ${index + 1}:`);
289
+ console.log(msg.content);
290
+ });
291
+ }
292
+
293
+ // Final summary
294
+ console.log(`\n${'='.repeat(70)}`);
295
+ console.log('HYBRID WORKFLOW TEST COMPLETE');
296
+ console.log('='.repeat(70));
297
+ console.log('\nThis test demonstrates automatic exclusive routing:');
298
+ console.log('- When an agent has BOTH handoff and direct edges');
299
+ console.log('- It uses Command-based routing for exclusive execution');
300
+ console.log('- Either handoff OR direct edges execute, never both');
301
+ console.log(
302
+ '\nThis prevents duplicate processing in delegation scenarios!'
303
+ );
304
+ } catch (error) {
305
+ console.error('Error in hybrid multi-agent test:', error);
306
+ }
307
+ }
308
+
309
+ // Run the test
310
+ testHybridMultiAgent();
@@ -167,29 +167,33 @@ async function testParallelMultiAgent() {
167
167
  description: 'Aggregate analysis results',
168
168
  edgeType: 'direct', // Fan-in is also direct
169
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
- },
170
+ // prompt: (messages, runStartIndex) => {
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(
174
+ // (msg, index) => msg.getType() === 'ai' && index >= runStartIndex
175
+ // );
176
+ // const messageContent = aiMessages.map((msg) => msg.content).join('\n');
177
+
178
+ // const hasFinancialAnalysis = messageContent.includes(
179
+ // 'FINANCIAL ANALYSIS:'
180
+ // );
181
+ // const hasTechnicalAnalysis = messageContent.includes(
182
+ // 'TECHNICAL ANALYSIS:'
183
+ // );
184
+ // const hasMarketAnalysis = messageContent.includes('MARKET ANALYSIS:');
185
+
186
+ // console.log(
187
+ // `Checking for analyses - Financial: ${hasFinancialAnalysis}, Technical: ${hasTechnicalAnalysis}, Market: ${hasMarketAnalysis}`
188
+ // );
189
+
190
+ // if (hasFinancialAnalysis && hasTechnicalAnalysis && hasMarketAnalysis) {
191
+ // 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.';
192
+ // }
193
+ // return undefined; // No prompt if we haven't received all analyst inputs
194
+ // },
195
+ prompt:
196
+ '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}',
193
197
  },
194
198
  ];
195
199