-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathfunction-calling-agent.js
More file actions
398 lines (360 loc) · 12.8 KB
/
function-calling-agent.js
File metadata and controls
398 lines (360 loc) · 12.8 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
/**
* @process specializations/ai-agents-conversational/function-calling-agent
* @description Function Calling Agent with Tool Integration - Process for building agents with function calling capabilities
* including tool definition, input validation, parallel execution, error handling, and result aggregation.
* @inputs { agentName?: string, tools?: array, llmProvider?: string, parallelExecution?: boolean, outputDir?: string }
* @outputs { success: boolean, toolDefinitions: array, functionCallingLogic: object, errorHandlers: object, integrationTests: array, artifacts: array }
*
* @example
* const result = await orchestrate('specializations/ai-agents-conversational/function-calling-agent', {
* agentName: 'data-analyst-agent',
* tools: ['query_database', 'create_chart', 'send_email'],
* llmProvider: 'openai',
* parallelExecution: true
* });
*
* @references
* - OpenAI Function Calling: https://platform.openai.com/docs/guides/function-calling
* - Anthropic Tool Use: https://docs.anthropic.com/claude/docs/tool-use
* - LangChain Tools: https://python.langchain.com/docs/modules/agents/tools/
*/
import { defineTask } from '@a5c-ai/babysitter-sdk';
export async function process(inputs, ctx) {
const {
agentName = 'function-calling-agent',
tools = [],
llmProvider = 'openai',
parallelExecution = true,
outputDir = 'function-calling-output',
maxRetries = 3,
timeout = 30000
} = inputs;
const startTime = ctx.now();
const artifacts = [];
ctx.log('info', `Starting Function Calling Agent Development for ${agentName}`);
// ============================================================================
// PHASE 1: TOOL SPECIFICATION
// ============================================================================
ctx.log('info', 'Phase 1: Specifying tools');
const toolSpecification = await ctx.task(toolSpecificationTask, {
agentName,
tools,
llmProvider,
outputDir
});
artifacts.push(...toolSpecification.artifacts);
// ============================================================================
// PHASE 2: INPUT VALIDATION
// ============================================================================
ctx.log('info', 'Phase 2: Implementing input validation');
const inputValidation = await ctx.task(inputValidationTask, {
agentName,
toolDefinitions: toolSpecification.definitions,
outputDir
});
artifacts.push(...inputValidation.artifacts);
// ============================================================================
// PHASE 3: FUNCTION EXECUTION LOGIC
// ============================================================================
ctx.log('info', 'Phase 3: Implementing function execution');
const executionLogic = await ctx.task(functionExecutionTask, {
agentName,
toolDefinitions: toolSpecification.definitions,
parallelExecution,
timeout,
outputDir
});
artifacts.push(...executionLogic.artifacts);
// ============================================================================
// PHASE 4: ERROR HANDLING
// ============================================================================
ctx.log('info', 'Phase 4: Implementing error handling');
const errorHandling = await ctx.task(errorHandlingTask, {
agentName,
toolDefinitions: toolSpecification.definitions,
maxRetries,
outputDir
});
artifacts.push(...errorHandling.artifacts);
// ============================================================================
// PHASE 5: RESULT AGGREGATION
// ============================================================================
ctx.log('info', 'Phase 5: Implementing result aggregation');
const resultAggregation = await ctx.task(resultAggregationTask, {
agentName,
parallelExecution,
outputDir
});
artifacts.push(...resultAggregation.artifacts);
// ============================================================================
// PHASE 6: INTEGRATION TESTING
// ============================================================================
ctx.log('info', 'Phase 6: Creating integration tests');
const integrationTests = await ctx.task(integrationTestsTask, {
agentName,
toolDefinitions: toolSpecification.definitions,
outputDir
});
artifacts.push(...integrationTests.artifacts);
// Final Breakpoint
await ctx.breakpoint({
question: `Function calling agent ${agentName} complete. ${toolSpecification.definitions.length} tools configured. Review implementation?`,
title: 'Function Calling Agent Review',
context: {
runId: ctx.runId,
summary: {
agentName,
toolCount: toolSpecification.definitions.length,
llmProvider,
parallelExecution,
testCount: integrationTests.tests.length
},
files: artifacts.map(a => ({ path: a.path, format: a.format || 'javascript' }))
}
});
const endTime = ctx.now();
const duration = endTime - startTime;
return {
success: true,
agentName,
toolDefinitions: toolSpecification.definitions,
functionCallingLogic: executionLogic.logic,
errorHandlers: errorHandling.handlers,
integrationTests: integrationTests.tests,
artifacts,
duration,
metadata: {
processId: 'specializations/ai-agents-conversational/function-calling-agent',
timestamp: startTime,
outputDir
}
};
}
// ============================================================================
// TASK DEFINITIONS
// ============================================================================
export const toolSpecificationTask = defineTask('tool-specification', (args, taskCtx) => ({
kind: 'agent',
title: `Specify Tools - ${args.agentName}`,
agent: {
name: 'function-calling-architect', // AG-TU-001: Creates function calling schemas with JSON schema validation
prompt: {
role: 'Tool Architect',
task: 'Specify tools for function calling agent',
context: args,
instructions: [
'1. Create detailed tool definitions',
'2. Define JSON schemas for parameters',
'3. Write clear tool descriptions for LLM',
'4. Define required vs optional parameters',
'5. Add parameter examples',
'6. Format for target LLM provider',
'7. Document return value schemas',
'8. Save tool specifications'
],
outputFormat: 'JSON with tool definitions'
},
outputSchema: {
type: 'object',
required: ['definitions', 'artifacts'],
properties: {
definitions: { type: 'array' },
schemas: { type: 'object' },
specPath: { type: 'string' },
artifacts: { type: 'array' }
}
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
},
labels: ['agent', 'function-calling', 'tools']
}));
export const inputValidationTask = defineTask('input-validation', (args, taskCtx) => ({
kind: 'skill',
title: `Implement Input Validation - ${args.agentName}`,
skill: {
name: 'function-calling-schemas', // SK-TU-001: Function calling schema templates for various APIs
prompt: {
role: 'Input Validation Developer',
task: 'Implement input validation for function calls',
context: args,
instructions: [
'1. Create validation for each tool',
'2. Validate parameter types',
'3. Validate required parameters',
'4. Check parameter constraints',
'5. Sanitize inputs for security',
'6. Generate helpful error messages',
'7. Handle type coercion',
'8. Save validation logic'
],
outputFormat: 'JSON with validation logic'
},
outputSchema: {
type: 'object',
required: ['validators', 'artifacts'],
properties: {
validators: { type: 'object' },
validationCodePath: { type: 'string' },
artifacts: { type: 'array' }
}
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
},
labels: ['agent', 'function-calling', 'validation']
}));
export const functionExecutionTask = defineTask('function-execution', (args, taskCtx) => ({
kind: 'skill',
title: `Implement Function Execution - ${args.agentName}`,
skill: {
name: 'langchain-tools', // SK-LC-004: LangChain tool creation and integration utilities
prompt: {
role: 'Function Execution Developer',
task: 'Implement function calling execution logic',
context: args,
instructions: [
'1. Parse function call from LLM response',
'2. Route to correct tool handler',
'3. Implement parallel execution if enabled',
'4. Add timeout handling',
'5. Capture execution results',
'6. Format results for LLM consumption',
'7. Handle streaming responses',
'8. Save execution logic'
],
outputFormat: 'JSON with execution logic'
},
outputSchema: {
type: 'object',
required: ['logic', 'artifacts'],
properties: {
logic: { type: 'object' },
executionCodePath: { type: 'string' },
artifacts: { type: 'array' }
}
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
},
labels: ['agent', 'function-calling', 'execution']
}));
export const errorHandlingTask = defineTask('error-handling-fc', (args, taskCtx) => ({
kind: 'agent',
title: `Implement Error Handling - ${args.agentName}`,
agent: {
name: 'error-handler-developer',
prompt: {
role: 'Error Handling Developer',
task: 'Implement error handling for function calls',
context: args,
instructions: [
'1. Define error types',
'2. Implement retry logic with backoff',
'3. Handle tool-specific errors',
'4. Create fallback strategies',
'5. Format errors for LLM',
'6. Add error logging',
'7. Implement circuit breaker',
'8. Save error handlers'
],
outputFormat: 'JSON with error handlers'
},
outputSchema: {
type: 'object',
required: ['handlers', 'artifacts'],
properties: {
handlers: { type: 'object' },
errorCodePath: { type: 'string' },
retryConfig: { type: 'object' },
artifacts: { type: 'array' }
}
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
},
labels: ['agent', 'function-calling', 'error-handling']
}));
export const resultAggregationTask = defineTask('result-aggregation', (args, taskCtx) => ({
kind: 'agent',
title: `Implement Result Aggregation - ${args.agentName}`,
agent: {
name: 'aggregation-developer',
prompt: {
role: 'Result Aggregation Developer',
task: 'Implement result aggregation for parallel calls',
context: args,
instructions: [
'1. Collect results from parallel calls',
'2. Handle partial failures',
'3. Order results appropriately',
'4. Merge related results',
'5. Format aggregated results',
'6. Handle timeout on aggregation',
'7. Create result summaries',
'8. Save aggregation logic'
],
outputFormat: 'JSON with aggregation logic'
},
outputSchema: {
type: 'object',
required: ['aggregator', 'artifacts'],
properties: {
aggregator: { type: 'object' },
aggregationCodePath: { type: 'string' },
artifacts: { type: 'array' }
}
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
},
labels: ['agent', 'function-calling', 'aggregation']
}));
export const integrationTestsTask = defineTask('integration-tests-fc', (args, taskCtx) => ({
kind: 'agent',
title: `Create Integration Tests - ${args.agentName}`,
agent: {
name: 'test-developer',
prompt: {
role: 'Integration Test Developer',
task: 'Create integration tests for function calling',
context: args,
instructions: [
'1. Create tests for each tool',
'2. Test valid inputs',
'3. Test invalid inputs',
'4. Test error handling',
'5. Test parallel execution',
'6. Test timeout handling',
'7. Create mock tool implementations',
'8. Save test suite'
],
outputFormat: 'JSON with integration tests'
},
outputSchema: {
type: 'object',
required: ['tests', 'artifacts'],
properties: {
tests: { type: 'array' },
testSuitePath: { type: 'string' },
mocks: { type: 'object' },
artifacts: { type: 'array' }
}
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
},
labels: ['agent', 'function-calling', 'testing']
}));