@librechat/agents 3.0.63 → 3.0.65

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.
@@ -254,6 +254,8 @@ IMPORTANT: You are the specialist - provide a complete, helpful response to the
254
254
  console.log(' - Specialist received and acted on instructions');
255
255
  console.log(' - No premature end tokens after handoff');
256
256
  console.log(' - Multi-turn conversation continued smoothly');
257
+
258
+ console.dir(contentParts, { depth: null });
257
259
  }
258
260
 
259
261
  process.on('unhandledRejection', (reason, promise) => {
@@ -0,0 +1,291 @@
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 } 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
+ * Test parallel handoffs - where an LLM calls multiple transfer tools simultaneously
16
+ *
17
+ * Graph structure:
18
+ * coordinator -> [researcher, writer] (via parallel handoff tools)
19
+ *
20
+ * The coordinator agent has two transfer tools:
21
+ * - transfer_to_researcher
22
+ * - transfer_to_writer
23
+ *
24
+ * When given a task that needs both, it should call both tools in parallel.
25
+ */
26
+ async function testParallelHandoffs() {
27
+ console.log(
28
+ 'Testing Parallel Handoffs (LLM calling multiple transfers)...\n'
29
+ );
30
+
31
+ const { contentParts, aggregateContent } = createContentAggregator();
32
+
33
+ const agents: t.AgentInputs[] = [
34
+ {
35
+ agentId: 'coordinator',
36
+ provider: Providers.OPENAI,
37
+ clientOptions: {
38
+ modelName: 'gpt-4o-mini',
39
+ apiKey: process.env.OPENAI_API_KEY,
40
+ },
41
+ instructions: `You are a COORDINATOR agent. Your job is to delegate tasks to specialized agents.
42
+
43
+ You have access to two transfer tools:
44
+ - transfer_to_researcher: For research and fact-finding tasks
45
+ - transfer_to_writer: For content creation and writing tasks
46
+
47
+ IMPORTANT: When a task requires BOTH research AND writing, you MUST call BOTH transfer tools SIMULTANEOUSLY in the same response. Do not call them sequentially.
48
+
49
+ For example, if asked to "research and write about X", call both transfers at once to enable parallel work.
50
+
51
+ When delegating, provide clear instructions to each agent about what they should do.`,
52
+ },
53
+ {
54
+ agentId: 'researcher',
55
+ provider: Providers.ANTHROPIC,
56
+ clientOptions: {
57
+ modelName: 'claude-haiku-4-5',
58
+ apiKey: process.env.ANTHROPIC_API_KEY,
59
+ },
60
+ instructions: `You are a RESEARCHER. When you receive a task:
61
+ 1. Provide concise research findings (100-150 words)
62
+ 2. Start your response with "📚 RESEARCH FINDINGS:"`,
63
+ },
64
+ {
65
+ agentId: 'writer',
66
+ provider: Providers.ANTHROPIC,
67
+ clientOptions: {
68
+ modelName: 'claude-haiku-4-5',
69
+ apiKey: process.env.ANTHROPIC_API_KEY,
70
+ },
71
+ instructions: `You are a WRITER. When you receive a task:
72
+ 1. Provide creative content (100-150 words)
73
+ 2. Start your response with "✍️ WRITTEN CONTENT:"`,
74
+ },
75
+ ];
76
+
77
+ /**
78
+ * Create handoff edges from coordinator to both researcher and writer.
79
+ * These are separate edges so the LLM sees both transfer tools.
80
+ */
81
+ const edges: t.GraphEdge[] = [
82
+ {
83
+ from: 'coordinator',
84
+ to: 'researcher',
85
+ edgeType: 'handoff',
86
+ description: 'Transfer to researcher for research and fact-finding tasks',
87
+ prompt: 'Research task instructions',
88
+ },
89
+ {
90
+ from: 'coordinator',
91
+ to: 'writer',
92
+ edgeType: 'handoff',
93
+ description: 'Transfer to writer for content creation and writing tasks',
94
+ prompt: 'Writing task instructions',
95
+ },
96
+ ];
97
+
98
+ /** Track which agents are active and their timing */
99
+ const activeAgents = new Set<string>();
100
+ const agentTimings: Record<string, { start?: number; end?: number }> = {};
101
+ const startTime = Date.now();
102
+
103
+ const customHandlers = {
104
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
105
+ [GraphEvents.CHAT_MODEL_END]: {
106
+ handle: (
107
+ _event: string,
108
+ _data: t.StreamEventData,
109
+ metadata?: Record<string, unknown>
110
+ ): void => {
111
+ const nodeName = metadata?.langgraph_node as string;
112
+ if (nodeName) {
113
+ const elapsed = Date.now() - startTime;
114
+ agentTimings[nodeName] = agentTimings[nodeName] || {};
115
+ agentTimings[nodeName].end = elapsed;
116
+ activeAgents.delete(nodeName);
117
+ console.log(`\n⏱️ [${nodeName}] COMPLETED at ${elapsed}ms`);
118
+ }
119
+ },
120
+ },
121
+ [GraphEvents.CHAT_MODEL_START]: {
122
+ handle: (
123
+ _event: string,
124
+ _data: t.StreamEventData,
125
+ metadata?: Record<string, unknown>
126
+ ): void => {
127
+ const nodeName = metadata?.langgraph_node as string;
128
+ if (nodeName) {
129
+ const elapsed = Date.now() - startTime;
130
+ /** Store first start time for parallel overlap calculation */
131
+ if (!agentTimings[nodeName]?.start) {
132
+ agentTimings[nodeName] = agentTimings[nodeName] || {};
133
+ agentTimings[nodeName].start = elapsed;
134
+ }
135
+ activeAgents.add(nodeName);
136
+ console.log(`\n⏱️ [${nodeName}] STARTED at ${elapsed}ms`);
137
+ console.log(
138
+ ` Active agents: ${Array.from(activeAgents).join(', ')}`
139
+ );
140
+ }
141
+ },
142
+ },
143
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
144
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
145
+ handle: (
146
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
147
+ data: t.StreamEventData
148
+ ): void => {
149
+ aggregateContent({
150
+ event,
151
+ data: data as unknown as { result: t.ToolEndEvent },
152
+ });
153
+ },
154
+ },
155
+ [GraphEvents.ON_RUN_STEP]: {
156
+ handle: (
157
+ event: GraphEvents.ON_RUN_STEP,
158
+ data: t.StreamEventData
159
+ ): void => {
160
+ aggregateContent({ event, data: data as t.RunStep });
161
+ },
162
+ },
163
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
164
+ handle: (
165
+ event: GraphEvents.ON_RUN_STEP_DELTA,
166
+ data: t.StreamEventData
167
+ ): void => {
168
+ aggregateContent({ event, data: data as t.RunStepDeltaEvent });
169
+ },
170
+ },
171
+ [GraphEvents.ON_MESSAGE_DELTA]: {
172
+ handle: (
173
+ event: GraphEvents.ON_MESSAGE_DELTA,
174
+ data: t.StreamEventData
175
+ ): void => {
176
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
177
+ },
178
+ },
179
+ };
180
+
181
+ const runConfig: t.RunConfig = {
182
+ runId: `parallel-handoffs-${Date.now()}`,
183
+ graphConfig: {
184
+ type: 'multi-agent',
185
+ agents,
186
+ edges,
187
+ },
188
+ customHandlers,
189
+ returnContent: true,
190
+ };
191
+
192
+ try {
193
+ const run = await Run.create(runConfig);
194
+
195
+ /** Prompt designed to trigger parallel handoffs without confusing language */
196
+ const userMessage = `Help me with two topics:
197
+ 1. The history of the internet
198
+ 2. A short poem about technology
199
+
200
+ I need information on both topics.`;
201
+
202
+ conversationHistory.push(new HumanMessage(userMessage));
203
+
204
+ console.log('User message:', userMessage);
205
+ console.log(
206
+ '\nInvoking multi-agent graph with parallel handoff request...\n'
207
+ );
208
+
209
+ const config = {
210
+ configurable: {
211
+ thread_id: 'parallel-handoffs-test-1',
212
+ },
213
+ streamMode: 'values',
214
+ version: 'v2' as const,
215
+ };
216
+
217
+ const inputs = {
218
+ messages: conversationHistory,
219
+ };
220
+
221
+ await run.processStream(inputs, config);
222
+ const finalMessages = run.getRunMessages();
223
+
224
+ if (finalMessages) {
225
+ conversationHistory.push(...finalMessages);
226
+ }
227
+
228
+ /** Analyze parallel execution */
229
+ console.log('\n\n========== TIMING SUMMARY ==========');
230
+ console.log('Available timing keys:', Object.keys(agentTimings));
231
+ for (const [agent, timing] of Object.entries(agentTimings)) {
232
+ const duration =
233
+ timing.end && timing.start ? timing.end - timing.start : 'N/A';
234
+ console.log(
235
+ `${agent}: started=${timing.start}ms, ended=${timing.end}ms, duration=${duration}ms`
236
+ );
237
+ }
238
+
239
+ /** Check if researcher and writer ran in parallel (handle key variations) */
240
+ const researcherKey = Object.keys(agentTimings).find((k) =>
241
+ k.includes('researcher')
242
+ );
243
+ const writerKey = Object.keys(agentTimings).find((k) =>
244
+ k.includes('writer')
245
+ );
246
+ const researcherTiming = researcherKey
247
+ ? agentTimings[researcherKey]
248
+ : undefined;
249
+ const writerTiming = writerKey ? agentTimings[writerKey] : undefined;
250
+
251
+ if (researcherTiming && writerTiming) {
252
+ const bothStarted = researcherTiming.start && writerTiming.start;
253
+ const bothEnded = researcherTiming.end && writerTiming.end;
254
+
255
+ if (bothStarted && bothEnded) {
256
+ const overlap =
257
+ Math.min(researcherTiming.end!, writerTiming.end!) -
258
+ Math.max(researcherTiming.start!, writerTiming.start!);
259
+
260
+ if (overlap > 0) {
261
+ console.log(
262
+ `\n✅ PARALLEL HANDOFFS SUCCESSFUL: ${overlap}ms overlap between researcher and writer`
263
+ );
264
+ } else {
265
+ console.log(
266
+ `\n⚠️ SEQUENTIAL EXECUTION: researcher and writer did not overlap`
267
+ );
268
+ console.log(
269
+ ` This may indicate the LLM called transfers sequentially, not in parallel`
270
+ );
271
+ }
272
+ }
273
+ } else {
274
+ console.log(
275
+ '\n⚠️ Not all agents were invoked. Check if handoffs occurred.'
276
+ );
277
+ console.log(' researcher timing:', researcherTiming);
278
+ console.log(' writer timing:', writerTiming);
279
+ }
280
+ console.log('====================================\n');
281
+
282
+ console.log('Final content parts:', contentParts.length, 'parts');
283
+ console.dir(contentParts, { depth: null });
284
+ await sleep(3000);
285
+ } catch (error) {
286
+ console.error('Error in parallel handoffs test:', error);
287
+ throw error;
288
+ }
289
+ }
290
+
291
+ testParallelHandoffs();
@@ -281,6 +281,13 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
281
281
  )[] = [];
282
282
  let parentCommand: Command | null = null;
283
283
 
284
+ /**
285
+ * Collect handoff commands (Commands with string goto and Command.PARENT)
286
+ * for potential parallel handoff aggregation
287
+ */
288
+ const handoffCommands: Command[] = [];
289
+ const nonCommandOutputs: BaseMessage[] = [];
290
+
284
291
  for (const output of outputs) {
285
292
  if (isCommand(output)) {
286
293
  if (
@@ -297,24 +304,66 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
297
304
  goto: output.goto,
298
305
  });
299
306
  }
300
- } else {
307
+ } else if (output.graph === Command.PARENT) {
301
308
  /**
302
- * Non-Send Commands (including handoff Commands with string goto)
303
- * are passed through as-is. For single handoffs, this works correctly.
304
- *
305
- * Note: Parallel handoffs (LLM calling multiple transfer tools simultaneously)
306
- * are not yet fully supported. For parallel agent execution, use direct edges
307
- * with edgeType: 'direct' instead of handoff edges.
309
+ * Handoff Command with destination.
310
+ * Handle both string ('agent') and array (['agent']) formats.
311
+ * Collect for potential parallel aggregation.
308
312
  */
313
+ const goto = output.goto;
314
+ const isSingleStringDest = typeof goto === 'string';
315
+ const isSingleArrayDest =
316
+ Array.isArray(goto) &&
317
+ goto.length === 1 &&
318
+ typeof goto[0] === 'string';
319
+
320
+ if (isSingleStringDest || isSingleArrayDest) {
321
+ handoffCommands.push(output);
322
+ } else {
323
+ /** Multi-destination or other command - pass through */
324
+ combinedOutputs.push(output);
325
+ }
326
+ } else {
327
+ /** Other commands - pass through */
309
328
  combinedOutputs.push(output);
310
329
  }
311
330
  } else {
331
+ nonCommandOutputs.push(output);
312
332
  combinedOutputs.push(
313
333
  Array.isArray(input) ? [output] : { messages: [output] }
314
334
  );
315
335
  }
316
336
  }
317
337
 
338
+ /**
339
+ * Handle handoff commands - convert to Send objects for parallel execution
340
+ * when multiple handoffs are requested
341
+ */
342
+ if (handoffCommands.length > 1) {
343
+ /**
344
+ * Multiple parallel handoffs - convert to Send objects.
345
+ * Each Send carries its own state with the appropriate messages.
346
+ * This enables LLM-initiated parallel execution when calling multiple
347
+ * transfer tools simultaneously.
348
+ */
349
+ const sends = handoffCommands.map((cmd) => {
350
+ /** Extract destination - handle both string and array formats */
351
+ const goto = cmd.goto;
352
+ const destination =
353
+ typeof goto === 'string' ? goto : (goto as string[])[0];
354
+ return new Send(destination, cmd.update);
355
+ });
356
+
357
+ const parallelCommand = new Command({
358
+ graph: Command.PARENT,
359
+ goto: sends,
360
+ });
361
+ combinedOutputs.push(parallelCommand);
362
+ } else if (handoffCommands.length === 1) {
363
+ /** Single handoff - pass through as-is */
364
+ combinedOutputs.push(handoffCommands[0]);
365
+ }
366
+
318
367
  if (parentCommand) {
319
368
  combinedOutputs.push(parentCommand);
320
369
  }
@@ -357,6 +357,8 @@ export type MultiAgentGraphInput = StandardGraphInput & {
357
357
 
358
358
  export interface AgentInputs {
359
359
  agentId: string;
360
+ /** Human-readable name for the agent (used in handoff context). Defaults to agentId if not provided. */
361
+ name?: string;
360
362
  toolEnd?: boolean;
361
363
  toolMap?: ToolMap;
362
364
  tools?: GraphTools;