@librechat/agents 3.0.0-rc1 → 3.0.0-rc2

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.
@@ -0,0 +1,361 @@
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 supervisor-based multi-agent system
15
+ *
16
+ * The supervisor has handoff tools for 5 different specialists.
17
+ * To demonstrate the concept while respecting LangGraph constraints,
18
+ * we show two approaches:
19
+ *
20
+ * 1. All 5 specialists exist but share the same adaptive configuration
21
+ * 2. Only 2 agents total by using a single adaptive specialist (requires workaround)
22
+ */
23
+ async function testSupervisorMultiAgent() {
24
+ console.log('Testing Supervisor-Based Multi-Agent System...\n');
25
+
26
+ // NOTE: To truly have only 2 agents with 5 handoff tools, you would need:
27
+ // 1. Custom tool implementation (see multi-agent-supervisor-mock.ts)
28
+ // 2. Or modify MultiAgentGraph to support "virtual" agents
29
+ // 3. Or use a single conditional edge with role parameter
30
+ //
31
+ // This example shows the concept using 6 agents that share configuration
32
+
33
+ // Set up content aggregator
34
+ const { contentParts, aggregateContent } = createContentAggregator();
35
+
36
+ // Define configurations for all possible specialists
37
+ const specialistConfigs = {
38
+ data_analyst: {
39
+ provider: Providers.ANTHROPIC,
40
+ clientOptions: {
41
+ modelName: 'claude-3-5-sonnet-latest',
42
+ apiKey: process.env.ANTHROPIC_API_KEY,
43
+ },
44
+ instructions: `You are a Data Analyst specialist. Your expertise includes:
45
+ - Statistical analysis and data visualization
46
+ - SQL queries and database optimization
47
+ - Python/R for data science
48
+ - Machine learning model evaluation
49
+ - A/B testing and experiment design
50
+
51
+ Follow the supervisor's specific instructions carefully.`,
52
+ maxContextTokens: 8000,
53
+ },
54
+ security_expert: {
55
+ provider: Providers.ANTHROPIC,
56
+ clientOptions: {
57
+ modelName: 'claude-3-5-sonnet-latest',
58
+ apiKey: process.env.ANTHROPIC_API_KEY,
59
+ },
60
+ instructions: `You are a Security Expert. Your expertise includes:
61
+ - Cybersecurity best practices
62
+ - Vulnerability assessment and penetration testing
63
+ - Security architecture and threat modeling
64
+ - Compliance (GDPR, HIPAA, SOC2, etc.)
65
+ - Incident response and forensics
66
+
67
+ Follow the supervisor's specific instructions carefully.`,
68
+ maxContextTokens: 8000,
69
+ },
70
+ product_designer: {
71
+ provider: Providers.ANTHROPIC,
72
+ clientOptions: {
73
+ modelName: 'claude-3-5-sonnet-latest',
74
+ apiKey: process.env.ANTHROPIC_API_KEY,
75
+ },
76
+ instructions: `You are a Product Designer. Your expertise includes:
77
+ - User experience (UX) design principles
78
+ - User interface (UI) design and prototyping
79
+ - Design systems and component libraries
80
+ - User research and usability testing
81
+ - Accessibility and inclusive design
82
+
83
+ Follow the supervisor's specific instructions carefully.`,
84
+ maxContextTokens: 8000,
85
+ },
86
+ devops_engineer: {
87
+ provider: Providers.ANTHROPIC,
88
+ clientOptions: {
89
+ modelName: 'claude-3-5-sonnet-latest',
90
+ apiKey: process.env.ANTHROPIC_API_KEY,
91
+ },
92
+ instructions: `You are a DevOps Engineer. Your expertise includes:
93
+ - CI/CD pipeline design and optimization
94
+ - Infrastructure as Code (Terraform, CloudFormation)
95
+ - Container orchestration (Kubernetes, Docker)
96
+ - Cloud platforms (AWS, GCP, Azure)
97
+ - Monitoring, logging, and observability
98
+
99
+ Follow the supervisor's specific instructions carefully.`,
100
+ maxContextTokens: 8000,
101
+ },
102
+ legal_advisor: {
103
+ provider: Providers.ANTHROPIC,
104
+ clientOptions: {
105
+ modelName: 'claude-3-5-sonnet-latest',
106
+ apiKey: process.env.ANTHROPIC_API_KEY,
107
+ },
108
+ instructions: `You are a Legal Advisor specializing in technology. Your expertise includes:
109
+ - Software licensing and open source compliance
110
+ - Data privacy and protection laws
111
+ - Intellectual property and patents
112
+ - Contract review and negotiation
113
+ - Regulatory compliance for tech companies
114
+
115
+ Follow the supervisor's specific instructions carefully.`,
116
+ maxContextTokens: 8000,
117
+ },
118
+ };
119
+
120
+ // Track which specialist role was selected
121
+ let selectedRole = '';
122
+ let roleInstructions = '';
123
+
124
+ // Create custom handlers
125
+ const customHandlers = {
126
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
127
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
128
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
129
+ [GraphEvents.ON_RUN_STEP]: {
130
+ handle: (
131
+ event: GraphEvents.ON_RUN_STEP,
132
+ data: t.StreamEventData
133
+ ): void => {
134
+ const runStepData = data as any;
135
+ if (runStepData?.name) {
136
+ console.log(`\n[${runStepData.name}] Processing...`);
137
+ }
138
+ aggregateContent({ event, data: data as t.RunStep });
139
+ },
140
+ },
141
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
142
+ handle: (
143
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
144
+ data: t.StreamEventData
145
+ ): void => {
146
+ aggregateContent({
147
+ event,
148
+ data: data as unknown as { result: t.ToolEndEvent },
149
+ });
150
+ },
151
+ },
152
+ [GraphEvents.ON_MESSAGE_DELTA]: {
153
+ handle: (
154
+ event: GraphEvents.ON_MESSAGE_DELTA,
155
+ data: t.StreamEventData
156
+ ): void => {
157
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
158
+ },
159
+ },
160
+ [GraphEvents.TOOL_START]: {
161
+ handle: (
162
+ _event: string,
163
+ data: t.StreamEventData,
164
+ metadata?: Record<string, unknown>
165
+ ): void => {
166
+ const toolData = data as any;
167
+ if (toolData?.name?.includes('transfer_to_')) {
168
+ const specialist = toolData.name.replace('transfer_to_', '');
169
+ console.log(`\n🔀 Transferring to ${specialist}...`);
170
+ selectedRole = specialist;
171
+ }
172
+ },
173
+ },
174
+ };
175
+
176
+ // Function to create the graph with supervisor having multiple handoff options
177
+ function createSupervisorGraph(): t.RunConfig {
178
+ console.log(`\nCreating graph with supervisor and 5 specialist agents.`);
179
+ console.log('All specialists share the same adaptive configuration.\n');
180
+
181
+ // Define the adaptive specialist configuration that will be reused
182
+ const specialistConfig = {
183
+ provider: Providers.ANTHROPIC,
184
+ clientOptions: {
185
+ modelName: 'claude-3-5-sonnet-latest',
186
+ apiKey: process.env.ANTHROPIC_API_KEY,
187
+ },
188
+ instructions: `You are an Adaptive Specialist. Your agent ID indicates your role:
189
+
190
+ - data_analyst: Focus on statistical analysis, metrics, ML evaluation, A/B testing
191
+ - security_expert: Focus on cybersecurity, vulnerability assessment, compliance
192
+ - product_designer: Focus on UX/UI design, user research, accessibility
193
+ - devops_engineer: Focus on CI/CD, infrastructure, cloud platforms, monitoring
194
+ - legal_advisor: Focus on licensing, privacy laws, contracts, regulatory compliance
195
+
196
+ The supervisor will provide specific instructions. Follow them while maintaining your expert perspective.`,
197
+ maxContextTokens: 8000,
198
+ };
199
+
200
+ // Create the graph with supervisor and all 5 specialists
201
+ // All specialists share the same adaptive configuration
202
+ const agents: t.AgentInputs[] = [
203
+ {
204
+ agentId: 'supervisor',
205
+ provider: Providers.ANTHROPIC,
206
+ clientOptions: {
207
+ modelName: 'claude-3-5-sonnet-latest',
208
+ apiKey: process.env.ANTHROPIC_API_KEY,
209
+ },
210
+ instructions: `You are a Task Supervisor with access to 5 specialist agents:
211
+ 1. transfer_to_data_analyst - For statistical analysis and metrics
212
+ 2. transfer_to_security_expert - For cybersecurity and vulnerability assessment
213
+ 3. transfer_to_product_designer - For UX/UI design
214
+ 4. transfer_to_devops_engineer - For infrastructure and deployment
215
+ 5. transfer_to_legal_advisor - For compliance and licensing
216
+
217
+ Your role is to:
218
+ 1. Analyze the incoming request
219
+ 2. Decide which specialist is best suited
220
+ 3. Use the appropriate transfer tool (e.g., transfer_to_data_analyst)
221
+ 4. Provide specific instructions to guide their work
222
+
223
+ Be specific about what you need from the specialist.`,
224
+ maxContextTokens: 8000,
225
+ },
226
+ // Include all 5 specialists with the same adaptive configuration
227
+ {
228
+ agentId: 'data_analyst',
229
+ ...specialistConfig,
230
+ },
231
+ {
232
+ agentId: 'security_expert',
233
+ ...specialistConfig,
234
+ },
235
+ {
236
+ agentId: 'product_designer',
237
+ ...specialistConfig,
238
+ },
239
+ {
240
+ agentId: 'devops_engineer',
241
+ ...specialistConfig,
242
+ },
243
+ {
244
+ agentId: 'legal_advisor',
245
+ ...specialistConfig,
246
+ },
247
+ ];
248
+
249
+ // Create edges from supervisor to all 5 specialists
250
+ const edges: t.GraphEdge[] = [
251
+ {
252
+ from: 'supervisor',
253
+ to: 'data_analyst',
254
+ description:
255
+ 'Transfer to data analyst for statistical analysis and metrics',
256
+ edgeType: 'handoff',
257
+ },
258
+ {
259
+ from: 'supervisor',
260
+ to: 'security_expert',
261
+ description: 'Transfer to security expert for cybersecurity assessment',
262
+ edgeType: 'handoff',
263
+ },
264
+ {
265
+ from: 'supervisor',
266
+ to: 'product_designer',
267
+ description: 'Transfer to product designer for UX/UI design',
268
+ edgeType: 'handoff',
269
+ },
270
+ {
271
+ from: 'supervisor',
272
+ to: 'devops_engineer',
273
+ description:
274
+ 'Transfer to DevOps engineer for infrastructure and deployment',
275
+ edgeType: 'handoff',
276
+ },
277
+ {
278
+ from: 'supervisor',
279
+ to: 'legal_advisor',
280
+ description: 'Transfer to legal advisor for compliance and licensing',
281
+ edgeType: 'handoff',
282
+ },
283
+ ];
284
+
285
+ return {
286
+ runId: `supervisor-multi-agent-${Date.now()}`,
287
+ graphConfig: {
288
+ type: 'multi-agent',
289
+ agents,
290
+ edges,
291
+ },
292
+ customHandlers,
293
+ returnContent: true,
294
+ };
295
+ }
296
+
297
+ try {
298
+ // Test with different queries
299
+ const testQueries = [
300
+ 'How can we analyze user engagement metrics to improve our product?',
301
+ 'What security measures should we implement for our new API?',
302
+ 'Can you help design a better onboarding flow for our mobile app?',
303
+ 'We need to set up a CI/CD pipeline for our microservices.',
304
+ 'What are the legal implications of using GPL-licensed code in our product?',
305
+ ];
306
+
307
+ const config = {
308
+ configurable: {
309
+ thread_id: 'supervisor-conversation-1',
310
+ },
311
+ streamMode: 'values',
312
+ version: 'v2' as const,
313
+ };
314
+
315
+ for (const query of testQueries) {
316
+ console.log(`\n${'='.repeat(60)}`);
317
+ console.log(`USER QUERY: "${query}"`);
318
+ console.log('='.repeat(60));
319
+
320
+ // Reset conversation
321
+ conversationHistory.length = 0;
322
+ conversationHistory.push(new HumanMessage(query));
323
+
324
+ // Create graph with supervisor having 5 handoff tools to 1 adaptive specialist
325
+ const runConfig = createSupervisorGraph();
326
+ const run = await Run.create(runConfig);
327
+
328
+ console.log('Processing request...');
329
+
330
+ // Process with streaming
331
+ const inputs = {
332
+ messages: conversationHistory,
333
+ };
334
+
335
+ const finalContentParts = await run.processStream(inputs, config);
336
+ const finalMessages = run.getRunMessages();
337
+
338
+ if (finalMessages) {
339
+ conversationHistory.push(...finalMessages);
340
+ }
341
+
342
+ // Show summary
343
+ console.log(`\n${'─'.repeat(60)}`);
344
+ console.log(`Agents in graph: 6 total (supervisor + 5 specialists)`);
345
+ console.log(`All specialists share the same adaptive configuration`);
346
+ console.log(
347
+ `Supervisor tools: transfer_to_data_analyst, transfer_to_security_expert,`
348
+ );
349
+ console.log(
350
+ ` transfer_to_product_designer, transfer_to_devops_engineer,`
351
+ );
352
+ console.log(` transfer_to_legal_advisor`);
353
+ console.log('─'.repeat(60));
354
+ }
355
+ } catch (error) {
356
+ console.error('Error in supervisor multi-agent test:', error);
357
+ }
358
+ }
359
+
360
+ // Run the test
361
+ testSupervisorMultiAgent();
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { config } from 'dotenv';
4
+ config();
5
+
6
+ import { HumanMessage } from '@langchain/core/messages';
7
+ import { Run } from '@/run';
8
+ import { Providers } from '@/common';
9
+ import type * as t from '@/types';
10
+
11
+ /**
12
+ * Test the custom promptKey feature for handoff edges
13
+ * This demonstrates how to use custom parameter names instead of "instructions"
14
+ */
15
+ async function testCustomPromptKey() {
16
+ console.log('Testing Custom Prompt Key Feature...\n');
17
+
18
+ const runConfig: t.RunConfig = {
19
+ runId: `test-custom-prompt-key-${Date.now()}`,
20
+ graphConfig: {
21
+ type: 'multi-agent',
22
+ agents: [
23
+ {
24
+ agentId: 'supervisor',
25
+ provider: Providers.ANTHROPIC,
26
+ clientOptions: {
27
+ modelName: 'claude-3-5-sonnet-latest',
28
+ apiKey: process.env.ANTHROPIC_API_KEY,
29
+ },
30
+ instructions: `You are a Task Supervisor managing different agents:
31
+
32
+ 1. transfer_to_researcher - For research tasks (uses "query" parameter)
33
+ 2. transfer_to_designer - For design tasks (uses "requirements" parameter)
34
+ 3. transfer_to_coder - For coding tasks (uses "specification" parameter)
35
+
36
+ Each agent expects different parameter names in their handoff tools.
37
+ Pay attention to the parameter names when calling each tool.`,
38
+ maxContextTokens: 8000,
39
+ },
40
+ {
41
+ agentId: 'researcher',
42
+ provider: Providers.ANTHROPIC,
43
+ clientOptions: {
44
+ modelName: 'claude-3-5-sonnet-latest',
45
+ apiKey: process.env.ANTHROPIC_API_KEY,
46
+ },
47
+ instructions: `You are a Research Agent. You receive research queries to investigate.
48
+ Look for the "Query:" field in the transfer message.`,
49
+ maxContextTokens: 8000,
50
+ },
51
+ {
52
+ agentId: 'designer',
53
+ provider: Providers.ANTHROPIC,
54
+ clientOptions: {
55
+ modelName: 'claude-3-5-sonnet-latest',
56
+ apiKey: process.env.ANTHROPIC_API_KEY,
57
+ },
58
+ instructions: `You are a Design Agent. You receive design requirements to implement.
59
+ Look for the "Requirements:" field in the transfer message.`,
60
+ maxContextTokens: 8000,
61
+ },
62
+ {
63
+ agentId: 'coder',
64
+ provider: Providers.ANTHROPIC,
65
+ clientOptions: {
66
+ modelName: 'claude-3-5-sonnet-latest',
67
+ apiKey: process.env.ANTHROPIC_API_KEY,
68
+ },
69
+ instructions: `You are a Coding Agent. You receive technical specifications to implement.
70
+ Look for the "Specification:" field in the transfer message.`,
71
+ maxContextTokens: 8000,
72
+ },
73
+ ],
74
+ edges: [
75
+ {
76
+ from: 'supervisor',
77
+ to: 'researcher',
78
+ edgeType: 'handoff',
79
+ // Custom parameter name: "query"
80
+ prompt: 'The research question or topic to investigate',
81
+ promptKey: 'query',
82
+ },
83
+ {
84
+ from: 'supervisor',
85
+ to: 'designer',
86
+ edgeType: 'handoff',
87
+ // Custom parameter name: "requirements"
88
+ prompt: 'The design requirements and constraints',
89
+ promptKey: 'requirements',
90
+ },
91
+ {
92
+ from: 'supervisor',
93
+ to: 'coder',
94
+ edgeType: 'handoff',
95
+ // Custom parameter name: "specification"
96
+ prompt: 'The technical specification for the code to implement',
97
+ promptKey: 'specification',
98
+ },
99
+ ],
100
+ },
101
+ };
102
+
103
+ const run = await Run.create(runConfig);
104
+
105
+ // Test queries for different agents
106
+ const testQueries = [
107
+ // 'Research the latest trends in sustainable energy storage technologies',
108
+ 'Design a mobile app interface for a fitness tracking application',
109
+ // 'Write a Python function that calculates the Fibonacci sequence recursively',
110
+ ];
111
+
112
+ const config = {
113
+ configurable: {
114
+ thread_id: 'custom-prompt-key-test-1',
115
+ },
116
+ streamMode: 'values',
117
+ version: 'v2' as const,
118
+ };
119
+
120
+ for (const query of testQueries) {
121
+ console.log(`\n${'='.repeat(60)}`);
122
+ console.log(`USER QUERY: "${query}"`);
123
+ console.log('='.repeat(60));
124
+
125
+ const inputs = {
126
+ messages: [new HumanMessage(query)],
127
+ };
128
+
129
+ await run.processStream(inputs, config);
130
+
131
+ console.log(`\n${'─'.repeat(60)}`);
132
+ console.log('Each agent receives instructions via their custom parameter:');
133
+ console.log('- Researcher expects "query"');
134
+ console.log('- Designer expects "requirements"');
135
+ console.log('- Coder expects "specification"');
136
+ console.log('─'.repeat(60));
137
+ }
138
+
139
+ console.log('\n\nDemonstration complete!');
140
+ console.log('The promptKey feature allows for more semantic parameter names');
141
+ console.log('that better match the domain and purpose of each agent.');
142
+ }
143
+
144
+ // Run the test
145
+ testCustomPromptKey().catch(console.error);
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { config } from 'dotenv';
4
+ config();
5
+
6
+ import { HumanMessage } from '@langchain/core/messages';
7
+ import { Run } from '@/run';
8
+ import { Providers } from '@/common';
9
+ import type * as t from '@/types';
10
+
11
+ /**
12
+ * Test the new handoff input feature using the prompt field
13
+ * This demonstrates how supervisors can pass specific instructions to specialists
14
+ */
15
+ async function testHandoffInput() {
16
+ console.log('Testing Handoff Input Feature...\n');
17
+
18
+ const runConfig: t.RunConfig = {
19
+ runId: `test-handoff-input-${Date.now()}`,
20
+ graphConfig: {
21
+ type: 'multi-agent',
22
+ agents: [
23
+ {
24
+ agentId: 'supervisor',
25
+ provider: Providers.ANTHROPIC,
26
+ clientOptions: {
27
+ modelName: 'claude-3-5-sonnet-latest',
28
+ apiKey: process.env.ANTHROPIC_API_KEY,
29
+ },
30
+ instructions: `You are a Task Supervisor. You have access to two specialist agents:
31
+
32
+ 1. transfer_to_analyst - For data analysis tasks
33
+ 2. transfer_to_writer - For content creation tasks
34
+
35
+ When transferring to a specialist, you MUST provide specific instructions
36
+ in the tool call to guide their work. Be detailed about what you need.`,
37
+ maxContextTokens: 8000,
38
+ },
39
+ {
40
+ agentId: 'analyst',
41
+ provider: Providers.ANTHROPIC,
42
+ clientOptions: {
43
+ modelName: 'claude-3-5-sonnet-latest',
44
+ apiKey: process.env.ANTHROPIC_API_KEY,
45
+ },
46
+ instructions: `You are a Data Analyst. Follow the supervisor's instructions carefully.
47
+ When you receive instructions, acknowledge them and perform the requested analysis.`,
48
+ maxContextTokens: 8000,
49
+ },
50
+ {
51
+ agentId: 'writer',
52
+ provider: Providers.ANTHROPIC,
53
+ clientOptions: {
54
+ modelName: 'claude-3-5-sonnet-latest',
55
+ apiKey: process.env.ANTHROPIC_API_KEY,
56
+ },
57
+ instructions: `You are a Content Writer. Follow the supervisor's instructions carefully.
58
+ When you receive instructions, acknowledge them and create the requested content.`,
59
+ maxContextTokens: 8000,
60
+ },
61
+ ],
62
+ edges: [
63
+ {
64
+ from: 'supervisor',
65
+ to: ['analyst', 'writer'],
66
+ edgeType: 'handoff',
67
+ // This prompt field now serves as the description for the input parameter
68
+ prompt:
69
+ 'Specific instructions for the specialist to follow. Be detailed about what analysis to perform, what data to focus on, or what content to create.',
70
+ },
71
+ ],
72
+ },
73
+ };
74
+
75
+ const run = await Run.create(runConfig);
76
+
77
+ // Test queries that should result in different handoffs with specific instructions
78
+ const testQueries = [
79
+ 'Analyze our Q4 sales data and identify the top 3 performing products',
80
+ 'Write a blog post about the benefits of remote work for software developers',
81
+ ];
82
+
83
+ const config = {
84
+ configurable: {
85
+ thread_id: 'handoff-input-test-1',
86
+ },
87
+ streamMode: 'values',
88
+ version: 'v2' as const,
89
+ };
90
+
91
+ for (const query of testQueries) {
92
+ console.log(`\n${'='.repeat(60)}`);
93
+ console.log(`USER QUERY: "${query}"`);
94
+ console.log('='.repeat(60));
95
+
96
+ const inputs = {
97
+ messages: [new HumanMessage(query)],
98
+ };
99
+
100
+ await run.processStream(inputs, config);
101
+
102
+ console.log(`\n${'─'.repeat(60)}`);
103
+ console.log('Notice how the supervisor passes specific instructions');
104
+ console.log('to the specialist through the handoff tool input parameter.');
105
+ console.log('─'.repeat(60));
106
+ }
107
+ }
108
+
109
+ // Run the test
110
+ testHandoffInput().catch(console.error);