Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K

    第一步

    Claude 介紹快速入門

    模型與定價

    模型概覽選擇模型Claude 4.5 的新功能遷移到 Claude 4.5模型棄用定價

    使用 Claude 建構

    功能概覽使用 Messages API上下文視窗提示詞最佳實踐

    功能

    提示詞快取上下文編輯延伸思考串流訊息批次處理引用多語言支援Token 計數嵌入向量視覺PDF 支援Files API搜尋結果Google Sheets 附加元件

    工具

    概述如何實現工具使用代幣高效工具使用細粒度工具串流Bash 工具代碼執行工具電腦使用工具文字編輯工具網頁擷取工具網路搜尋工具記憶工具

    代理技能

    概述在 API 中開始使用 Agent Skills技能編寫最佳實踐使用 Agent Skills 與 API

    Agent SDK

    概述Agent SDK 參考 - TypeScriptPython 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 的輸出以及處理工具使用和工具結果內容區塊。

    選擇模型

    我們建議對複雜工具和模糊查詢使用最新的 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. 通過發送角色為 user 的新消息和包含 tool_result 類型的 content 區塊來繼續對話,以及以下信息:
      • 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 輸出
    © 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