Claude 能够与工具和函数交互,让您扩展 Claude 的能力来执行更广泛的任务。
通过我们新的课程学习掌握 Claude 工具使用所需的一切!请 继续使用此表单分享您的想法和建议。
以下是使用 Messages API 向 Claude 提供工具的示例:
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [
      {
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            }
          },
          "required": ["location"]
        }
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "What is the weather like in San Francisco?"
      }
    ]
  }'

工具使用的工作原理

Claude 支持两种类型的工具:
  1. 客户端工具:在您的系统上执行的工具,包括:
  2. 服务器工具:在 Anthropic 服务器上执行的工具,如网络搜索网络获取工具。这些工具必须在 API 请求中指定,但不需要您进行实现。
Anthropic 定义的工具使用版本化类型(例如,web_search_20250305text_editor_20250124)来确保跨模型版本的兼容性。

客户端工具

通过以下步骤将客户端工具与 Claude 集成:
1

为 Claude 提供工具和用户提示

  • 在您的 API 请求中定义具有名称、描述和输入模式的客户端工具。
  • 包含可能需要这些工具的用户提示,例如,“旧金山的天气如何?”
2

Claude 决定使用工具

  • Claude 评估是否有任何工具可以帮助处理用户的查询。
  • 如果是,Claude 构造一个格式正确的工具使用请求。
  • 对于客户端工具,API 响应的 stop_reasontool_use,表示 Claude 的意图。
3

执行工具并返回结果

  • 从 Claude 的请求中提取工具名称和输入
  • 在您的系统上执行工具代码
  • 在包含 tool_result 内容块的新 user 消息中返回结果
4

Claude 使用工具结果制定响应

  • Claude 分析工具结果以制定对原始用户提示的最终响应。
注意:步骤 3 和 4 是可选的。对于某些工作流程,Claude 的工具使用请求(步骤 2)可能就是您所需要的全部,无需将结果发送回 Claude。

服务器工具

服务器工具遵循不同的工作流程:
1

为 Claude 提供工具和用户提示

  • 服务器工具,如网络搜索网络获取,有自己的参数。
  • 包含可能需要这些工具的用户提示,例如,“搜索关于 AI 的最新新闻”或”分析此 URL 的内容”。
2

Claude 执行服务器工具

  • Claude 评估服务器工具是否可以帮助处理用户的查询。
  • 如果是,Claude 执行工具,结果会自动合并到 Claude 的响应中。
3

Claude 使用服务器工具结果制定响应

  • Claude 分析服务器工具结果以制定对原始用户提示的最终响应。
  • 服务器工具执行不需要额外的用户交互。

工具使用示例

以下是一些代码示例,演示各种工具使用模式和技术。为了简洁起见,工具是简单的工具,工具描述比理想情况下要短,以确保最佳性能。
curl https://api.anthropic.com/v1/messages \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --data \
'{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [{
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The unit of temperature, either \"celsius\" or \"fahrenheit\""
                }
            },
            "required": ["location"]
        }
    }],
    "messages": [{"role": "user", "content": "What is the weather like in San Francisco?"}]
}'
Claude 将返回类似以下的响应:
JSON
{
  "id": "msg_01Aq9w938a90dw8q",
  "model": "claude-sonnet-4-5",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll check the current weather in San Francisco for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA", "unit": "celsius"}
    }
  ]
}
然后您需要使用提供的输入执行 get_weather 函数,并在新的 user 消息中返回结果:
curl https://api.anthropic.com/v1/messages \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --data \
'{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [
        {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "The unit of temperature, either \"celsius\" or \"fahrenheit\""
                    }
                },
                "required": ["location"]
            }
        }
    ],
    "messages": [
        {
            "role": "user",
            "content": "What is the weather like in San Francisco?"
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I'll check the current weather in San Francisco for you."
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01A09q90qw90lq917835lq9",
                    "name": "get_weather",
                    "input": {
                        "location": "San Francisco, CA",
                        "unit": "celsius"
                    }
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
                    "content": "15 degrees"
                }
            ]
        }
    ]
}'
这将打印 Claude 的最终响应,其中包含天气数据:
JSON
{
  "id": "msg_01Aq9w938a90dw8q",
  "model": "claude-sonnet-4-5",
  "stop_reason": "stop_sequence",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "The current weather in San Francisco is 15 degrees Celsius (59 degrees Fahrenheit). It's a cool day in the city by the bay!"
    }
  ]
}
Claude 可以在单个响应中并行调用多个工具,这对于需要多个独立操作的任务很有用。使用并行工具时,所有 tool_use 块都包含在单个助手消息中,所有相应的 tool_result 块必须在后续用户消息中提供。
重要:工具结果必须格式正确,以避免 API 错误并确保 Claude 继续使用并行工具。有关详细的格式要求和完整代码示例,请参阅我们的实现指南
有关实现并行工具调用的全面示例、测试脚本和最佳实践,请参阅我们实现指南中的并行工具使用部分
您可以在单个请求中为 Claude 提供多个工具供其选择。以下是一个同时包含 get_weatherget_time 工具的示例,以及一个询问两者的用户查询。
curl https://api.anthropic.com/v1/messages \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --data \
'{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [{
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
                }
            },
            "required": ["location"]
        }
    },
    {
        "name": "get_time",
        "description": "Get the current time in a given time zone",
        "input_schema": {
            "type": "object",
            "properties": {
                "timezone": {
                    "type": "string",
                    "description": "The IANA time zone name, e.g. America/Los_Angeles"
                }
            },
            "required": ["timezone"]
        }
    }],
    "messages": [{
        "role": "user",
        "content": "What is the weather like right now in New York? Also what time is it there?"
    }]
}'
在这种情况下,Claude 可能会:
  • 顺序使用工具(一次一个)— 先调用 get_weather,然后在收到天气结果后调用 get_time
  • 使用并行工具调用 — 当操作独立时,在单个响应中输出多个 tool_use
当 Claude 进行并行工具调用时,您必须在单个 user 消息中返回所有工具结果,每个结果都在自己的 tool_result 块中。
如果用户的提示不包含足够的信息来填充工具的所有必需参数,Claude Opus 更有可能识别出缺少参数并询问。Claude Sonnet 可能会询问,特别是在提示它在输出工具请求之前先思考时。但它也可能尽力推断一个合理的值。例如,使用上面的 get_weather 工具,如果您问 Claude “天气如何?“而不指定位置,Claude,特别是 Claude Sonnet,可能会对工具输入进行猜测:
JSON
{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "get_weather",
  "input": {"location": "New York, NY", "unit": "fahrenheit"}
}
这种行为不能保证,特别是对于更模糊的提示和不太智能的模型。如果 Claude Opus 没有足够的上下文来填写必需的参数,它更有可能用澄清问题而不是进行工具调用来响应。
某些任务可能需要按顺序调用多个工具,使用一个工具的输出作为另一个工具的输入。在这种情况下,Claude 将一次调用一个工具。如果提示一次调用所有工具,如果下游工具依赖于上游工具的工具结果,Claude 很可能会为下游工具猜测参数。以下是使用 get_location 工具获取用户位置,然后将该位置传递给 get_weather 工具的示例:
curl https://api.anthropic.com/v1/messages \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --data \
'{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [
        {
            "name": "get_location",
            "description": "Get the current user location based on their IP address. This tool has no parameters or arguments.",
            "input_schema": {
                "type": "object",
                "properties": {}
            }
        },
        {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
                    }
                },
                "required": ["location"]
            }
        }
    ],
    "messages": [{
        "role": "user",
        "content": "What is the weather like where I am?"
    }]
}'
在这种情况下,Claude 首先会调用 get_location 工具来获取用户的位置。在您在 tool_result 中返回位置后,Claude 然后会使用该位置调用 get_weather 来获得最终答案。完整的对话可能如下所示:
角色内容
用户我所在地方的天气如何?
助手我先找到您的当前位置,然后检查那里的天气。[使用 get_location 工具]
用户[get_location 的工具结果,匹配 id 和结果为 San Francisco, CA]
助手[使用 get_weather 工具,输入如下]{ “location”: “San Francisco, CA”, “unit”: “fahrenheit” }
用户[get_weather 的工具结果,匹配 id 和结果为 “59°F (15°C), mostly cloudy”]
助手根据您在加利福尼亚州旧金山的当前位置,现在的天气是 59°F (15°C),大部分多云。这是一个相当凉爽和阴天的日子。如果您要外出,可能需要带一件轻便的夹克。
此示例演示了 Claude 如何将多个工具调用链接在一起,以回答需要从不同来源收集数据的问题。关键步骤是:
  1. Claude 首先意识到它需要用户的位置来回答天气问题,因此它调用 get_location 工具。
  2. 用户(即客户端代码)执行实际的 get_location 函数并在 tool_result 块中返回结果”San Francisco, CA”。
  3. 现在知道了位置,Claude 继续调用 get_weather 工具,传入”San Francisco, CA”作为 location 参数(以及猜测的 unit 参数,因为 unit 不是必需参数)。
  4. 用户再次使用提供的参数执行实际的 get_weather 函数,并在另一个 tool_result 块中返回天气数据。
  5. 最后,Claude 将天气数据合并到对原始问题的自然语言响应中。
默认情况下,Claude Opus 被提示在回答工具使用查询之前先思考,以最好地确定是否需要工具、使用哪个工具以及适当的参数。Claude Sonnet 和 Claude Haiku 被提示尽可能多地尝试使用工具,更有可能调用不必要的工具或推断缺失的参数。要提示 Sonnet 或 Haiku 在进行工具调用之前更好地评估用户查询,可以使用以下提示:思维链提示使用相关工具(如果可用)回答用户的请求。在调用工具之前,进行一些分析。首先,考虑提供的工具中哪个是回答用户请求的相关工具。其次,遍历相关工具的每个必需参数,并确定用户是否直接提供或给出了足够的信息来推断值。在决定是否可以推断参数时,仔细考虑所有上下文,看它是否支持特定值。如果所有必需参数都存在或可以合理推断,则继续进行工具调用。但是,如果必需参数的值之一缺失,请不要调用函数(即使用缺失参数的填充值也不行),而是要求用户提供缺失的参数。如果未提供可选参数,请不要要求更多信息。
您可以使用工具让 Claude 产生遵循模式的 JSON 输出,即使您没有任何意图通过工具或函数运行该输出。以这种方式使用工具时:
  • 您通常希望提供单个工具
  • 您应该设置 tool_choice(参见强制工具使用)来指示模型明确使用该工具
  • 请记住,模型将把 input 传递给工具,因此工具的名称和描述应该从模型的角度来看。
以下使用 record_summary 工具按特定格式描述图像。
#!/bin/bash
IMAGE_URL="https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
IMAGE_MEDIA_TYPE="image/jpeg"
IMAGE_BASE64=$(curl "$IMAGE_URL" | base64)

curl https://api.anthropic.com/v1/messages \
     --header "content-type: application/json" \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --data \
'{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [{
        "name": "record_summary",
        "description": "Record summary of an image using well-structured JSON.",
        "input_schema": {
            "type": "object",
            "properties": {
                "key_colors": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
"r": { "type": "number", "description": "red value [0.0, 1.0]" },
"g": { "type": "number", "description": "green value [0.0, 1.0]" },
"b": { "type": "number", "description": "blue value [0.0, 1.0]" },
"name": { "type": "string", "description": "Human-readable color name in snake_case, e.g. \"olive_green\" or \"turquoise\"" }
                        },
                        "required": [ "r", "g", "b", "name" ]
                    },
                    "description": "Key colors in the image. Limit to less than four."
                },
                "description": {
                    "type": "string",
                    "description": "Image description. One to two sentences max."
                },
                "estimated_year": {
                    "type": "integer",
                    "description": "Estimated year that the image was taken, if it is a photo. Only set this if the image appears to be non-fictional. Rough estimates are okay!"
                }
            },
            "required": [ "key_colors", "description" ]
        }
    }],
    "tool_choice": {"type": "tool", "name": "record_summary"},
    "messages": [
        {"role": "user", "content": [
            {"type": "image", "source": {
                "type": "base64",
                "media_type": "'$IMAGE_MEDIA_TYPE'",
                "data": "'$IMAGE_BASE64'"
            }},
            {"type": "text", "text": "Describe this image."}
        ]}
    ]
}'

定价

Tool use requests are priced based on:
  1. The total number of input tokens sent to the model (including in the tools parameter)
  2. The number of output tokens generated
  3. For server-side tools, additional usage-based pricing (e.g., web search charges per search performed)
Client-side tools are priced the same as any other Claude API request, while server-side tools may incur additional charges based on their specific usage. The additional tokens from tool use come from:
  • The tools parameter in API requests (tool names, descriptions, and schemas)
  • tool_use content blocks in API requests and responses
  • tool_result content blocks in API requests
When you use tools, we also automatically include a special system prompt for the model which enables tool use. The number of tool use tokens required for each model are listed below (excluding the additional tokens listed above). Note that the table assumes at least 1 tool is provided. If no tools are provided, then a tool choice of none uses 0 additional system prompt tokens.
ModelTool choiceTool use system prompt token count
Claude Opus 4.1auto, none
any, tool
346 tokens
313 tokens
Claude Opus 4auto, none
any, tool
346 tokens
313 tokens
Claude Sonnet 4.5auto, none
any, tool
346 tokens
313 tokens
Claude Sonnet 4auto, none
any, tool
346 tokens
313 tokens
Claude Sonnet 3.7auto, none
any, tool
346 tokens
313 tokens
Claude Sonnet 3.5 (Oct) (deprecated)auto, none
any, tool
346 tokens
313 tokens
Claude Sonnet 3.5 (June) (deprecated)auto, none
any, tool
294 tokens
261 tokens
Claude Haiku 4.5auto, none
any, tool
346 tokens
313 tokens
Claude Haiku 3.5auto, none
any, tool
264 tokens
340 tokens
Claude Opus 3 (deprecated)auto, none
any, tool
530 tokens
281 tokens
Claude Sonnet 3auto, none
any, tool
159 tokens
235 tokens
Claude Haiku 3auto, none
any, tool
264 tokens
340 tokens
These token counts are added to your normal input and output tokens to calculate the total cost of a request. 请参阅我们的模型概述表了解当前的每个模型价格。 当您发送工具使用提示时,就像任何其他 API 请求一样,响应将输出输入和输出令牌计数作为报告的 usage 指标的一部分。

下一步

在我们的食谱中探索我们的即用工具使用代码示例存储库: