Claude 平台工具调用机制与 OpenAI 兼容层限制解析

本文档解析了 Claude 平台的工具调用机制,包括工具定义规范、强制调用、严格模式以及 OpenAI 兼容层的限制。重点指出 OpenAI 兼容层忽略 `strict` 参数,无法保证工具调用 JSON 的严格校验,建议使用 Claude 原生 API 的结构化输出功能。同时提供了工具调用的完整流程和示例代码。

READ

Claude 平台通过 tool_use 和 tool_result 块实现工具调用。工具分为在客户端运行的“客户端工具”(如自定义工具、bash、text_editor)和在 Anthropic 基础设施上运行的“服务器工具”(如 web_search、web_fetch)。客户端工具需要开发者自行编写代码执行并返回结果,而服务器工具则直接返回结果。通过 tool_choice 参数可以控制模型是否调用工具或强制调用特定工具。

来源1

工具定义规范与最佳实践

在 Claude 平台定义工具时,必须提供 name(匹配 ^[a-zA-Z0-9_-]{1,128}$)、description 和 input_schema(JSON Schema 格式)。description 是决定工具调用准确率的最关键因素,建议为每个工具编写 3-4 句以上的详细描述,说明其用途、参数含义及限制。对于复杂工具,可以使用 input_examples 提供示例输入,帮助模型理解参数格式。

强制工具调用 (Forcing Tool Use)

通过 tool_choice 参数可以强制模型调用工具。例如,tool_choice: {"type": "tool", "name": "get_weather"} 会强制调用指定工具。然而,部分模型(如 Claude Fable 5.2, Claude Mythos 5.2, Claude Opus 5.5, Claude Sonnet 5.5 等)不支持强制工具调用,使用 any 或 tool 类型会返回 400 错误。在这些模型上,建议使用 auto 配合 strict: true 来保证工具调用的准确性。

严格模式 (Strict Tool Use)

在工具定义中添加 strict: true 可以确保 Claude 的工具调用严格遵循提供的 input_schema。如果模型生成的参数不符合 schema,API 会返回错误。这比 OpenAI 兼容层中的 strict 参数更可靠,因为 OpenAI 兼容层会忽略该参数。

来源2

OpenAI 兼容层限制

Claude 平台提供 OpenAI 兼容层,允许使用 OpenAI SDK 进行调用,但存在以下关键限制:

  1. strict 参数被忽略:在 OpenAI 兼容层中,工具定义中的 strict 参数会被忽略,无法保证工具调用 JSON 严格遵循 schema。若需严格校验,必须使用 Claude 原生 API 并启用结构化输出 (Structured Outputs)。
  2. response_format 限制:仅支持 json_schema 且必须设置 strict: true。设置 json_object 或 text 会返回 400 错误。
  3. 系统/开发者消息提升 (Hoisting):OpenAI 兼容层会将所有 system 和 developer 角色消息提升并拼接为顶层 system 字段。无法在对话中途添加系统指令,需使用 Claude 原生 API 的 mid-conversation system messages。
  4. thinking 支持差异:在 Claude 5 模型上,兼容层默认开启 thinking 且不支持返回思考内容。设置 adaptive 类型会返回 400 错误。
  5. 其他忽略字段:top_p、temperature(部分模型)、logprobs、metadata、presence_penalty、frequency_penalty、seed 等字段在兼容层中会被忽略或返回错误。

来源3

工具调用处理流程

  1. 发起请求:在 tools 参数中定义工具,发送包含用户消息的请求。
  2. 模型响应:如果模型决定调用工具,响应中将包含 tool_use 块,包含工具名称和参数。
  3. 执行工具:客户端代码解析 tool_use 块,执行相应工具逻辑。
  4. 返回结果:将工具执行结果封装为 tool_result 块,通过新的请求发送给模型。
  5. 最终响应:模型根据工具结果生成最终回答。

示例代码 (Python)

以下示例展示了如何在 Claude 平台定义工具、调用工具并处理结果:

import anthropic

client = anthropic.Anthropic()

tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a given location.",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and state, e.g. San Francisco, CA",
                }
            },
            "required": ["location"],
        },
    }
]

messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]

# 发起请求
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "auto"},
    messages=messages,
)

# 检查是否有工具调用
tool_use = next((block for block in response.content if block.type == "tool_use"), None)
if tool_use:
    print(f"Claude called {tool_use.name} with {tool_use.input}")
    # 执行工具逻辑
    weather = "15 degrees Celsius, partly cloudy"
    
    # 将结果返回给模型
    messages += [
        {"role": "assistant", "content": response.content},
        {
            "role": "user",
            "content": [
                {"type": "tool_result", "tool_use_id": tool_use.id, "content": weather}
            ],
        },
    ]
    
    # 获取最终响应
    followup = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        tools=tools,
        tool_choice={"type": "auto"},
        messages=messages,
    )
    
    final_text = next((block for block in followup.content if block.type == "text"), None)
    if final_text:
        print(final_text.text)

来源1

Conversation

评论

正在加载评论