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
| // 定义工具接口
interface Tool {
name: string;
description: string;
parameters: Schema;
execute: (input: any) => Promise<any>;
}
// 示例工具:搜索
class SearchTool implements Tool {
name = 'web_search';
description = 'Search the web for current information';
parameters = {
type: 'object',
properties: {
query: {
type: 'string',
description: 'The search query'
},
num_results: {
type: 'number',
description: 'Number of results to return',
default: 5
}
},
required: ['query']
};
async execute(input: { query: string; num_results?: number }): Promise<string> {
const results = await this.searchEngine.search(
input.query,
input.num_results || 5
);
return JSON.stringify(results, null, 2);
}
}
// 示例工具:代码执行
class CodeExecutionTool implements Tool {
name = 'code_interpreter';
description = 'Execute Python code and get the result';
parameters = {
type: 'object',
properties: {
code: {
type: 'string',
description: 'The Python code to execute'
}
},
required: ['code']
};
async execute(input: { code: string }): Promise<string> {
try {
const result = await this.pythonRunner.run(input.code);
return result.stdout || result.stderr || 'Execution completed';
} catch (error) {
return `Error: ${error.message}`;
}
}
}
// Agent使用工具
class ToolUsingAgent {
private tools = new Map<string, Tool>();
registerTool(tool: Tool): void {
this.tools.set(tool.name, tool);
}
async execute(task: string): Promise<string> {
// 1. 让LLM选择工具
const toolChoice = await this.selectTool(task);
// 2. 验证参数
const tool = this.tools.get(toolChoice.name);
const validated = this.validateParameters(
tool.parameters,
toolChoice.arguments
);
// 3. 执行工具
const result = await tool.execute(validated);
// 4. 处理结果
return await this.processResult(result, task);
}
private async selectTool(task: string): Promise<any> {
const toolsSpec = Array.from(this.tools.values()).map(tool => ({
name: tool.name,
description: tool.description,
input_schema: tool.parameters
}));
const prompt = `
Task: ${task}
Available tools:
${JSON.stringify(toolsSpec, null, 2)}
Select the appropriate tool and provide its arguments as JSON.
`;
const response = await this.llm.complete(prompt);
return JSON.parse(response);
}
}
|