---
title: 處理工具呼叫
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls
description: 解析 tool_use 區塊、格式化 tool_result 回應，並使用 is_error 處理錯誤。
---

本頁涵蓋工具呼叫的生命週期：從 Claude 的回應中讀取 `tool_use` 區塊、在您的回覆中格式化 `tool_result` 區塊，以及傳達錯誤訊號。若要了解自動處理這些工作的 SDK 抽象層，請參閱 [Tool Runner](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-runner)。

<Note>
  **使用 Tool Runner 更簡單：** 本頁所描述的手動工具處理可由 [Tool Runner](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-runner) 自動管理。當您需要對工具執行進行自訂控制時，請使用本頁內容。
</Note>

Claude 的回應會依其使用的是[用戶端工具或伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/overview#how-tool-use-works)而有所不同。

## 處理來自用戶端工具的結果

回應的 `stop_reason` 會是 `tool_use`，並包含一個或多個 `tool_use` 內容區塊，其中包括：

* `id`：此特定工具使用區塊的唯一識別碼。稍後將用於比對工具結果。
* `name`：所使用工具的名稱。
* `input`：一個物件，包含傳遞給工具的輸入，符合該工具的 `input_schema`。

屬於 [computer use](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/computer-use-tool) 或 [browser use](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/browser-use-tool) 工具集成員的 `tool_use` 區塊還會帶有 `toolset_name` 欄位（`"computer"` 或 `"browser"`）。其 `name` 是 Claude 正在呼叫的成員工具，例如 `screenshot` 或 `navigate`，因此請同時依據這兩個欄位來分派這些區塊。

<Accordion title="包含 `tool_use` 內容區塊的 API 回應範例">
  ```json JSON
  {
    "id": "msg_01Aq9w938a90dw8q",
    "model": "claude-opus-5-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" }
      }
    ]
  }
  ```
</Accordion>

當您收到用戶端工具的工具使用回應時，您應該：

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` 或 [`search_result`](https://platform.claude.com/docs/zh-TW/build-with-claude/search-results) 類型。
   * `is_error`（選填）：若工具執行導致錯誤，請設為 `true`。

回應 computer use 或 browser use 成員區塊的 `tool_result` 也必須回傳與 `tool_use` 區塊相同的 `toolset_name` 值；省略該值的成員結果會被拒絕。其 `content` 的範圍也較窄：成員結果只能包含 `text` 和 `image` 區塊，而 browser use 結果可以額外加入一個 [`browser_state`](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/browser-use-tool#track-tabs-and-page-state) 區塊（[分頁管理成員](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/browser-use-tool#tab-management-results)僅回傳該區塊）。

<Note>
  **重要的格式要求：**

  * 工具結果區塊必須在訊息歷史中緊接在其對應的工具使用區塊之後。您不能在助理的工具使用訊息與使用者的工具結果訊息之間插入任何訊息。
  * 在包含工具結果的使用者訊息中，tool\_result 區塊必須位於 content 陣列的最前面。任何文字都必須放在所有工具結果之後。
  * 如果助理回合也呼叫了尚未有結果區塊的[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)，則使用者訊息必須只包含 `tool_result` 區塊。結果之後的文字會提前結束該回合；對於 Claude 直接呼叫的伺服器工具，請求隨後會以 400 錯誤失敗，並指出未解決的伺服器工具名稱。請參閱[停止原因與後備處理](https://platform.claude.com/docs/zh-TW/build-with-claude/handling-stop-reasons#tool-use)。

  例如，以下會導致 400 錯誤：

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

  當助理回合僅呼叫用戶端工具時，以下是正確的：

  ```json
  {
    "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」的錯誤，請檢查您的工具結果格式是否正確。
</Note>

<Warning>
  工具結果經常帶有來自您無法控制之來源的內容：網頁、收到的電子郵件、使用者上傳的檔案、第三方 API。請將這些內容視為不受信任的：能夠影響這些內容的攻擊者可能會嵌入試圖重新導向 Claude 的指令（間接提示注入，indirect prompt injection）。請將不受信任的內容保留在 `tool_result` 區塊內，而非 `system` 提示或一般的使用者 `text` 區塊中，並參閱[緩解越獄與提示注入](https://platform.claude.com/docs/zh-TW/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks#indirect-prompt-injection)以進一步強化防護。
</Warning>

<AccordionGroup>
  <Accordion title="成功的工具結果範例">
    ```json JSON
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": "15 degrees"
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="包含圖片的工具結果範例">
    ```json JSON
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": [
            { "type": "text", "text": "15 degrees" },
            {
              "type": "image",
              "source": {
                "type": "base64",
                "media_type": "image/jpeg",
                "data": "/9j/4AAQSkZJRg..."
              }
            }
          ]
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="空的工具結果範例">
    ```json JSON
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9"
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="包含文件的工具結果範例">
    ```json JSON
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": [
            { "type": "text", "text": "The weather is" },
            {
              "type": "document",
              "source": {
                "type": "text",
                "media_type": "text/plain",
                "data": "15 degrees"
              }
            }
          ]
        }
      ]
    }
    ```
  </Accordion>
</AccordionGroup>

收到工具結果後，Claude 會使用該資訊繼續針對原始使用者提示生成回應。

## 處理來自伺服器工具的結果

Claude 會在內部執行工具，並將結果直接整合到其回應中，無需額外的使用者互動。

<Note>
  一個回應可以同時包含用戶端 `tool_use` 區塊以及沒有結果區塊的 `server_tool_use` 區塊。該伺服器工具呼叫尚未完成，其結果區塊會在稍後的回應中送達。請以僅包含用戶端工具之 `tool_result` 區塊的使用者訊息回覆，並保持相同的 `tools` 陣列；對於 Claude 直接呼叫的伺服器工具，API 會在該請求中執行它，而下一個回應會以其結果區塊開頭。請參閱[停止原因與後備處理](https://platform.claude.com/docs/zh-TW/build-with-claude/handling-stop-reasons#tool-use)。
</Note>

<Tip>
  **與其他 API 的差異**

  與將工具使用分離或使用 `tool`、`function` 等特殊角色的 API 不同，Claude API 將工具直接整合到 `user` 和 `assistant` 訊息結構中。

  訊息包含由 `text`、`image`、`tool_use` 和 `tool_result` 區塊組成的陣列。`user` 訊息包含用戶端內容和 `tool_result`，而 `assistant` 訊息包含 AI 生成的內容和 `tool_use`。
</Tip>

## 使用 is\_error 處理錯誤

搭配 Claude 使用工具時，可能會發生幾種不同類型的錯誤：

<AccordionGroup>
  <Accordion title="工具執行錯誤">
    如果工具本身在執行期間拋出錯誤（例如，擷取天氣資料時發生網路錯誤），您可以在 `content` 中回傳錯誤訊息，並附上 `"is_error": true`：

    ```json JSON
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": "ConnectionError: the weather service API is not available (HTTP 500)",
          "is_error": true
        }
      ]
    }
    ```

    Claude 隨後會將此錯誤整合到其對使用者的回應中。例如：「很抱歉，由於天氣服務 API 無法使用，我無法取得目前的天氣。請稍後再試。」

    <Tip>
      撰寫具指導性的錯誤訊息。與其使用像 `"failed"` 這樣的通用錯誤，不如說明出了什麼問題以及 Claude 接下來應該嘗試什麼（例如 `"Rate limit exceeded. Retry after 60 seconds."`）。這能為 Claude 提供恢復或調整所需的上下文，而無需猜測。
    </Tip>
  </Accordion>

  <Accordion title="無效的工具名稱">
    如果 Claude 嘗試使用工具的方式無效（例如，缺少必要參數），通常表示 Claude 沒有足夠的資訊來正確使用該工具。在開發期間，最好的做法是在工具定義中使用更詳細的 `description` 值，然後再次嘗試該請求。

    不過，您也可以使用指出錯誤的 `tool_result` 繼續推進對話，Claude 會嘗試補上缺少的資訊後再次使用該工具：

    ```json JSON
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": "Error: Missing required 'location' parameter",
          "is_error": true
        }
      ]
    }
    ```

    如果工具請求無效或缺少參數，Claude 會在向使用者致歉之前重試 2 至 3 次並進行修正。

    <Tip>
      若要完全消除無效的工具呼叫，請在您的工具定義上使用 `strict: true` 的[嚴格工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/strict-tool-use)。這可保證工具輸入始終與您的結構描述完全相符，避免缺少參數和類型不符的情況。
    </Tip>
  </Accordion>

  <Accordion title="伺服器工具錯誤">
    當伺服器工具遇到錯誤時（例如，Web Search 的網路問題），Claude 會透明地處理這些錯誤，並嘗試向使用者提供替代回應或說明。與用戶端工具不同，您不需要為伺服器工具處理 `is_error` 結果。

    特別針對網頁搜尋，可能的錯誤代碼包括：

    * `too_many_requests`：超出速率限制
    * `invalid_input`：無效的搜尋查詢參數
    * `max_uses_exceeded`：超出網頁搜尋工具的最大使用次數
    * `query_too_long`：查詢超出最大長度
    * `unavailable`：發生內部錯誤
  </Accordion>
</AccordionGroup>

## 後續步驟

<CardGroup cols={3}>
  <Card title="平行工具使用" icon="grid" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/parallel-tool-use">
    處理 Claude 在單一回合中呼叫多個工具的回應。
  </Card>

  <Card title="Tool Runner（SDK）" icon="wrench" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-runner">
    讓 SDK 為您管理 `tool_use` 迴圈、結果格式化與重試。
  </Card>

  <Card title="定義工具" icon="hammer" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools">
    撰寫能引導 Claude 選用正確工具的結構描述與說明。
  </Card>
</CardGroup>
