@librechat/agents 3.0.36 → 3.0.40
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.
- package/dist/cjs/agents/AgentContext.cjs +71 -2
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +3 -0
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +5 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +12 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +329 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +34 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearchRegex.cjs +455 -0
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +71 -2
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +4 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +5 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +324 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +34 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +448 -0
- package/dist/esm/tools/ToolSearchRegex.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +25 -1
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +2 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/test/mockTools.d.ts +28 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +86 -0
- package/dist/types/tools/ToolNode.d.ts +7 -1
- package/dist/types/tools/ToolSearchRegex.d.ts +80 -0
- package/dist/types/types/graph.d.ts +7 -1
- package/dist/types/types/tools.d.ts +136 -0
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +86 -0
- package/src/common/enum.ts +2 -0
- package/src/events.ts +5 -1
- package/src/graphs/Graph.ts +6 -0
- package/src/index.ts +2 -0
- package/src/scripts/code_exec_ptc.ts +277 -0
- package/src/scripts/programmatic_exec.ts +396 -0
- package/src/scripts/programmatic_exec_agent.ts +231 -0
- package/src/scripts/tool_search_regex.ts +162 -0
- package/src/test/mockTools.ts +366 -0
- package/src/tools/ProgrammaticToolCalling.ts +423 -0
- package/src/tools/ToolNode.ts +38 -4
- package/src/tools/ToolSearchRegex.ts +535 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +318 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +613 -0
- package/src/tools/__tests__/ToolSearchRegex.integration.test.ts +161 -0
- package/src/tools/__tests__/ToolSearchRegex.test.ts +232 -0
- package/src/types/graph.ts +7 -1
- package/src/types/tools.ts +166 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// src/scripts/programmatic_exec.ts
|
|
2
|
+
/**
|
|
3
|
+
* Test script for Programmatic Tool Calling (PTC).
|
|
4
|
+
* Run with: npm run programmatic_exec
|
|
5
|
+
*
|
|
6
|
+
* Demonstrates:
|
|
7
|
+
* 1. Runtime toolMap injection - the tool map is passed at invocation time
|
|
8
|
+
* 2. Tool classification with allowed_callers (inspired by Anthropic's API)
|
|
9
|
+
* - 'direct': Tool can only be called directly by the LLM (default)
|
|
10
|
+
* - 'code_execution': Tool can only be called from within PTC
|
|
11
|
+
* - Both: Tool can be called either way
|
|
12
|
+
*
|
|
13
|
+
* IMPORTANT: The Python code passed to PTC should NOT define the tool functions.
|
|
14
|
+
* The Code API automatically generates async function stubs from the tool definitions.
|
|
15
|
+
* The code should just CALL the tools as if they're already available:
|
|
16
|
+
* - result = await get_weather(city="SF")
|
|
17
|
+
* - results = await asyncio.gather(tool1(), tool2())
|
|
18
|
+
*/
|
|
19
|
+
import { config } from 'dotenv';
|
|
20
|
+
config();
|
|
21
|
+
|
|
22
|
+
import type { StructuredToolInterface } from '@langchain/core/tools';
|
|
23
|
+
import type { LCTool, ToolMap } from '@/types';
|
|
24
|
+
import { createProgrammaticToolCallingTool } from '@/tools/ProgrammaticToolCalling';
|
|
25
|
+
import {
|
|
26
|
+
createGetTeamMembersTool,
|
|
27
|
+
createGetExpensesTool,
|
|
28
|
+
createGetWeatherTool,
|
|
29
|
+
createCalculatorTool,
|
|
30
|
+
createProgrammaticToolRegistry,
|
|
31
|
+
} from '@/test/mockTools';
|
|
32
|
+
|
|
33
|
+
// ============================================================================
|
|
34
|
+
// Test Runner
|
|
35
|
+
// ============================================================================
|
|
36
|
+
|
|
37
|
+
interface RunTestOptions {
|
|
38
|
+
toolMap: ToolMap;
|
|
39
|
+
tools?: LCTool[];
|
|
40
|
+
session_id?: string;
|
|
41
|
+
timeout?: number;
|
|
42
|
+
showArtifact?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function runTest(
|
|
46
|
+
ptcTool: ReturnType<typeof createProgrammaticToolCallingTool>,
|
|
47
|
+
testName: string,
|
|
48
|
+
code: string,
|
|
49
|
+
options: RunTestOptions
|
|
50
|
+
): Promise<void> {
|
|
51
|
+
console.log(`\n${'='.repeat(70)}`);
|
|
52
|
+
console.log(`TEST: ${testName}`);
|
|
53
|
+
console.log('='.repeat(70));
|
|
54
|
+
console.log('\nCode:');
|
|
55
|
+
console.log('```python');
|
|
56
|
+
console.log(code.trim());
|
|
57
|
+
console.log('```\n');
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const startTime = Date.now();
|
|
61
|
+
|
|
62
|
+
// Manual testing: schema params + extras (LangChain moves extras to config.toolCall)
|
|
63
|
+
const result = await ptcTool.invoke({
|
|
64
|
+
code,
|
|
65
|
+
tools: options.tools,
|
|
66
|
+
session_id: options.session_id,
|
|
67
|
+
timeout: options.timeout,
|
|
68
|
+
toolMap: options.toolMap, // Non-schema field → config.toolCall.toolMap
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const duration = Date.now() - startTime;
|
|
72
|
+
|
|
73
|
+
console.log(`Result (${duration}ms):`);
|
|
74
|
+
if (Array.isArray(result)) {
|
|
75
|
+
console.log(result[0]);
|
|
76
|
+
if (options.showArtifact) {
|
|
77
|
+
console.log('\n--- Artifact ---');
|
|
78
|
+
console.dir(result[1], { depth: null });
|
|
79
|
+
}
|
|
80
|
+
} else {
|
|
81
|
+
console.log(result);
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
console.error('Error:', error instanceof Error ? error.message : error);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ============================================================================
|
|
89
|
+
// Main
|
|
90
|
+
// ============================================================================
|
|
91
|
+
|
|
92
|
+
async function main(): Promise<void> {
|
|
93
|
+
console.log('Programmatic Tool Calling (PTC) - Test Script');
|
|
94
|
+
console.log('==============================================');
|
|
95
|
+
console.log('Demonstrating runtime toolMap injection\n');
|
|
96
|
+
|
|
97
|
+
const apiKey = process.env.LIBRECHAT_CODE_API_KEY;
|
|
98
|
+
if (!apiKey) {
|
|
99
|
+
console.error(
|
|
100
|
+
'Error: LIBRECHAT_CODE_API_KEY environment variable is not set.'
|
|
101
|
+
);
|
|
102
|
+
console.log('Please set it in your .env file or environment.');
|
|
103
|
+
process.exit(1);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
console.log('Creating mock tools...');
|
|
107
|
+
const mockTools: StructuredToolInterface[] = [
|
|
108
|
+
createGetTeamMembersTool(),
|
|
109
|
+
createGetExpensesTool(),
|
|
110
|
+
createGetWeatherTool(),
|
|
111
|
+
createCalculatorTool(),
|
|
112
|
+
];
|
|
113
|
+
|
|
114
|
+
const toolMap: ToolMap = new Map(mockTools.map((t) => [t.name, t]));
|
|
115
|
+
const toolDefinitions = Array.from(createProgrammaticToolRegistry().values());
|
|
116
|
+
|
|
117
|
+
console.log(
|
|
118
|
+
`ToolMap contains ${toolMap.size} tools: ${Array.from(toolMap.keys()).join(', ')}`
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
console.log('\nCreating PTC tool (without toolMap)...');
|
|
122
|
+
const ptcTool = createProgrammaticToolCallingTool({ apiKey });
|
|
123
|
+
console.log('PTC tool created successfully!');
|
|
124
|
+
console.log(
|
|
125
|
+
'Note: toolMap will be passed at runtime with each invocation.\n'
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
const baseOptions = { toolMap, tools: toolDefinitions };
|
|
129
|
+
|
|
130
|
+
// =========================================================================
|
|
131
|
+
// Test 1: Simple async tool call
|
|
132
|
+
// =========================================================================
|
|
133
|
+
await runTest(
|
|
134
|
+
ptcTool,
|
|
135
|
+
'Simple async tool call',
|
|
136
|
+
`
|
|
137
|
+
# Tools are auto-generated as async functions - just await them
|
|
138
|
+
result = await get_weather(city="San Francisco")
|
|
139
|
+
print(f"Weather in SF: {result['temperature']}°F, {result['condition']}")
|
|
140
|
+
`,
|
|
141
|
+
{ ...baseOptions, showArtifact: true }
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
// =========================================================================
|
|
145
|
+
// Test 2: Sequential loop with await
|
|
146
|
+
// =========================================================================
|
|
147
|
+
await runTest(
|
|
148
|
+
ptcTool,
|
|
149
|
+
'Sequential loop - Process team expenses',
|
|
150
|
+
`
|
|
151
|
+
# Each tool call uses await
|
|
152
|
+
team = await get_team_members()
|
|
153
|
+
print("Team expense report:")
|
|
154
|
+
print("-" * 30)
|
|
155
|
+
total = 0
|
|
156
|
+
for member in team:
|
|
157
|
+
expenses = await get_expenses(user_id=member['id'])
|
|
158
|
+
member_total = sum(e['amount'] for e in expenses)
|
|
159
|
+
total += member_total
|
|
160
|
+
print(f"{member['name']}: \${member_total:.2f}")
|
|
161
|
+
print("-" * 30)
|
|
162
|
+
print(f"Total: \${total:.2f}")
|
|
163
|
+
`,
|
|
164
|
+
baseOptions
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
// =========================================================================
|
|
168
|
+
// Test 3: Parallel execution with asyncio.gather
|
|
169
|
+
// =========================================================================
|
|
170
|
+
await runTest(
|
|
171
|
+
ptcTool,
|
|
172
|
+
'Parallel execution - Weather for multiple cities',
|
|
173
|
+
`
|
|
174
|
+
# Use asyncio.gather for parallel tool calls - single round-trip!
|
|
175
|
+
import asyncio
|
|
176
|
+
|
|
177
|
+
cities = ["San Francisco", "New York", "London"]
|
|
178
|
+
results = await asyncio.gather(*[
|
|
179
|
+
get_weather(city=city)
|
|
180
|
+
for city in cities
|
|
181
|
+
])
|
|
182
|
+
|
|
183
|
+
print("Weather report:")
|
|
184
|
+
for city, weather in zip(cities, results):
|
|
185
|
+
print(f" {city}: {weather['temperature']}°F, {weather['condition']}")
|
|
186
|
+
`,
|
|
187
|
+
baseOptions
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
// =========================================================================
|
|
191
|
+
// Test 4: Chained dependencies
|
|
192
|
+
// =========================================================================
|
|
193
|
+
await runTest(
|
|
194
|
+
ptcTool,
|
|
195
|
+
'Chained dependencies - Get team then process each',
|
|
196
|
+
`
|
|
197
|
+
# Get team first, then fetch expenses for each
|
|
198
|
+
team = await get_team_members()
|
|
199
|
+
engineering = [m for m in team if m['department'] == 'Engineering']
|
|
200
|
+
|
|
201
|
+
print(f"Engineering team ({len(engineering)} members):")
|
|
202
|
+
for member in engineering:
|
|
203
|
+
expenses = await get_expenses(user_id=member['id'])
|
|
204
|
+
equipment = sum(e['amount'] for e in expenses if e['category'] == 'equipment')
|
|
205
|
+
print(f" {member['name']}: \${equipment:.2f} on equipment")
|
|
206
|
+
`,
|
|
207
|
+
baseOptions
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
// =========================================================================
|
|
211
|
+
// Test 5: Conditional logic
|
|
212
|
+
// =========================================================================
|
|
213
|
+
await runTest(
|
|
214
|
+
ptcTool,
|
|
215
|
+
'Conditional logic - Find high spenders',
|
|
216
|
+
`
|
|
217
|
+
team = await get_team_members()
|
|
218
|
+
high_spenders = []
|
|
219
|
+
|
|
220
|
+
for member in team:
|
|
221
|
+
expenses = await get_expenses(user_id=member['id'])
|
|
222
|
+
total = sum(e['amount'] for e in expenses)
|
|
223
|
+
if total > 300:
|
|
224
|
+
high_spenders.append((member['name'], total))
|
|
225
|
+
|
|
226
|
+
if high_spenders:
|
|
227
|
+
print("High spenders (over $300):")
|
|
228
|
+
for name, amount in sorted(high_spenders, key=lambda x: x[1], reverse=True):
|
|
229
|
+
print(f" {name}: \${amount:.2f}")
|
|
230
|
+
else:
|
|
231
|
+
print("No high spenders found.")
|
|
232
|
+
`,
|
|
233
|
+
baseOptions
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
// =========================================================================
|
|
237
|
+
// Test 6: Mixed parallel and sequential
|
|
238
|
+
// =========================================================================
|
|
239
|
+
await runTest(
|
|
240
|
+
ptcTool,
|
|
241
|
+
'Mixed - Parallel expense fetch after sequential team fetch',
|
|
242
|
+
`
|
|
243
|
+
import asyncio
|
|
244
|
+
|
|
245
|
+
# Step 1: Get team (one tool call)
|
|
246
|
+
team = await get_team_members()
|
|
247
|
+
print(f"Fetched {len(team)} team members")
|
|
248
|
+
|
|
249
|
+
# Step 2: Get all expenses in parallel (single round-trip for all!)
|
|
250
|
+
all_expenses = await asyncio.gather(*[
|
|
251
|
+
get_expenses(user_id=member['id'])
|
|
252
|
+
for member in team
|
|
253
|
+
])
|
|
254
|
+
|
|
255
|
+
# Step 3: Process and output
|
|
256
|
+
print("\\nExpense summary:")
|
|
257
|
+
for member, expenses in zip(team, all_expenses):
|
|
258
|
+
total = sum(e['amount'] for e in expenses)
|
|
259
|
+
print(f" {member['name']}: \${total:.2f} ({len(expenses)} items)")
|
|
260
|
+
`,
|
|
261
|
+
baseOptions
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
// =========================================================================
|
|
265
|
+
// Test 7: Calculator usage
|
|
266
|
+
// =========================================================================
|
|
267
|
+
await runTest(
|
|
268
|
+
ptcTool,
|
|
269
|
+
'Calculator tool usage',
|
|
270
|
+
`
|
|
271
|
+
# All tools are async - use await
|
|
272
|
+
result1 = await calculator(expression="2 + 2 * 3")
|
|
273
|
+
result2 = await calculator(expression="(10 + 5) / 3")
|
|
274
|
+
|
|
275
|
+
print(f"2 + 2 * 3 = {result1['result']}")
|
|
276
|
+
print(f"(10 + 5) / 3 = {result2['result']:.2f}")
|
|
277
|
+
`,
|
|
278
|
+
baseOptions
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
// =========================================================================
|
|
282
|
+
// Test 8: Error handling in code
|
|
283
|
+
// =========================================================================
|
|
284
|
+
await runTest(
|
|
285
|
+
ptcTool,
|
|
286
|
+
'Error handling - Invalid city',
|
|
287
|
+
`
|
|
288
|
+
# Tool errors become Python exceptions - handle with try/except
|
|
289
|
+
cities = ["San Francisco", "InvalidCity", "New York"]
|
|
290
|
+
|
|
291
|
+
for city in cities:
|
|
292
|
+
try:
|
|
293
|
+
weather = await get_weather(city=city)
|
|
294
|
+
print(f"{city}: {weather['temperature']}°F")
|
|
295
|
+
except Exception as e:
|
|
296
|
+
print(f"{city}: Error - {e}")
|
|
297
|
+
`,
|
|
298
|
+
baseOptions
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
// =========================================================================
|
|
302
|
+
// Test 9: Early termination
|
|
303
|
+
// =========================================================================
|
|
304
|
+
await runTest(
|
|
305
|
+
ptcTool,
|
|
306
|
+
'Early termination - Stop when condition met',
|
|
307
|
+
`
|
|
308
|
+
# Stop as soon as we find what we need - no wasted tool calls
|
|
309
|
+
team = await get_team_members()
|
|
310
|
+
|
|
311
|
+
for member in team:
|
|
312
|
+
expenses = await get_expenses(user_id=member['id'])
|
|
313
|
+
if any(e['category'] == 'equipment' for e in expenses):
|
|
314
|
+
print(f"First team member with equipment expense: {member['name']}")
|
|
315
|
+
equipment_total = sum(e['amount'] for e in expenses if e['category'] == 'equipment')
|
|
316
|
+
print(f"Equipment total: \${equipment_total:.2f}")
|
|
317
|
+
break
|
|
318
|
+
else:
|
|
319
|
+
print("No team member has equipment expenses")
|
|
320
|
+
`,
|
|
321
|
+
baseOptions
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
// =========================================================================
|
|
325
|
+
// Test 10: Subset of tools
|
|
326
|
+
// =========================================================================
|
|
327
|
+
await runTest(
|
|
328
|
+
ptcTool,
|
|
329
|
+
'Subset of tools - Only weather',
|
|
330
|
+
`
|
|
331
|
+
# Only the weather tool is available in this execution
|
|
332
|
+
import asyncio
|
|
333
|
+
|
|
334
|
+
sf, nyc = await asyncio.gather(
|
|
335
|
+
get_weather(city="San Francisco"),
|
|
336
|
+
get_weather(city="New York")
|
|
337
|
+
)
|
|
338
|
+
print(f"SF: {sf['temperature']}°F vs NYC: {nyc['temperature']}°F")
|
|
339
|
+
difference = abs(sf['temperature'] - nyc['temperature'])
|
|
340
|
+
print(f"Temperature difference: {difference}°F")
|
|
341
|
+
`,
|
|
342
|
+
{
|
|
343
|
+
...baseOptions,
|
|
344
|
+
tools: [toolDefinitions.find((t) => t.name === 'get_weather')!],
|
|
345
|
+
}
|
|
346
|
+
);
|
|
347
|
+
|
|
348
|
+
// =========================================================================
|
|
349
|
+
// Test 11: Note about ToolNode injection
|
|
350
|
+
// =========================================================================
|
|
351
|
+
console.log(`\n${'='.repeat(70)}`);
|
|
352
|
+
console.log('NOTE: ToolNode Runtime Injection');
|
|
353
|
+
console.log('='.repeat(70));
|
|
354
|
+
console.log(
|
|
355
|
+
'\nWhen PTC is invoked through ToolNode in a real agent:\n' +
|
|
356
|
+
'- ToolNode detects call.name === "programmatic_code_execution"\n' +
|
|
357
|
+
'- ToolNode injects: { ...invokeParams, toolMap, programmaticToolDefs }\n' +
|
|
358
|
+
'- PTC tool extracts these from params (not from config)\n' +
|
|
359
|
+
'- No explicit tools parameter needed in schema\n\n' +
|
|
360
|
+
'This test demonstrates param injection with explicit tools:\n'
|
|
361
|
+
);
|
|
362
|
+
|
|
363
|
+
await runTest(
|
|
364
|
+
ptcTool,
|
|
365
|
+
'Runtime injection with explicit tools',
|
|
366
|
+
`
|
|
367
|
+
# ToolNode would inject toolMap+programmaticToolDefs
|
|
368
|
+
# For this test, we pass tools explicitly (same effect)
|
|
369
|
+
team = await get_team_members()
|
|
370
|
+
print(f"Team size: {len(team)}")
|
|
371
|
+
for member in team:
|
|
372
|
+
print(f"- {member['name']} ({member['department']})")
|
|
373
|
+
`,
|
|
374
|
+
baseOptions
|
|
375
|
+
);
|
|
376
|
+
|
|
377
|
+
console.log('\n' + '='.repeat(70));
|
|
378
|
+
console.log('All tests completed!');
|
|
379
|
+
console.log('='.repeat(70) + '\n');
|
|
380
|
+
console.log('Summary of allowed_callers patterns:');
|
|
381
|
+
console.log(
|
|
382
|
+
'- get_team_members, get_expenses, calculator: code_execution only'
|
|
383
|
+
);
|
|
384
|
+
console.log('- get_weather: both direct and code_execution');
|
|
385
|
+
console.log(
|
|
386
|
+
'\nIn a real agent setup, the LLM would only see tools with allowed_callers'
|
|
387
|
+
);
|
|
388
|
+
console.log(
|
|
389
|
+
'including "direct", while PTC can call any tool with "code_execution".\n'
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
main().catch((err) => {
|
|
394
|
+
console.error('Fatal error:', err);
|
|
395
|
+
process.exit(1);
|
|
396
|
+
});
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// src/scripts/programmatic_exec_agent.ts
|
|
2
|
+
/**
|
|
3
|
+
* Test script for Programmatic Tool Calling (PTC) with agent integration.
|
|
4
|
+
* Run with: npm run programmatic_exec_agent
|
|
5
|
+
*
|
|
6
|
+
* Demonstrates:
|
|
7
|
+
* 1. Tool classification with allowed_callers:
|
|
8
|
+
* - direct: Tool bound to LLM (can be called directly)
|
|
9
|
+
* - code_execution: Tool available for PTC (not bound to LLM)
|
|
10
|
+
* - Both: Tool bound to LLM AND available for PTC
|
|
11
|
+
* 2. Deferred loading with defer_loading: true (for tool search)
|
|
12
|
+
* 3. Agent-level tool configuration via toolRegistry
|
|
13
|
+
* 4. ToolNode runtime injection of programmatic tools
|
|
14
|
+
*
|
|
15
|
+
* This shows the real-world integration pattern with agents.
|
|
16
|
+
*/
|
|
17
|
+
import { config } from 'dotenv';
|
|
18
|
+
config();
|
|
19
|
+
|
|
20
|
+
import type { StructuredToolInterface } from '@langchain/core/tools';
|
|
21
|
+
import { HumanMessage, BaseMessage } from '@langchain/core/messages';
|
|
22
|
+
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
23
|
+
import type * as t from '@/types';
|
|
24
|
+
import { createCodeExecutionTool } from '@/tools/CodeExecutor';
|
|
25
|
+
import { createProgrammaticToolCallingTool } from '@/tools/ProgrammaticToolCalling';
|
|
26
|
+
import { createToolSearchRegexTool } from '@/tools/ToolSearchRegex';
|
|
27
|
+
import { getLLMConfig } from '@/utils/llmConfig';
|
|
28
|
+
import { getArgs } from '@/scripts/args';
|
|
29
|
+
import { Run } from '@/run';
|
|
30
|
+
import {
|
|
31
|
+
createGetTeamMembersTool,
|
|
32
|
+
createGetExpensesTool,
|
|
33
|
+
createGetWeatherTool,
|
|
34
|
+
createProgrammaticToolRegistry,
|
|
35
|
+
} from '@/test/mockTools';
|
|
36
|
+
|
|
37
|
+
// ============================================================================
|
|
38
|
+
// Tool Registry (Metadata)
|
|
39
|
+
// ============================================================================
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Tool registry only needs business logic tools that require filtering.
|
|
43
|
+
* Special tools (execute_code, programmatic_code_execution, tool_search_regex)
|
|
44
|
+
* are always bound directly to the LLM and don't need registry entries.
|
|
45
|
+
*/
|
|
46
|
+
function createAgentToolRegistry(): t.LCToolRegistry {
|
|
47
|
+
// Use shared programmatic tool registry (get_team_members, get_expenses, etc.)
|
|
48
|
+
return createProgrammaticToolRegistry();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ============================================================================
|
|
52
|
+
// Main
|
|
53
|
+
// ============================================================================
|
|
54
|
+
|
|
55
|
+
const conversationHistory: BaseMessage[] = [];
|
|
56
|
+
|
|
57
|
+
async function main(): Promise<void> {
|
|
58
|
+
console.log('Programmatic Tool Calling - Agent Integration Test');
|
|
59
|
+
console.log('===================================================\n');
|
|
60
|
+
|
|
61
|
+
const { userName, location, provider } = await getArgs();
|
|
62
|
+
const llmConfig = getLLMConfig(provider);
|
|
63
|
+
|
|
64
|
+
// Create all tool instances
|
|
65
|
+
const mockTools: StructuredToolInterface[] = [
|
|
66
|
+
createGetTeamMembersTool(),
|
|
67
|
+
createGetExpensesTool(),
|
|
68
|
+
createGetWeatherTool(),
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
const toolMap = new Map(mockTools.map((t) => [t.name, t]));
|
|
72
|
+
|
|
73
|
+
// Create special tools (PTC, code execution, tool search)
|
|
74
|
+
const codeExecTool = createCodeExecutionTool();
|
|
75
|
+
const ptcTool = createProgrammaticToolCallingTool();
|
|
76
|
+
const toolSearchTool = createToolSearchRegexTool();
|
|
77
|
+
|
|
78
|
+
// Build complete tool list and map
|
|
79
|
+
const allTools = [...mockTools, codeExecTool, ptcTool, toolSearchTool];
|
|
80
|
+
const completeToolMap = new Map(allTools.map((t) => [t.name, t]));
|
|
81
|
+
|
|
82
|
+
// Create tool registry with allowed_callers configuration
|
|
83
|
+
// Only includes business logic tools (not special tools like execute_code, PTC, tool_search)
|
|
84
|
+
const toolRegistry = createAgentToolRegistry();
|
|
85
|
+
|
|
86
|
+
console.log('Tool configuration:');
|
|
87
|
+
console.log('- Total tools:', allTools.length);
|
|
88
|
+
console.log(
|
|
89
|
+
'- Programmatic-allowed:',
|
|
90
|
+
Array.from(toolRegistry.values())
|
|
91
|
+
.filter((t) => t.allowed_callers?.includes('code_execution'))
|
|
92
|
+
.map((t) => t.name)
|
|
93
|
+
.join(', ')
|
|
94
|
+
);
|
|
95
|
+
console.log(
|
|
96
|
+
'- Direct-only:',
|
|
97
|
+
Array.from(toolRegistry.values())
|
|
98
|
+
.filter(
|
|
99
|
+
(t) =>
|
|
100
|
+
!t.allowed_callers ||
|
|
101
|
+
(t.allowed_callers.includes('direct') &&
|
|
102
|
+
!t.allowed_callers.includes('code_execution'))
|
|
103
|
+
)
|
|
104
|
+
.map((t) => t.name)
|
|
105
|
+
.join(', ')
|
|
106
|
+
);
|
|
107
|
+
console.log(
|
|
108
|
+
'- Both:',
|
|
109
|
+
Array.from(toolRegistry.values())
|
|
110
|
+
.filter(
|
|
111
|
+
(t) =>
|
|
112
|
+
t.allowed_callers?.includes('direct') &&
|
|
113
|
+
t.allowed_callers?.includes('code_execution')
|
|
114
|
+
)
|
|
115
|
+
.map((t) => t.name)
|
|
116
|
+
.join(', ')
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
// Create run with toolRegistry configuration
|
|
120
|
+
const run = await Run.create<t.IState>({
|
|
121
|
+
runId: 'ptc-agent-test',
|
|
122
|
+
graphConfig: {
|
|
123
|
+
type: 'standard',
|
|
124
|
+
llmConfig,
|
|
125
|
+
agents: [
|
|
126
|
+
{
|
|
127
|
+
agentId: 'default',
|
|
128
|
+
provider: llmConfig.provider,
|
|
129
|
+
clientOptions: llmConfig,
|
|
130
|
+
tools: allTools,
|
|
131
|
+
toolMap: completeToolMap,
|
|
132
|
+
toolRegistry, // Pass tool registry for programmatic/deferred tool config
|
|
133
|
+
instructions:
|
|
134
|
+
'You are an AI assistant with access to programmatic tool calling. ' +
|
|
135
|
+
'When you need to process multiple items or perform complex data operations, ' +
|
|
136
|
+
'use the programmatic_code_execution tool to write Python code that calls tools efficiently.',
|
|
137
|
+
},
|
|
138
|
+
],
|
|
139
|
+
},
|
|
140
|
+
returnContent: true,
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const config: Partial<RunnableConfig> & {
|
|
144
|
+
version: 'v1' | 'v2';
|
|
145
|
+
streamMode: string;
|
|
146
|
+
} = {
|
|
147
|
+
configurable: {
|
|
148
|
+
provider,
|
|
149
|
+
thread_id: 'ptc-test-conversation',
|
|
150
|
+
},
|
|
151
|
+
streamMode: 'values',
|
|
152
|
+
version: 'v2',
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
console.log('\n' + '='.repeat(70));
|
|
156
|
+
console.log('Test: Process team expenses using PTC');
|
|
157
|
+
console.log('='.repeat(70) + '\n');
|
|
158
|
+
|
|
159
|
+
const userMessage = new HumanMessage(
|
|
160
|
+
`Hi! I need you to analyze our team's expenses. Please:
|
|
161
|
+
1. Get the list of team members
|
|
162
|
+
2. For each member, get their expense records
|
|
163
|
+
3. Calculate the total expenses per member
|
|
164
|
+
4. Identify anyone who spent more than $300
|
|
165
|
+
5. Show me the results in a nice format
|
|
166
|
+
|
|
167
|
+
Use the programmatic_code_execution tool to do this efficiently - don't call each tool separately!`
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
conversationHistory.push(userMessage);
|
|
171
|
+
|
|
172
|
+
const inputs = {
|
|
173
|
+
messages: conversationHistory,
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
console.log('Running agent with PTC capability...\n');
|
|
177
|
+
|
|
178
|
+
const finalContentParts = await run.processStream(inputs, config);
|
|
179
|
+
const finalMessages = run.getRunMessages();
|
|
180
|
+
|
|
181
|
+
if (finalMessages) {
|
|
182
|
+
conversationHistory.push(...finalMessages);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
console.log('\n' + '='.repeat(70));
|
|
186
|
+
console.log('Agent Response:');
|
|
187
|
+
console.log('='.repeat(70));
|
|
188
|
+
|
|
189
|
+
if (finalContentParts) {
|
|
190
|
+
for (const part of finalContentParts) {
|
|
191
|
+
if (part?.type === 'text' && part.text) {
|
|
192
|
+
console.log(part.text);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
console.log('\n' + '='.repeat(70));
|
|
198
|
+
console.log('Test completed successfully!');
|
|
199
|
+
console.log('='.repeat(70));
|
|
200
|
+
console.log('\nKey observations:');
|
|
201
|
+
console.log(
|
|
202
|
+
'1. LLM only sees tools with allowed_callers including "direct" (get_weather, execute_code, programmatic_code_execution, tool_search_regex)'
|
|
203
|
+
);
|
|
204
|
+
console.log(
|
|
205
|
+
'2. When PTC is invoked, ToolNode automatically injects programmatic tools (get_team_members, get_expenses, get_weather)'
|
|
206
|
+
);
|
|
207
|
+
console.log(
|
|
208
|
+
'3. No need to manually configure runtime toolMap - handled by agent context'
|
|
209
|
+
);
|
|
210
|
+
console.log(
|
|
211
|
+
'4. Tool filtering based on allowed_callers happens automatically\n'
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
process.on('unhandledRejection', (reason, promise) => {
|
|
216
|
+
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
217
|
+
console.log('Conversation history:');
|
|
218
|
+
console.dir(conversationHistory, { depth: null });
|
|
219
|
+
process.exit(1);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
process.on('uncaughtException', (err) => {
|
|
223
|
+
console.error('Uncaught Exception:', err);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
main().catch((err) => {
|
|
227
|
+
console.error('Fatal error:', err);
|
|
228
|
+
console.log('Conversation history:');
|
|
229
|
+
console.dir(conversationHistory, { depth: null });
|
|
230
|
+
process.exit(1);
|
|
231
|
+
});
|