4.2 工具定义与注册

工具接口

1
2
3
4
5
6
interface Tool {
name: string;
description: string;
parameters: JSONSchema;
execute: (params: any) => Promise<any>;
}

内置工具

read 工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export const readTool: Tool = {
name: 'read',
description: '读取文件内容',
parameters: {
type: 'object',
properties: {
path: { type: 'string', description: '文件路径' }
},
required: ['path']
},
execute: async (params) => {
return fs.readFileSync(params.path, 'utf-8');
}
};

write 工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export const writeTool: Tool = {
name: 'write',
description: '写入文件',
parameters: {
type: 'object',
properties: {
path: { type: 'string' },
content: { type: 'string' }
},
required: ['path', 'content']
},
execute: async (params) => {
fs.writeFileSync(params.path, params.content);
return '文件已写入';
}
};

exec 工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export const execTool: Tool = {
name: 'exec',
description: '执行命令',
parameters: {
type: 'object',
properties: {
command: { type: 'string' }
},
required: ['command']
},
execute: async (params) => {
return child_process.execSync(params.command).toString();
}
};

导航

上一篇: 4.1 Function Calling 原理

下一篇: 4.3 工具执行循环