Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    開始使用
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.5 新功能遷移至 Claude 4.5模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API上下文窗口提示詞最佳實踐
    功能
    提示詞快取上下文編輯擴展思考努力串流消息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實現工具使用細粒度工具串流Bash 工具代碼執行工具程式化工具調用計算機使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶體工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐使用 API 的 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2 (預覽)Python SDK遷移指南
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞生成器使用提示詞範本提示詞改進器清晰直接使用範例 (多次提示)讓 Claude 思考 (CoT)使用 XML 標籤給 Claude 一個角色 (系統提示詞)預填 Claude 的回應鏈接複雜提示詞長上下文提示擴展思考提示
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    加強防護欄
    減少幻覺增加輸出一致性緩解越獄串流拒絕減少提示詞洩露保持 Claude 的角色
    管理和監控
    Admin API 概覽使用量和成本 APIClaude Code Analytics API
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

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

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    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

    Learn

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

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

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

    如何實現工具使用

    學習如何在 Claude API 中定義和使用工具,包括工具定義、最佳實踐和工具執行器的實現。

    選擇模型

    我們建議對複雜工具和模糊查詢使用最新的 Claude Sonnet (4.5) 或 Claude Opus (4.1) 模型;它們能更好地處理多個工具並在需要時尋求澄清。

    對於直接的工具使用 Claude Haiku 模型,但請注意它們可能會推斷缺失的參數。

    如果使用 Claude 進行工具使用和擴展思考,請參考我們的指南 此處 以獲取更多信息。

    指定客戶端工具

    客戶端工具(包括 Anthropic 定義的和用戶定義的)在 API 請求的 tools 頂級參數中指定。每個工具定義包括:

    ParameterDescription
    name工具的名稱。必須符合正則表達式 ^[a-zA-Z0-9_-]{1,64}$。
    description工具功能、何時應使用以及其行為方式的詳細純文本描述。
    input_schema定義工具預期參數的 JSON Schema 對象。
    input_examples(可選,測試版)示例輸入對象的數組,幫助 Claude 理解如何使用工具。請參閱 提供工具使用示例。

    工具使用系統提示

    當您使用 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 句話,如果工具複雜則更多。
    • 優先考慮描述,但對於複雜工具可考慮使用 input_examples。 清晰的描述最重要,但對於具有複雜輸入、嵌套對象或格式敏感參數的工具,您可以使用 input_examples 字段(測試版)提供經過模式驗證的示例。有關詳細信息,請參閱 提供工具使用示例。

    良好的描述清楚地解釋了工具的功能、何時使用、返回的數據以及 ticker 參數的含義。不佳的描述過於簡潔,讓 Claude 對工具的行為和使用方式有許多疑問。

    提供工具使用示例

    您可以提供具體的有效工具輸入示例,幫助 Claude 更有效地理解如何使用您的工具。這對於具有嵌套對象、可選參數或格式敏感輸入的複雜工具特別有用。

    工具使用示例是一項測試版功能。為您的提供商包含適當的 測試版標頭:

    ProviderBeta headerSupported models
    Claude API,
    Microsoft Foundry
    advanced-tool-use-2025-11-20All models
    Vertex AI,
    Amazon Bedrock
    tool-examples-2025-10-29Claude Opus 4.5 only

    基本用法

    將可選的 input_examples 字段添加到您的工具定義中,其中包含示例輸入對象的數組。每個示例必須根據工具的 input_schema 有效:

    import anthropic
    
    client = anthropic.Anthropic()
    
    response = client.messages.create(
        model="claude-sonnet-4-5-20250929",
        max_tokens=1024,
        betas=["advanced-tool-use-2025-11-20"],
        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"
                        }
                    },
                    "required": ["location"]
                },
                "input_examples": [
                    {
                        "location": "San Francisco, CA",
                        "unit": "fahrenheit"
                    },
                    {
                        "location": "Tokyo, Japan",
                        "unit": "celsius"
                    },
                    {
                        "location": "New York, NY"  # 'unit' is optional
                    }
                ]
            }
        ],
        messages=[
            {"role": "user", "content": "What's the weather like in San Francisco?"}
        ]
    )

    示例包含在提示中,與您的工具模式一起,向 Claude 展示格式良好的工具調用的具體模式。這幫助 Claude 理解何時包含可選參數、使用什麼格式以及如何構建複雜輸入。

    要求和限制

    • 模式驗證 - 每個示例必須根據工具的 input_schema 有效。無效示例返回 400 錯誤
    • 不支持服務器端工具 - 只有用戶定義的工具可以有輸入示例
    • 令牌成本 - 示例增加提示令牌:簡單示例約 20-50 個令牌,複雜嵌套對象約 100-200 個令牌

    工具執行器(測試版)

    工具執行器為使用 Claude 執行工具提供了開箱即用的解決方案。工具執行器不是手動處理工具調用、工具結果和對話管理,而是自動:

    • 在 Claude 調用工具時執行工具
    • 處理請求/響應週期
    • 管理對話狀態
    • 提供類型安全和驗證

    我們建議您對大多數工具使用實現使用工具執行器。

    工具執行器目前處於測試版,可在 Python、TypeScript 和 Ruby 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 消息中添加明確的說明。例如:What's the weather like in London? Use the get_weather tool in your response.

    使用嚴格工具保證工具調用

    將 tool_choice: {"type": "any"} 與 嚴格工具使用 結合,以保證您的工具之一將被調用 AND 工具輸入嚴格遵循您的模式。在您的工具定義上設置 strict: true 以啟用模式驗證。

    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 4 模型,它們具有內置的令牌高效工具使用和改進的並行工具調用。

    如果您仍在使用 Claude Sonnet 3.7,您可以啟用 token-efficient-tools-2025-02-19 beta 標頭,這有助於鼓勵 Claude 使用並行工具。您也可以引入一個「批量工具」,它可以充當元工具來同時包裝對其他工具的調用。

    有關如何使用此解決方法的信息,請參閱我們食譜中的此示例。

    處理工具使用和工具結果內容塊

    使用工具運行器更簡單:本部分中描述的手動工具處理由工具運行器自動管理。當您需要對工具執行進行自定義控制時,請使用本部分。

    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 停止原因

    使用服務器工具(如網絡搜索)時,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 輸出
    • 處理 max_tokens 停止原因