Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 发布说明
    Search...
    ⌘K

    第一步

    Claude 简介快速开始

    模型与定价

    模型概览选择模型Claude 4.5 的新功能迁移到 Claude 4.5模型弃用定价

    使用 Claude 构建

    功能概览使用 Messages API上下文窗口提示词最佳实践

    功能

    提示词缓存上下文编辑扩展思考流式消息批处理引用多语言支持Token 计数嵌入向量视觉PDF 支持Files API搜索结果Google Sheets 插件

    工具

    概述如何实现工具使用令牌高效的工具使用细粒度工具流式传输Bash 工具代码执行工具计算机使用工具文本编辑器工具Web fetch 工具网络搜索工具记忆工具

    代理技能

    概述在 API 中开始使用 Agent Skills技能创作最佳实践通过 API 使用 Agent Skills

    Agent SDK

    概览TypeScript SDKPython SDK

    指南

    流式输入处理权限会话管理托管 Agent SDK修改系统提示词SDK 中的 MCP自定义工具SDK 中的子代理SDK 中的斜杠命令SDK 中的代理技能跟踪成本和使用情况待办事项列表SDK 中的插件

    API 中的 MCP

    MCP 连接器远程 MCP 服务器

    Claude 在第三方平台上

    Amazon BedrockVertex AI

    提示词工程

    概述提示词生成器使用提示模板提示词改进器保持清晰和直接使用示例(多示例提示)让 Claude 思考(思维链)使用XML标签给Claude分配角色(系统提示)预填充 Claude 的响应链式复杂提示长文本技巧扩展思考技巧

    测试与评估

    定义成功标准开发测试用例使用评估工具减少延迟

    加强防护措施

    减少幻觉提高输出一致性缓解越狱handle-streaming-refusals减少提示词泄露保持Claude的角色特征

    管理和监控

    Admin API 概述使用量和成本 APIClaude Code 分析 API
    Console
    工具

    如何实现工具使用

    学习如何在 Claude 中实现和使用工具,包括工具定义、工具运行器和最佳实践。

    选择模型

    我们建议对复杂工具和模糊查询使用最新的 Claude Sonnet (4.5) 或 Claude Opus (4.1) 模型;它们能更好地处理多个工具并在需要时寻求澄清。

    对于直接的工具使用 Claude Haiku 模型,但请注意它们可能会推断缺失的参数。

    如果使用 Claude 工具和扩展思考,请参考我们的指南 此处 了解更多信息。

    指定客户端工具

    客户端工具(包括 Anthropic 定义的和用户定义的)在 API 请求的 tools 顶级参数中指定。每个工具定义包括:

    参数描述
    name工具的名称。必须匹配正则表达式 ^[a-zA-Z0-9_-]{1,64}$。
    description工具功能、何时使用以及行为方式的详细纯文本描述。
    input_schema定义工具预期参数的 JSON Schema 对象。

    工具使用系统提示

    当您使用 tools 参数调用 Claude API 时,我们从工具定义、工具配置和任何用户指定的系统提示构建一个特殊的系统提示。构建的提示旨在指示模型使用指定的工具并为工具正确运行提供必要的上下文:

    In this environment you have access to a set of tools you can use to answer the user's question.
    {{ FORMATTING INSTRUCTIONS }}
    String and scalar parameters should be specified as is, while lists and objects should use JSON format. Note that spaces for string values are not stripped. The output is not expected to be valid XML and is parsed with regular expressions.
    Here are the functions available in JSONSchema format:
    {{ TOOL DEFINITIONS IN JSON SCHEMA }}
    {{ USER SYSTEM PROMPT }}
    {{ TOOL CONFIGURATION }}

    工具定义的最佳实践

    为了从使用工具的 Claude 中获得最佳性能,请遵循以下指南:

    • 提供极其详细的描述。 这是工具性能中最重要的因素。您的描述应该解释有关工具的每个细节,包括:
      • 工具的功能
      • 何时应该使用它(以及何时不应该)
      • 每个参数的含义以及它如何影响工具的行为
      • 任何重要的注意事项或限制,例如如果工具名称不清楚,工具不会返回什么信息。您能为 Claude 提供的关于工具的上下文越多,它在决定何时以及如何使用它们时就会越好。每个工具描述至少应该有 3-4 句话,如果工具很复杂则更多。
    • 优先考虑描述而不是示例。 虽然您可以在工具的描述中或在附带的提示中包含如何使用工具的示例,但这不如拥有清晰全面的工具目的和参数说明重要。只有在您充分完善了描述之后才添加示例。

    好的描述清楚地解释了工具的功能、何时使用、返回的数据以及 ticker 参数的含义。不佳的描述太简洁,给 Claude 留下了许多关于工具行为和使用的开放问题。

    工具运行器(测试版)

    工具运行器为使用 Claude 执行工具提供了开箱即用的解决方案。工具运行器不是手动处理工具调用、工具结果和对话管理,而是自动:

    • 在 Claude 调用工具时执行工具
    • 处理请求/响应周期
    • 管理对话状态
    • 提供类型安全和验证

    我们建议您对大多数工具使用实现使用工具运行器。

    工具运行器目前处于测试版,仅在 Python 和 TypeScript SDK 中可用。

    基本用法

    SDK 工具运行器处于测试版。本文档的其余部分涵盖手动工具实现。

    控制 Claude 的输出

    强制工具使用

    在某些情况下,您可能希望 Claude 使用特定工具来回答用户的问题,即使 Claude 认为可以在不使用工具的情况下提供答案。您可以通过在 tool_choice 字段中指定工具来执行此操作,如下所示:

    tool_choice = {"type": "tool", "name": "get_weather"}

    使用 tool_choice 参数时,我们有四个可能的选项:

    • auto 允许 Claude 决定是否调用任何提供的工具。这是提供 tools 时的默认值。
    • any 告诉 Claude 它必须使用其中一个提供的工具,但不强制特定工具。
    • tool 允许我们强制 Claude 始终使用特定工具。
    • none 防止 Claude 使用任何工具。这是未提供 tools 时的默认值。

    使用 提示缓存 时,对 tool_choice 参数的更改将使缓存的消息块失效。工具定义和系统提示保持缓存,但消息内容必须重新处理。

    此图说明了每个选项的工作方式:

    请注意,当您将 tool_choice 设置为 any 或 tool 时,我们将预填充助手消息以强制使用工具。这意味着模型不会在 tool_use 内容块之前发出自然语言响应或解释,即使明确要求这样做。

    使用 扩展思考 和工具使用时,不支持 tool_choice: {"type": "any"} 和 tool_choice: {"type": "tool", "name": "..."} 并将导致错误。只有 tool_choice: {"type": "auto"} (默认值)和 tool_choice: {"type": "none"} 与扩展思考兼容。

    我们的测试表明这不应该降低性能。如果您希望模型在仍然请求模型使用特定工具的同时提供自然语言上下文或解释,您可以对 tool_choice 使用 {"type": "auto"} (默认值)并在 user 消息中添加明确的说明。例如:伦敦的天气怎么样?在您的回应中使用 get_weather 工具。

    JSON 输出

    工具不一定需要是客户端函数 — 您可以在任何时候想要模型返回遵循提供的模式的 JSON 输出时使用工具。例如,您可能会使用具有特定模式的 record_summary 工具。有关完整的工作示例,请参阅 Claude 工具使用。

    使用工具的模型响应

    使用工具时,Claude 通常会评论它正在做什么或在调用工具之前自然地响应用户。

    例如,给定提示"旧金山现在的天气怎么样,那里现在几点?",Claude 可能会响应:

    JSON
    {
      "role": "assistant",
      "content": [
        {
          "type": "text",
          "text": "I'll help you check the current weather and time in San Francisco."
        },
        {
          "type": "tool_use",
          "id": "toolu_01A09q90qw90lq917835lq9",
          "name": "get_weather",
          "input": {"location": "San Francisco, CA"}
        }
      ]
    }

    这种自然的响应风格帮助用户理解 Claude 正在做什么,并创建更具对话性的交互。您可以通过系统提示和在提示中提供 <examples> 来指导这些响应的风格和内容。

    重要的是要注意,Claude 在解释其操作时可能会使用各种措辞和方法。您的代码应该像对待任何其他助手生成的文本一样对待这些响应,而不是依赖特定的格式约定。

    并行工具使用

    默认情况下,Claude 可能会使用多个工具来回答用户查询。您可以通过以下方式禁用此行为:

    • 当 tool_choice 类型为 auto 时设置 disable_parallel_tool_use=true,这确保 Claude 最多使用 一个 工具
    • 当 tool_choice 类型为 any 或 tool 时设置 disable_parallel_tool_use=true,这确保 Claude 恰好使用 一个 工具

    最大化并行工具使用

    虽然 Claude 4 模型默认具有出色的并行工具使用功能,但您可以通过有针对性的提示增加所有模型中并行工具执行的可能性:

    Claude Sonnet 3.7 的并行工具使用

    Claude Sonnet 3.7 可能不太可能在响应中进行并行工具调用,即使您未设置 disable_parallel_tool_use。为了解决这个问题,我们建议启用 令牌高效工具使用,这有助于鼓励 Claude 使用并行工具。此测试版功能还可以降低延迟并平均节省 14% 的输出令牌。

    如果您不想选择令牌高效工具使用测试版,您也可以引入一个"批处理工具",该工具可以充当元工具来同时包装对其他工具的调用。我们发现,如果存在此工具,模型将使用它为您同时并行调用多个工具。

    有关如何使用此解决方法的信息,请参阅我们的 cookbook 中的 此示例。

    处理工具使用和工具结果内容块

    使用工具运行器更简单:本部分中描述的手动工具处理由 工具运行器 自动管理。当您需要对工具执行进行自定义控制时,请使用本部分。

    Claude 的响应根据它是使用客户端工具还是服务器工具而有所不同。

    处理来自客户端工具的结果

    响应将具有 tool_use 的 stop_reason 和一个或多个 tool_use 内容块,其中包括:

    • id:此特定工具使用块的唯一标识符。这将用于稍后匹配工具结果。
    • name:正在使用的工具的名称。
    • input:包含传递给工具的输入的对象,符合工具的 input_schema。

    当您收到客户端工具的工具使用响应时,您应该:

    1. 从 tool_use 块中提取 name、id 和 input。
    2. 在您的代码库中运行与该工具名称对应的实际工具,传入工具 input。
    3. 通过发送一条新消息来继续对话,其 role 为 user,content 块包含 tool_result 类型和以下信息:
      • tool_use_id:这是结果的工具使用请求的 id。
      • content:工具的结果,作为字符串(例如 "content": "15 degrees")、嵌套内容块的列表(例如 "content": [{"type": "text", "text": "15 degrees"}])或文档块的列表(例如 "content": ["type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "15 degrees"}])。这些内容块可以使用 text、image 或 document 类型。
      • is_error (可选):如果工具执行导致错误,设置为 true。

    重要的格式要求:

    • 工具结果块必须紧跟在消息历史中对应的工具使用块之后。您不能在助手的工具使用消息和用户的工具结果消息之间包含任何消息。
    • 在包含工具结果的用户消息中,tool_result 块必须首先出现在内容数组中。任何文本必须在所有工具结果之后。

    例如,这将导致 400 错误:

    {"role": "user", "content": [
      {"type": "text", "text": "Here are the results:"},  // ❌ Text before tool_result
      {"type": "tool_result", "tool_use_id": "toolu_01", ...}
    ]}

    这是正确的:

    {"role": "user", "content": [
      {"type": "tool_result", "tool_use_id": "toolu_01", ...},
      {"type": "text", "text": "What should I do next?"}  // ✅ Text after tool_result
    ]}

    如果您收到类似"tool_use ids were found without tool_result blocks immediately after"的错误,请检查您的工具结果是否格式正确。

    收到工具结果后,Claude 将使用该信息继续生成对原始用户提示的响应。

    处理来自服务器工具的结果

    Claude 在内部执行工具并将结果直接合并到其响应中,无需额外的用户交互。

    与其他 API 的区别

    与分离工具使用或使用特殊角色(如 tool 或 function)的 API 不同,Claude API 将工具直接集成到 user 和 assistant 消息结构中。

    消息包含 text、image、tool_use 和 tool_result 块的数组。user 消息包括客户端内容和 tool_result,而 assistant 消息包含 AI 生成的内容和 tool_use。

    处理 max_tokens 停止原因

    如果 Claude 的 响应因达到 max_tokens 限制而被截断,并且截断的响应包含不完整的工具使用块,您需要使用更高的 max_tokens 值重试请求以获得完整的工具使用。

    # Check if response was truncated during tool use
    if response.stop_reason == "max_tokens":
        # Check if the last content block is an incomplete tool_use
        last_block = response.content[-1]
        if last_block.type == "tool_use":
            # Send the request with higher max_tokens
            response = client.messages.create(
                model="claude-sonnet-4-5",
                max_tokens=4096,  # Increased limit
                messages=messages,
                tools=tools
            )

    处理 pause_turn 停止原因

    使用 Web 搜索等服务器工具时,API 可能会返回 pause_turn 停止原因,表示 API 已暂停长时间运行的轮次。

    以下是处理 pause_turn 停止原因的方法:

    import anthropic
    
    client = anthropic.Anthropic()
    
    # Initial request with web search
    response = client.messages.create(
        model="claude-3-7-sonnet-latest",
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": "Search for comprehensive information about quantum computing breakthroughs in 2025"
            }
        ],
        tools=[{
            "type": "web_search_20250305",
            "name": "web_search",
            "max_uses": 10
        }]
    )
    
    # Check if the response has pause_turn stop reason
    if response.stop_reason == "pause_turn":
        # Continue the conversation with the paused content
        messages = [
            {"role": "user", "content": "Search for comprehensive information about quantum computing breakthroughs in 2025"},
            {"role": "assistant", "content": response.content}
        ]
    
        # Send the continuation request
        continuation = client.messages.create(
            model="claude-3-7-sonnet-latest",
            max_tokens=1024,
            messages=messages,
            tools=[{
                "type": "web_search_20250305",
                "name": "web_search",
                "max_uses": 10
            }]
        )
    
        print(continuation)
    else:
        print(response)

    处理 pause_turn 时:

    • 继续对话:在后续请求中按原样传递暂停的响应,让 Claude 继续其轮次
    • 根据需要修改:如果您想中断或重定向对话,您可以选择在继续之前修改内容
    • 保留工具状态:在继续请求中包含相同的工具以维持功能

    故障排除错误

    内置错误处理:工具运行器 为大多数常见场景提供自动错误处理。本部分涵盖高级用例的手动错误处理。

    使用 Claude 工具时可能会发生几种不同类型的错误:

    • 控制 Claude 的输出
    • JSON 输出
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC