-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathtool-execution.ts
More file actions
478 lines (432 loc) · 14 KB
/
tool-execution.ts
File metadata and controls
478 lines (432 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/**
* Tool Execution Example
*
* Demonstrates tool calling capabilities with cascadeflow:
* - Defining custom tools
* - Tool execution with cascade
* - Multi-step tool workflows
* - Error handling in tool calls
* - Tool result validation
*
* Usage: npx tsx examples/nodejs/tool-execution.ts
*/
import { CascadeAgent, type Message, type Tool } from '@cascadeflow/core';
import { safeCalculateExpression } from './safe-math';
// ============================================================================
// Tool Definitions
// ============================================================================
/**
* Weather tool - simulates weather API
*/
const weatherTool = {
type: 'function' as const,
function: {
name: 'get_weather',
description: 'Get current weather for a location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name or coordinates'
},
units: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
description: 'Temperature units'
}
},
required: ['location']
}
}
};
/**
* Calculator tool - performs mathematical operations
*/
const calculatorTool = {
type: 'function' as const,
function: {
name: 'calculate',
description: 'Perform mathematical calculations',
parameters: {
type: 'object',
properties: {
expression: {
type: 'string',
description: 'Mathematical expression to evaluate (e.g., "2 + 2", "sqrt(16)")'
}
},
required: ['expression']
}
}
};
/**
* Search tool - simulates database search
*/
const searchTool = {
type: 'function' as const,
function: {
name: 'search_database',
description: 'Search a product database',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Search query'
},
category: {
type: 'string',
enum: ['electronics', 'books', 'clothing', 'all'],
description: 'Product category filter'
},
max_results: {
type: 'number',
description: 'Maximum number of results to return'
}
},
required: ['query']
}
}
};
/**
* Email tool - simulates sending emails
*/
const emailTool = {
type: 'function' as const,
function: {
name: 'send_email',
description: 'Send an email to a recipient',
parameters: {
type: 'object',
properties: {
to: {
type: 'string',
description: 'Recipient email address'
},
subject: {
type: 'string',
description: 'Email subject line'
},
body: {
type: 'string',
description: 'Email body content'
}
},
required: ['to', 'subject', 'body']
}
}
};
// ============================================================================
// Tool Execution Functions
// ============================================================================
/**
* Execute weather tool
*/
function executeWeatherTool(args: { location: string; units?: string }): string {
const { location, units = 'celsius' } = args;
// Simulate weather data
const temp = units === 'celsius' ? 22 : 72;
const conditions = ['sunny', 'cloudy', 'rainy', 'partly cloudy'];
const condition = conditions[Math.floor(Math.random() * conditions.length)];
return JSON.stringify({
location,
temperature: temp,
units,
condition,
humidity: 65,
wind_speed: 12
});
}
/**
* Execute calculator tool
*/
function executeCalculatorTool(args: { expression: string }): string {
try {
const result = safeCalculateExpression(args.expression);
return JSON.stringify({
expression: args.expression,
result,
unit: typeof result === 'number' ? 'number' : 'unknown'
});
} catch (error) {
return JSON.stringify({
error: 'Calculation failed',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
}
/**
* Execute search tool
*/
function executeSearchTool(args: { query: string; category?: string; max_results?: number }): string {
const { query, category = 'all', max_results = 5 } = args;
// Simulate search results
const products = [
{ id: 1, name: 'Laptop Pro', category: 'electronics', price: 1299 },
{ id: 2, name: 'TypeScript Book', category: 'books', price: 39 },
{ id: 3, name: 'Wireless Mouse', category: 'electronics', price: 29 },
{ id: 4, name: 'Cotton T-Shirt', category: 'clothing', price: 19 },
{ id: 5, name: 'Programming Guide', category: 'books', price: 49 },
];
let results = products;
if (category !== 'all') {
results = results.filter(p => p.category === category);
}
// Simple search filter
results = results.filter(p =>
p.name.toLowerCase().includes(query.toLowerCase())
);
return JSON.stringify({
query,
category,
total_results: results.length,
results: results.slice(0, max_results)
});
}
/**
* Execute email tool
*/
function executeEmailTool(args: { to: string; subject: string; body: string }): string {
// Simulate email sending
return JSON.stringify({
status: 'sent',
to: args.to,
subject: args.subject,
timestamp: new Date().toISOString(),
message_id: `msg_${Math.random().toString(36).substr(2, 9)}`
});
}
/**
* Tool execution dispatcher
*/
function executeToolCall(toolName: string, args: any): string {
switch (toolName) {
case 'get_weather':
return executeWeatherTool(args);
case 'calculate':
return executeCalculatorTool(args);
case 'search_database':
return executeSearchTool(args);
case 'send_email':
return executeEmailTool(args);
default:
return JSON.stringify({ error: 'Unknown tool', tool: toolName });
}
}
// ============================================================================
// Example Scenarios
// ============================================================================
type NormalizedToolCall = {
id: string;
name: string;
arguments: Record<string, any>;
};
type ExecutedToolCall = {
call: NormalizedToolCall;
result: string;
};
function parseArgs(raw: string): Record<string, any> {
try {
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
} catch {
return {};
}
}
function normalizeToolCall(raw: any, index: number): NormalizedToolCall | null {
if (!raw || typeof raw !== 'object') return null;
const fn = raw.function && typeof raw.function === 'object' ? raw.function : {};
const name = fn.name || raw.name;
if (!name) return null;
const args = typeof fn.arguments === 'string' ? parseArgs(fn.arguments) : {};
return {
id: raw.id || `call_${index}`,
name,
arguments: args,
};
}
async function runToolConversation(params: {
agent: CascadeAgent;
query: string;
tools: Tool[];
maxTurns?: number;
}) {
const { agent, query, tools, maxTurns = 7 } = params;
const messages: Message[] = [{ role: 'user', content: query }];
const executed: ExecutedToolCall[] = [];
let totalCost = 0;
let modelUsed = '';
let finalResponse = '';
for (let turn = 0; turn < maxTurns; turn += 1) {
const result = await agent.run(messages, {
tools,
maxTokens: 250,
temperature: 0.4,
maxSteps: maxTurns,
});
totalCost += result.totalCost || 0;
modelUsed = result.modelUsed || modelUsed;
const content = (result.content || '').trim();
const rawToolCalls = Array.isArray(result.toolCalls) ? result.toolCalls : [];
const normalized = rawToolCalls
.map((raw, i) => normalizeToolCall(raw, executed.length + i))
.filter((v): v is NormalizedToolCall => Boolean(v));
if (normalized.length > 0) {
messages.push({
role: 'assistant',
content: content || '',
tool_calls: normalized.map(call => ({
id: call.id,
type: 'function' as const,
function: {
name: call.name,
arguments: JSON.stringify(call.arguments),
},
})),
});
for (const toolCall of normalized) {
const toolResult = executeToolCall(toolCall.name, toolCall.arguments);
executed.push({ call: toolCall, result: toolResult });
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
name: toolCall.name,
content: toolResult,
});
}
continue;
}
if (content) {
finalResponse = content;
break;
}
}
if (!finalResponse) {
const fallback = await agent.run(messages, {
tools,
maxTokens: 200,
temperature: 0.2,
maxSteps: 1,
});
totalCost += fallback.totalCost || 0;
modelUsed = fallback.modelUsed || modelUsed;
finalResponse = (fallback.content || '').trim();
}
return {
modelUsed,
totalCost,
finalResponse,
turns: messages.length,
executed,
};
}
async function main() {
console.log('\n╔═══════════════════════════════════════════════════════════════╗');
console.log('║ cascadeflow - Tool Execution Examples ║');
console.log('╚═══════════════════════════════════════════════════════════════╝\n');
if (!process.env.OPENAI_API_KEY) {
console.log('⚠️ OPENAI_API_KEY not found in environment');
console.log(' Set it in .env file or export OPENAI_API_KEY=your_key');
console.log(' This example requires OpenAI for tool calling support\n');
return;
}
const agent = new CascadeAgent({
models: [
{ name: 'gpt-4o-mini', provider: 'openai', cost: 0.00015, supportsTools: true },
{ name: 'gpt-4o', provider: 'openai', cost: 0.00625, supportsTools: true },
],
quality: {
threshold: 0.7,
},
});
console.log('🔧 Tool calling capabilities:');
console.log(' • Weather lookups');
console.log(' • Mathematical calculations');
console.log(' • Database searches');
console.log(' • Email sending (simulated)');
console.log('');
const scenarios: Array<{ title: string; query: string; tools: Tool[] }> = [
{
title: 'Example 1: Single Tool Call (Weather)',
query: "What's the weather like in San Francisco?",
tools: [weatherTool],
},
{
title: 'Example 2: Mathematical Calculations',
query: 'Calculate the square root of 144 and then multiply it by 5',
tools: [calculatorTool],
},
{
title: 'Example 3: Database Search',
query: 'Search for electronics products',
tools: [searchTool],
},
{
title: 'Example 4: Multi-Tool Workflow',
query: 'Check the weather in New York and send me an email about it',
tools: [weatherTool, emailTool],
},
{
title: 'Example 5: Error Handling',
query: 'Calculate the result of dividing by zero: 10 / 0',
tools: [calculatorTool],
},
];
let aggregateCost = 0;
let aggregateCalls = 0;
let nonEmptyResponses = 0;
for (const scenario of scenarios) {
console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(scenario.title);
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
try {
const result = await runToolConversation({
agent,
query: scenario.query,
tools: scenario.tools,
});
aggregateCost += result.totalCost;
aggregateCalls += result.executed.length;
if (result.finalResponse) nonEmptyResponses += 1;
console.log(`Query: ${scenario.query}`);
console.log(`Model: ${result.modelUsed}`);
console.log(`Turns: ${result.turns}`);
console.log(`🔧 Tool Calls Made: ${result.executed.length}`);
for (const [index, executed] of result.executed.entries()) {
console.log(`\n Call ${index + 1}:`);
console.log(` Tool: ${executed.call.name}`);
console.log(` Arguments: ${JSON.stringify(executed.call.arguments)}`);
console.log(` Result: ${executed.result}`);
}
console.log(`\n💬 Response: ${result.finalResponse}`);
console.log(`💰 Cost: $${result.totalCost.toFixed(6)}`);
} catch (error) {
console.error('Error:', error instanceof Error ? error.message : error);
}
}
console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('📊 Tool Calling Summary');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('✅ Demonstrated Features:');
console.log(' • Single tool calls');
console.log(' • Multiple sequential tool calls');
console.log(' • Multi-tool workflows');
console.log(' • Error handling');
console.log(' • Closed tool loop continuation');
console.log('');
console.log('🎯 Validation Outcomes:');
console.log(` • Total tool calls executed: ${aggregateCalls}`);
console.log(` • Non-empty final responses: ${nonEmptyResponses}/${scenarios.length}`);
console.log(` • Total demo cost: $${aggregateCost.toFixed(6)}`);
console.log('');
console.log('📚 Learn More:');
console.log(' • See streaming-tools.ts for streaming with tools');
console.log(' • See multi-step-cascade.ts for complex workflows');
console.log('');
}
// Run examples
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});