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. 客戶端工具:在您的系統上執行的工具,包括:
    • 您創建和實作的使用者定義自訂工具
    • Anthropic 定義的工具,如電腦使用文字編輯器,需要客戶端實作
  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.7 (deprecated)auto, none
any, tool
346 tokens
313 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 指標的一部分。

下一步

探索我們在食譜中準備實作的工具使用程式碼範例儲存庫: