工具调用

工具调用按各协议的原生格式透传:Anthropic 格式用 tools + input_schema,OpenAI 格式用 tools + function.parameters,Responses API 用 tools + 顶层 name/parameters。流程都是三步:带工具发请求 → 客户端执行工具 → 把结果回传给模型。

请求体示例

带工具的推理请求

Anthropic 格式:

json
{
  "model": "claude-sonnet-5",
  "max_tokens": 256,
  "tools": [
    {
      "name": "get_weather",
      "description": "查询城市天气",
      "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
    }
  ],
  "messages": [{"role": "user", "content": "北京现在天气怎么样?"}]
}

模型决定调用时,stop_reasontool_usecontent 里有 typetool_use 的块,含 idnameinput

OpenAI 格式:

json
{
  "model": "gpt-5.6-sol",
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "查询城市天气",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
      }
    }
  ],
  "messages": [{"role": "user", "content": "北京现在天气怎么样?"}]
}

模型决定调用时,finish_reasontool_calls,调用在 choices[0].message.tool_calls[],参数是 JSON 字符串 function.arguments

客户端执行工具

从响应中取出工具名与参数,由客户端程序执行(如查询天气、查询数据库),得到结果。

回传工具结果

将模型的工具调用消息与执行结果一并追加到对话后再次请求。Anthropic 格式在 user 消息里放 tool_result 块(tool_use_id 对应上一步的 id);OpenAI 格式追加 roletool 的消息(tool_call_id 对应 tool_calls[].id)。模型据此生成最终回复,stop_reason 回到 end_turn(OpenAI 为 stop)。

最佳实践

  • 写清 description 与参数 schema,模型据此决定何时调用以及如何填写参数
  • 循环处理:响应仍为工具调用时,执行并回传结果,直到停止原因不再是 tool_use / tool_calls
  • 工具结果尽量精简,长结果会计入后续请求的输入 token
准备好了?三步即可开始登录控制台 · 购买额度 · 创建 API Key
DiscordGet community help instantly
工具调用 · 帮助文档