| 流程 | 定义 tools → 模型回 tool_calls → 执行 → 回填 tool 角色 → 二次请求 |
|---|---|
| 关键字段 | tools、tool_choice、tool_calls、tool_call_id |
| 并行 | 一次响应可含多个 tool_calls,逐一执行并全部回填 |
| 约束 | strict 模式可要求参数符合 JSON Schema |
第一轮请求(声明 tools)
第一轮请求(声明 tools)
curl -s https://api.openai.com/v1/chat/completions -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"北京今天天气?"}],"tools":[{"type":"function","function":{"name":"get_weather","description":"查询城市天气","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]}'
# 拿到 tool_calls 后执行本地函数,将结果以 {"role":"tool","tool_call_id":...,"content":...} 追加后再次请求tool_choice 可强制/禁止调用(auto/none/指定函数);生产环境务必在服务端校验参数后再执行。