GoodPut AI

工具调用

两种协议下的函数调用:定义、响应与结果回传。

平台模型支持工具调用(function calling):模型决定何时调用你定义的工具、以结构化 JSON 给出参数,你执行后把结果回传,模型基于结果继续生成。各模型支持情况见模型库能力标注。

OpenAI 协议

定义工具并发起请求

resp = client.chat.completions.create(
    model="deepseek/deepseek-v4-pro",
    messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询指定城市的实时天气",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }],
)

处理调用并回传结果

模型决定调用工具时,finish_reasontool_calls

msg = resp.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    result = get_weather(**json.loads(call.function.arguments))
    followup = client.chat.completions.create(
        model="deepseek/deepseek-v4-pro",
        messages=[
            {"role": "user", "content": "北京今天天气怎么样?"},
            msg,  # 原样回传含 tool_calls 的 assistant 消息
            {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)},
        ],
        tools=tools,
    )

tool_choice 支持 auto(默认)/ required(必须调用)/ none(禁止调用)/ 指定具体函数。

Anthropic 协议

工具用 input_schema 定义;模型调用时 stop_reasontool_use,结果以 user 消息中的 tool_result 块回传:

{
  "model": "z-ai/glm-5.2",
  "max_tokens": 1024,
  "tools": [{
    "name": "get_weather",
    "description": "查询指定城市的实时天气",
    "input_schema": {
      "type": "object",
      "properties": {"city": {"type": "string"}},
      "required": ["city"]
    }
  }],
  "messages": [
    {"role": "user", "content": "北京今天天气怎么样?"},
    {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_xx", "name": "get_weather", "input": {"city": "北京"}}]},
    {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_xx", "content": "{\"temp\": 31}"}]}
  ]
}

注意事项

  • 推理模型多轮工具调用:把上一轮 assistant 消息(含思考内容)原样回传,不要裁剪改写——协议层的字段兼容由网关处理
  • 工具定义计入输入 token 计费;工具很多时建议配合提示词缓存
  • 流式下工具参数以增量 JSON 返回(OpenAI 协议 delta.tool_calls[].function.arguments;Anthropic 协议 input_json_delta),需自行拼接

本页目录