---
title: 給 Claude 的 API 使用入門
url: https://platform.claude.com/docs/zh-TW/claude_api_primer
description: 本指南旨在讓 Claude 掌握使用 Claude API 的基礎知識。內容涵蓋模型 ID／基本 Messages API、工具使用、串流與思考的說明與範例，除此之外別無其他。
---

# 給 Claude 的 API 使用入門

> 本指南旨在讓 Claude 掌握使用 Claude API 的基礎知識。內容涵蓋模型 ID／基本 Messages API、工具使用、串流與思考的說明與範例，除此之外別無其他。

## 模型

```text wrap
Recommended default for most work, including complex agentic coding: Claude Opus 5.5: claude-opus-5-5
Step up for the hardest long-running agentic and research tasks, at 2.5x Claude Opus 5.5 pricing: Claude Fable 5.1: claude-fable-5-1
Previous Opus model: Claude Opus 5: claude-opus-5
Smart model: Claude Sonnet 5.5: claude-sonnet-5-5
Previous Sonnet model: Claude Sonnet 5: claude-sonnet-5
For fast, cost-effective tasks: Claude Haiku 5.5: claude-haiku-5-5
Previous Haiku model: Claude Haiku 4.5: claude-haiku-4-5-20251001
```

## 呼叫 API

### 基本請求與回應

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{"role": "user", "content": "Hello, Claude"}'
  ```

  ```python Python
  import anthropic

  message = anthropic.Anthropic().messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello, Claude"}],
  )
  print(message)
  ```
</CodeGroup>

```json Output
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello!"
    }
  ],
  "model": "claude-opus-5-5",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 12,
    "output_tokens": 6
  }
}
```

### 多輪對話

Messages API 是無狀態的（stateless），這表示您每次都必須將完整的對話歷史傳送給 API。您可以利用這種模式逐步建立對話。先前的對話輪次不一定要真的來自 Claude，您可以使用合成的 `assistant` 訊息。

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  messages:
    - role: user
      content: Hello, Claude
    - role: assistant
      content: Hello!
    - role: user
      content: Can you describe LLMs to me?
  YAML
  ```

  ```python Python
  import anthropic

  message = anthropic.Anthropic().messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[
          {"role": "user", "content": "Hello, Claude"},
          {"role": "assistant", "content": "Hello!"},
          {"role": "user", "content": "Can you describe LLMs to me?"},
      ],
  )
  print(message)
  ```
</CodeGroup>

### 預填 Claude 的回應

您可以在輸入訊息列表的最後一個位置預填（prefill）Claude 回應的一部分。使用此技巧可以塑造 Claude 的回應。以下範例使用 `"max_tokens": 1` 從 Claude 取得單一的選擇題答案。

<Note>
  Claude 4.6 及更新的模型以及 Claude Mythos Preview 不支援 assistant 訊息預填；對這些模型的請求必須以 user 訊息結尾。以下範例使用支援預填的模型。
</Note>

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  ant messages create <<'YAML'
  model: claude-sonnet-4-5
  max_tokens: 1
  messages:
    - role: user
      content: "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"
    - role: assistant
      content: "The answer is ("
  YAML
  ```

  ```python Python
  import anthropic

  message = anthropic.Anthropic().messages.create(
      model="claude-sonnet-4-5",
      max_tokens=1,
      messages=[
          {
              "role": "user",
              "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
          },
          {"role": "assistant", "content": "The answer is ("},
      ],
  )
  print(message.content[0].text)
  ```
</CodeGroup>

### 視覺

Claude 可以讀取請求中的文字與圖片。圖片支援 `base64` 與 `url` 兩種來源類型，以及 `image/jpeg`、`image/png`、`image/gif` 和 `image/webp` 媒體類型。

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  IMAGE_URL="https://platform.claude.com/docs/images/vision-example.jpg"

  # 選項 1：Base64 編碼的圖片（@ 前綴會自動將二進位檔案編碼為 base64）
  curl -sSo vision-example.jpg "$IMAGE_URL"

  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  messages:
    - role: user
      content:
        - type: image
          source:
            type: base64
            media_type: image/jpeg
            data: "@./vision-example.jpg"
        - type: text
          text: What is in the above image?
  YAML

  # 選項 2：以 URL 參照的圖片
  ant messages create <<YAML
  model: claude-opus-5-5
  max_tokens: 1024
  messages:
    - role: user
      content:
        - type: image
          source:
            type: url
            url: $IMAGE_URL
        - type: text
          text: What is in the above image?
  YAML
  ```

  ```python Python
  import anthropic
  import base64
  import httpx2

  # 選項 1：Base64 編碼的圖片
  image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
  image_media_type = "image/jpeg"
  image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")

  message = anthropic.Anthropic().messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[
          {
              "role": "user",
              "content": [
                  {
                      "type": "image",
                      "source": {
                          "type": "base64",
                          "media_type": image_media_type,
                          "data": image_data,
                      },
                  },
                  {"type": "text", "text": "What is in the above image?"},
              ],
          }
      ],
  )
  print(next(block.text for block in message.content if block.type == "text"))

  # 選項 2：URL 參照的圖片
  message_from_url = anthropic.Anthropic().messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[
          {
              "role": "user",
              "content": [
                  {
                      "type": "image",
                      "source": {
                          "type": "url",
                          "url": "https://platform.claude.com/docs/images/vision-example.jpg",
                      },
                  },
                  {"type": "text", "text": "What is in the above image?"},
              ],
          }
      ],
  )
  print(next(block.text for block in message_from_url.content if block.type == "text"))
  ```
</CodeGroup>

## 思考

思考有時能幫助 Claude 處理非常困難的任務。目前的機制是[「adaptive thinking」（自適應思考）](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)（`thinking: {"type": "adaptive"}`）：Claude 會自行決定何時思考以及思考多少，而您可以透過 [`effort`](https://platform.claude.com/docs/zh-TW/build-with-claude/effort) 參數（而非 token 預算）來引導思考深度。Claude 4.6 及更新的模型以及 Claude Mythos Preview 支援自適應思考。在 Claude 5 及更新的模型以及 Claude Mythos Preview 上，省略 `thinking` 參數時，思考預設為開啟。

在所有模型上，只要啟用思考，temperature 就必須設為 1（或不設定）。在 Claude 4.7 及更新的模型以及 Claude Mythos Preview 上，`temperature` 已被棄用，即使關閉思考，也只接受其預設值。

以下模型支援思考：

* Claude Opus 5.5（`claude-opus-5-5`，僅限自適應思考，始終開啟）
* Claude Sonnet 5.5（`claude-sonnet-5-5`，僅限自適應思考，預設開啟；`thinking: {"type": "disabled"}` 會回傳 400 錯誤，因此請傳送 `thinking: {"type": "between_tools"}` 來關閉預先思考）
* Claude Haiku 5.5（`claude-haiku-5-5`，僅限自適應思考，預設開啟）
* Claude Fable 5.1（`claude-fable-5-1`，僅限自適應思考，始終開啟）
* Claude Mythos 5.1（`claude-mythos-5-1`，僅限自適應思考，始終開啟）
* Claude Fable 5（`claude-fable-5`，僅限自適應思考，始終開啟）
* Claude Mythos 5（`claude-mythos-5`，僅限自適應思考，始終開啟）
* Claude Opus 5（claude-opus-5，僅限自適應思考，預設開啟）
* Claude Sonnet 5（`claude-sonnet-5`，僅限自適應思考，預設開啟）
* Claude Opus 4.8（claude-opus-4-8，僅限自適應思考）
* Claude Opus 4.7（`claude-opus-4-7`，僅限自適應思考）
* Claude Opus 4.6（`claude-opus-4-6`，自適應或舊版手動思考）
* Claude Sonnet 4.6（`claude-sonnet-4-6`，自適應或舊版手動思考）
* Claude Opus 4.5（`claude-opus-4-5-20251101`，僅限舊版手動思考）
* Claude Sonnet 4.5（`claude-sonnet-4-5-20250929`，[已棄用](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)，僅限舊版手動思考）
* Claude Haiku 4.5（`claude-haiku-4-5-20251001`，僅限舊版手動思考）

<Note>
  在 Claude 4.7 及更新的模型上，不支援手動擴展思考（帶有 `budget_tokens` 值的 `type: enabled`），並會傳回 400 錯誤。請改用[自適應思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)（`type: adaptive`）。
</Note>

### 思考的運作方式

當思考開啟時，Claude 會建立 `thinking` 內容區塊，在其中輸出其內部推理。API 回應會包含 `thinking` 內容區塊，後面接著 `text` 內容區塊。

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  ant messages create --transform content --format yaml <<'YAML'
  model: claude-opus-5-5
  max_tokens: 16000
  thinking:
    type: adaptive
    display: summarized
  messages:
    - role: user
      content: Are there an infinite number of prime numbers such that n mod 4 == 3?
  YAML
  ```

  ```python Python
  import anthropic

  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      thinking={"type": "adaptive", "display": "summarized"},
      messages=[
          {
              "role": "user",
              "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
          }
      ],
  )

  # 回應包含摘要的思考區塊與文字區塊
  for block in response.content:
      match block.type:
          case "thinking":
              print(f"\nThinking summary: {block.thinking}")
          case "text":
              print(f"\nResponse: {block.text}")
  ```
</CodeGroup>

手動擴展思考（`thinking: {"type": "enabled", "budget_tokens": N}`）是舊版機制。它僅適用於支援思考的 Claude 4 至 4.6 模型；Claude 4.7 及更新的模型會以 400 錯誤拒絕 `type: enabled`，並改用 [自適應思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)。使用手動擴展思考時，`budget_tokens` 設定 Claude 可用於內部推理過程的最大 token 數量；此限制適用於完整的思考 token，而非摘要後的輸出。除非您使用 [交錯思考](https://platform.claude.com/docs/zh-TW/claude_api_primer#interleaved-thinking)，否則 `budget_tokens` 必須小於 `max_tokens`，以便 Claude 在思考完成後有空間撰寫回應。

## 思考搭配工具使用

思考可以與 tool use（工具使用）一起使用，讓 Claude 能夠對工具選擇與結果處理進行推理。

重要限制：

1. **工具選擇限制：** 使用手動擴展思考（`thinking: {"type": "enabled"}`）時，僅支援 `tool_choice: {"type": "auto"}`（預設）或 `tool_choice: {"type": "none"}`。自適應思考接受強制工具使用，但[強制工具使用](https://platform.claude.com/docs/zh-TW/claude_api_primer#forcing-tool-use)一節所列的模型除外。在接受的情況下，強制工具呼叫會跳過思考：回應會直接以工具呼叫開始，且沒有 `thinking` 區塊。
2. **保留思考區塊：** 在工具使用期間，您必須將最後一則 assistant 訊息的 `thinking` 區塊傳回 API。

### 保留思考區塊

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  # 第一個請求：將 assistant 內容陣列（thinking + tool_use
  # 區塊，簽章完整）擷取為精簡的 JSON。
  ASSISTANT_CONTENT=$(ant messages create \
    --transform content --format jsonl <<'YAML'
  model: claude-opus-5-5
  max_tokens: 16000
  thinking:
    type: adaptive
    display: summarized
  tools:
    - name: get_weather
      description: Get the current weather for a location.
      input_schema:
        type: object
        properties:
          location:
            type: string
            description: The city name.
        required: [location]
  messages:
    - role: user
      content: "What's the weather in Paris?"
  YAML
  )

  TOOL_USE_ID=$(printf '%s' "$ASSISTANT_CONTENT" \
    | jq -r '.[] | select(.type == "tool_use") | .id')

  # 第二個請求：將擷取的區塊原封不動地作為 assistant
  # 訊息傳回。thinking 區塊必須伴隨 tool_use 區塊。
  ant messages create <<YAML
  model: claude-opus-5-5
  max_tokens: 16000
  thinking:
    type: adaptive
    display: summarized
  tools:
    - name: get_weather
      description: Get the current weather for a location.
      input_schema:
        type: object
        properties:
          location:
            type: string
            description: The city name.
        required: [location]
  messages:
    - role: user
      content: "What's the weather in Paris?"
    - role: assistant
      content: $ASSISTANT_CONTENT
    - role: user
      content:
        - type: tool_result
          tool_use_id: $TOOL_USE_ID
          content: "Current temperature: 72°F"
  YAML
  ```

  ```python Python
  import anthropic

  client = anthropic.Anthropic()

  weather_tool = {
      "name": "get_weather",
      "description": "Get the current weather for a location.",
      "input_schema": {
          "type": "object",
          "properties": {"location": {"type": "string", "description": "The city name."}},
          "required": ["location"],
      },
  }

  weather_data = {"temperature": 72}

  # 第一次請求 - Claude 以思考與工具請求回應
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      thinking={"type": "adaptive", "display": "summarized"},
      tools=[weather_tool],
      messages=[{"role": "user", "content": "What's the weather in Paris?"}],
  )

  # 擷取思考區塊與工具使用區塊
  thinking_block = next(
      (block for block in response.content if block.type == "thinking"), None
  )
  tool_use_block = next(
      (block for block in response.content if block.type == "tool_use"), None
  )

  # 第二次請求 - 包含思考區塊與工具結果
  continuation = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      thinking={"type": "adaptive", "display": "summarized"},
      tools=[weather_tool],
      messages=[
          {"role": "user", "content": "What's the weather in Paris?"},
          # 請注意 thinking_block 與 tool_use_block 都會一併傳入
          {"role": "assistant", "content": [thinking_block, tool_use_block]},
          {
              "role": "user",
              "content": [
                  {
                      "type": "tool_result",
                      "tool_use_id": tool_use_block.id,
                      "content": f"Current temperature: {weather_data['temperature']}°F",
                  }
              ],
          },
      ],
  )

  for block in continuation.content:
      if block.type == "text":
          print(block.text)
  ```
</CodeGroup>

### 交錯思考

「Interleaved thinking」（交錯思考）讓 Claude 能夠在工具呼叫之間進行思考，在決定下一步之前推理工具結果。

<Info>
  在具有[自適應思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)（`thinking: {type: "adaptive"}`）的模型上，交錯思考會自動啟用，不需要 beta 標頭。Sonnet 4.6 同時支援搭配手動擴展思考的 `interleaved-thinking-2025-05-14` beta 標頭以及自適應思考。
</Info>

在使用手動擴展思考的較舊模型（Claude 4、4.5 和 Sonnet 4.6 模型）上，請在您的 API 請求中加入 beta 標頭 `interleaved-thinking-2025-05-14` 以啟用交錯思考：

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  ant beta:messages create --beta interleaved-thinking-2025-05-14 <<'YAML'
  model: claude-sonnet-4-6
  max_tokens: 16000
  thinking:
    type: enabled
    budget_tokens: 10000
  tools:
    - name: calculator
      description: Perform arithmetic calculations.
      input_schema:
        type: object
        properties:
          expression:
            type: string
            description: The math expression to evaluate.
        required:
          - expression
    - name: database_query
      description: Query the product database.
      input_schema:
        type: object
        properties:
          query:
            type: string
            description: The database query.
        required:
          - query
  messages:
    - role: user
      content: "What's the total revenue if we sold 150 units of product A at $50 each?"
  YAML
  ```

  ```python Python
  import anthropic

  client = anthropic.Anthropic()

  calculator_tool = {
      "name": "calculator",
      "description": "Perform arithmetic calculations.",
      "input_schema": {
          "type": "object",
          "properties": {
              "expression": {
                  "type": "string",
                  "description": "The math expression to evaluate.",
              }
          },
          "required": ["expression"],
      },
  }

  database_tool = {
      "name": "database_query",
      "description": "Query the product database.",
      "input_schema": {
          "type": "object",
          "properties": {
              "query": {"type": "string", "description": "The database query."}
          },
          "required": ["query"],
      },
  }

  response = client.beta.messages.create(
      model="claude-sonnet-4-6",
      max_tokens=16000,
      thinking={"type": "enabled", "budget_tokens": 10000},
      tools=[calculator_tool, database_tool],
      messages=[
          {
              "role": "user",
              "content": "What's the total revenue if we sold 150 units of product A at $50 each?",
          }
      ],
      betas=["interleaved-thinking-2025-05-14"],
  )

  for block in response.content:
      match block.type:
          case "thinking":
              print(f"Thinking: {block.thinking}")
          case "tool_use":
              print(f"Tool call: {block.name}({block.input})")
          case "text":
              print(f"Response: {block.text}")
  ```
</CodeGroup>

使用交錯思考時，且僅限於交錯思考（而非一般的手動擴展思考），`budget_tokens` 可以超過 `max_tokens` 參數，因為在此情況下 `budget_tokens` 代表一個 assistant 輪次內所有思考區塊的總預算。

## 工具使用

### 指定用戶端工具

用戶端工具在 API 請求的 `tools` 頂層參數中指定。每個工具定義包含：

| 參數             | 說明                                                    |
| -------------- | ----------------------------------------------------- |
| `name`         | 工具的名稱。必須符合正規表示式 `^[a-zA-Z0-9_-]{1,128}$`。             |
| `description`  | 詳細的純文字說明，描述工具的功能、應在何時使用以及其行為方式。                       |
| `input_schema` | 定義工具預期參數的 [JSON Schema](https://json-schema.org/) 物件。 |

```json
{
  "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"]
  }
}
```

### 工具定義的最佳實務

**提供極為詳細的描述。** 這是影響工具效能最重要的因素。您的描述應說明工具的每個細節，包括：

* 工具的功能
* 應於何時使用（以及何時不應使用）
* 每個參數的意義及其如何影響工具的行為
* 任何重要的注意事項或限制

**對於複雜的工具，請考慮使用 `input_examples`。** 對於具有巢狀物件、選用參數或對格式敏感之輸入的工具，您可以使用 `input_examples` 欄位（beta）提供具體範例。這有助於 Claude 理解預期的輸入模式。詳情請參閱 [提供工具使用範例](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools#providing-tool-use-examples)。

良好工具描述的範例：

```json
{
  "name": "get_stock_price",
  "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string",
        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
      }
    },
    "required": ["ticker"]
  }
}
```

## 控制 Claude 的輸出

### 強制工具使用

您可以在 `tool_choice` 欄位中指定工具，以強制 Claude 使用特定工具：

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

使用 `tool_choice` 參數時，有四個可能的選項：

* `auto` 允許 Claude 決定是否呼叫任何提供的工具（預設）。
* `any` 告訴 Claude 必須使用其中一個提供的工具。
* `tool` 強制 Claude 始終使用特定工具。
* `none` 防止 Claude 使用任何工具。

在 Claude Opus 5.5、Claude Sonnet 5.5、Claude Fable 5.1 和 Claude Mythos 5.1 上，`any` 和 `tool` 會傳回 400 錯誤。請將 `tool_choice` 保持為 `auto`，並在工具定義上設定 `"strict": true`，以確保 Claude 進行的任何呼叫都符合工具的 `input_schema`。請參閱[嚴格工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/strict-tool-use)。

### JSON 輸出

工具不一定要是用戶端函式。只要您希望模型回傳符合所提供 schema 的 JSON 輸出，隨時都可以使用工具。

### 平行工具使用

預設情況下，Claude 可能會使用多個工具來回答使用者的查詢。您可以設定 `disable_parallel_tool_use=true` 來停用此行為。

## 處理工具使用與工具結果內容區塊

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

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

* `id`：此特定工具使用區塊的唯一識別碼。
* `name`：所使用工具的名稱。
* `input`：包含傳遞給工具之輸入的物件。

```json
{
  "role": "assistant",
  "content": [
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": { "location": "San Francisco, CA" }
    }
  ]
}
```

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

1. 從 `tool_use` 區塊中擷取 `name`、`id` 和 `input`。
2. 在您的程式碼庫中執行與該工具名稱對應的實際工具。
3. 傳送包含 `tool_result` 的新訊息以繼續對話：

```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "15 degrees"
    }
  ]
}
```

### 處理 `max_tokens` 停止原因

如果 Claude 的回應在工具使用期間因達到 `max_tokens` 限制而被截斷，請以更高的 `max_tokens` 值重試請求。

### 處理 `pause_turn` 停止原因

使用網頁搜尋等伺服器工具時，API 可能會回傳 `pause_turn` 停止原因。請在後續請求中將暫停的回應原封不動地傳回，以繼續對話。

## 錯誤疑難排解

### 工具執行錯誤

如果工具本身在執行期間拋出錯誤，請以 `"is_error": true` 回傳錯誤訊息：

```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 嘗試使用工具的方式無效（例如缺少必要參數），請在工具定義中使用更詳細的 `description` 值再次嘗試請求。

## 串流訊息

建立 Message 時，您可以設定 `"stream": true`，以使用 server-sent events（伺服器傳送事件），即 SSE，逐步串流（streaming）回應。

### 使用 SDK 進行串流

<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
  ```bash CLI
  ant messages create --stream --format jsonl \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello"}' \
    | jq -rj 'select(.delta.type? == "text_delta") | .delta.text'
  ```

  ```python Python
  import anthropic

  client = anthropic.Anthropic()

  with client.messages.stream(
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello"}],
      model="claude-opus-5-5",
  ) as stream:
      for text in stream.text_stream:
          print(text, end="", flush=True)
  ```
</CodeGroup>

### 事件類型

每個伺服器傳送事件都包含一個具名的事件類型與相關的 JSON 資料。每個串流使用以下事件流程：

1. `message_start`：包含一個 `content` 為空的 `Message` 物件。
2. 一系列內容區塊，每個區塊都有 `content_block_start`、一個或多個 `content_block_delta` 事件，以及 `content_block_stop`。
3. 一個或多個 `message_delta` 事件，表示對最終 `Message` 物件的頂層變更。
4. 最後一個 `message_stop` 事件。

**警告：** `message_delta` 事件的 `usage` 欄位中顯示的 token 計數是「累計」的。

### 內容區塊 delta 類型

#### 文字 delta

```json
{
  "type": "content_block_delta",
  "index": 0,
  "delta": { "type": "text_delta", "text": "Hello frien" }
}
```

#### 輸入 JSON delta

對於 `tool_use` 內容區塊，delta 是「部分 JSON 字串」：

```json
{"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}
```

#### 思考 delta

搭配串流使用思考時：

```json
{
  "type": "content_block_delta",
  "index": 0,
  "delta": {
    "type": "thinking_delta",
    "thinking": "Let me solve this step by step..."
  }
}
```

### 基本串流請求範例

```sse
event: message_start
data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-5-5", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}

event: message_stop
data: {"type": "message_stop"}
```
