使用 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?"
}
]
}'import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
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's the weather like in San Francisco?"}],
)
print(response)import { Anthropic } from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
async function main() {
const response = await anthropic.messages.create({
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: "Tell me the weather in San Francisco."
}]
});
console.log(response);
}
main().catch(console.error);import java.util.List;
import java.util.Map;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.Tool;
import com.anthropic.models.messages.Tool.InputSchema;
public class GetWeatherExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
InputSchema schema = InputSchema.builder()
.properties(JsonValue.from(Map.of(
"location",
Map.of(
"type", "string",
"description", "The city and state, e.g. San Francisco, CA"))))
.putAdditionalProperty("required", JsonValue.from(List.of("location")))
.build();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.addTool(Tool.builder()
.name("get_weather")
.description("Get the current weather in a given location")
.inputSchema(schema)
.build())
.addUserMessage("What's the weather like in San Francisco?")
.build();
Message message = client.messages().create(params);
System.out.println(message);
}
}工具使用的工作原理
Claude 支持两种类型的工具:
Anthropic 定义的工具使用版本化类型(例如,web_search_20250305、text_editor_20250124)来确保跨模型版本的兼容性。
客户端工具
通过以下步骤将客户端工具与 Claude 集成:
为 Claude 提供工具和用户提示
- 在您的 API 请求中定义具有名称、描述和输入模式的客户端工具。
- 包含可能需要这些工具的用户提示,例如,"旧金山的天气如何?"
Claude 决定使用工具
- Claude 评估是否有任何工具可以帮助处理用户的查询。
- 如果是,Claude 构造一个格式正确的工具使用请求。
- 对于客户端工具,API 响应的
stop_reason为tool_use,表示 Claude 的意图。
执行工具并返回结果
- 从 Claude 的请求中提取工具名称和输入
- 在您的系统上执行工具代码
- 在包含
tool_result内容块的新user消息中返回结果
Claude 使用工具结果制定响应
- Claude 分析工具结果以制定对原始用户提示的最终响应。
注意:步骤 3 和 4 是可选的。对于某些工作流程,Claude 的工具使用请求(步骤 2)可能就是您所需要的全部,无需将结果发送回 Claude。
服务器工具
服务器工具遵循不同的工作流程:
Claude 执行服务器工具
- Claude 评估服务器工具是否可以帮助处理用户的查询。
- 如果是,Claude 执行工具,结果会自动合并到 Claude 的响应中。
Claude 使用服务器工具结果制定响应
- Claude 分析服务器工具结果以制定对原始用户提示的最终响应。
- 服务器工具执行不需要额外的用户交互。
工具使用示例
以下是一些代码示例,演示各种工具使用模式和技术。为了简洁起见,工具是简单的工具,工具描述比理想情况下要短,以确保最佳性能。
定价
Tool use requests are priced based on:
- The total number of input tokens sent to the model (including in the
toolsparameter) - The number of output tokens generated
- 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
toolsparameter in API requests (tool names, descriptions, and schemas) tool_usecontent blocks in API requests and responsestool_resultcontent 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.
| Model | Tool choice | Tool use system prompt token count |
|---|---|---|
| Claude Opus 4.1 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Opus 4 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Sonnet 4.5 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Sonnet 4 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Sonnet 3.7 (deprecated) | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Haiku 4.5 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Haiku 3.5 | auto, noneany, tool | 264 tokens 340 tokens |
| Claude Opus 3 (deprecated) | auto, noneany, tool | 530 tokens 281 tokens |
| Claude Sonnet 3 | auto, noneany, tool | 159 tokens 235 tokens |
| Claude Haiku 3 | auto, noneany, 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 指标的一部分。
下一步
在我们的食谱中探索我们的即用工具使用代码示例存储库: