函数调用
让模型调用你应用中的结构化操作。
概述
函数调用(也叫"工具使用")让你向模型描述函数,模型可以选择用结构化 JSON 参数来调用它们。这使得模型能够与外部系统、数据库和 API 交互。
定义工具
在请求中传递 tools 数组,包含 JSON Schema 定义:
TypeScript
| 1 | const completion = await client.chat.completions.create({ |
| 2 | model: 'gpt-4o', |
| 3 | messages: [{ role: 'user', content: '东京的天气怎么样?' }], |
| 4 | tools: [ |
| 5 | { |
| 6 | type: 'function', |
| 7 | function: { |
| 8 | name: 'get_weather', |
| 9 | description: '获取指定地点的当前天气', |
| 10 | parameters: { |
| 11 | type: 'object', |
| 12 | properties: { |
| 13 | location: { type: 'string', description: '城市名称' }, |
| 14 | unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }, |
| 15 | }, |
| 16 | required: ['location'], |
| 17 | }, |
| 18 | }, |
| 19 | }, |
| 20 | ], |
| 21 | }); |
处理工具调用
当模型决定调用函数时,响应中包含 tool_calls 数组。执行函数并将结果发回:
TypeScript
| 1 | const toolCall = completion.choices[0].message.tool_calls[0]; |
| 2 | const args = JSON.parse(toolCall.function.arguments); |
| 3 | |
| 4 | // 执行你的函数 |
| 5 | const weather = await getWeather(args.location, args.unit); |
| 6 | |
| 7 | // 将结果发回 |
| 8 | const followUp = await client.chat.completions.create({ |
| 9 | model: 'gpt-4o', |
| 10 | messages: [ |
| 11 | { role: 'user', content: '东京的天气怎么样?' }, |
| 12 | completion.choices[0].message, |
| 13 | { |
| 14 | role: 'tool', |
| 15 | tool_call_id: toolCall.id, |
| 16 | content: JSON.stringify(weather), |
| 17 | }, |
| 18 | ], |
| 19 | }); |
支持的模型
具有"函数调用"功能的模型支持此特性,包括 GPT-4o、Claude Sonnet/Opus 和 Gemini 模型。在 模型页面 按"Tools"功能筛选。