---
title: Claude向けAPI使用入門
url: https://platform.claude.com/docs/ja/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はステートレスです。つまり、常に会話履歴全体を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のレスポンスのプリフィル

入力メッセージリストの最後の位置で、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
  # オプション 1: Base64 エンコードされた画像（@ プレフィックスを付けるとバイナリファイルが自動的に base64 エンコードされます）
  curl -sSo vision-example.jpg https://platform.claude.com/docs/images/vision-example.jpg

  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: https://platform.claude.com/docs/images/vision-example.jpg
        - 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/ja/build-with-claude/thinking)（`thinking: {"type": "adaptive"}`）です。Claudeがいつ、どの程度思考するかを判断し、トークン予算ではなく[`effort`](https://platform.claude.com/docs/ja/build-with-claude/effort)パラメータで思考の深さを調整します。適応型思考は、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/ja/about-claude/model-deprecations)、レガシーの手動思考のみ）
* Claude Haiku 4.5（`claude-haiku-4-5-20251001`、レガシーの手動思考のみ）

<Note>
  Claude 4.7以降のモデルでは、手動の「extended thinking」（拡張思考）（`budget_tokens`値を指定した`type: enabled`）はサポートされておらず、400エラーが返されます。代わりに[適応型思考](https://platform.claude.com/docs/ja/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 <<'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以降のモデルは `type: enabled` を400エラーで拒否し、代わりに[アダプティブ思考](https://platform.claude.com/docs/ja/build-with-claude/thinking)を使用します。手動の拡張思考では、`budget_tokens` はClaudeが内部の推論プロセスに使用できるトークンの最大数を設定します。この制限は要約された出力ではなく、完全な思考トークンに適用されます。[インターリーブ思考](https://platform.claude.com/docs/ja/claude_api_primer#interleaved-thinking)を使用していない限り、思考完了後にClaudeがレスポンスを書くための余地を確保できるよう、`budget_tokens` は `max_tokens` より小さくなければなりません。

## ツール使用を伴う思考

思考は「tool use」（ツール使用）と併用でき、Claudeがツールの選択や結果の処理について推論できるようになります。

重要な制限事項：

1. **ツール選択の制限：** 手動の拡張思考（`thinking: {"type": "enabled"}`）では、`tool_choice: {"type": "auto"}`（デフォルト）または`tool_choice: {"type": "none"}`のみがサポートされます。適応型思考では、[ツール使用の強制](https://platform.claude.com/docs/ja/claude_api_primer#forcing-tool-use)に記載されているモデルを除き、強制的なツール使用が受け付けられます。受け付けられる場合、強制されたツール呼び出しは思考をスキップします。レスポンスはツール呼び出しから始まり、`thinking`ブロックは含まれません。
2. **思考ブロックの保持：** ツール使用中は、最後のassistantメッセージの `thinking` ブロックをAPIに返す必要があります。

### 思考ブロックの保持

<CodeGroup exclude="shell:cURL, shell:CLI, typescript, csharp, go, java, php, ruby">
  ```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
  )

  # 2回目のリクエスト - 思考ブロックとツール結果を含めます
  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?"},
          # tool_use_block だけでなく thinking_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/ja/build-with-claude/thinking)（`thinking: {type: "adaptive"}`）を備えたモデルでは、インターリーブ思考は自動的に有効になります。ベータヘッダーは不要です。Sonnet 4.6は、手動の拡張思考での`interleaved-thinking-2025-05-14`ベータヘッダーと適応型思考の両方をサポートしています。
</Info>

手動の拡張思考を使用する古いモデル（Claude 4、4.5、およびSonnet 4.6モデル）では、APIリクエストにベータヘッダー`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`は、1つのアシスタントターン内のすべての思考ブロックにわたる合計予算を表すためです。

## ツール使用

### クライアントツールの指定

クライアントツールは、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` フィールド（ベータ）を使用して具体的な例を提供できます。これにより、Claudeが期待される入力パターンを理解しやすくなります。詳細については、[ツール使用の例の提供](https://platform.claude.com/docs/ja/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`パラメータを使用する場合、4つのオプションがあります：

* `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/ja/agents-and-tools/tool-use/strict-tool-use)を参照してください。

### JSON出力

ツールは必ずしもクライアント関数である必要はありません。提供されたスキーマに従うJSON出力をモデルに返させたい場合は、いつでもツールを使用できます。

### 並列ツール使用

デフォルトでは、Claudeはユーザーのクエリに答えるために複数のツールを使用することがあります。`disable_parallel_tool_use=true` を設定することで、この動作を無効にできます。

## ツール使用およびツール結果コンテンツブロックの処理

### クライアントツールからの結果の処理

レスポンスの`stop_reason`は`tool_use`となり、次を含む1つ以上の`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` 停止理由の処理

ツール使用中に `max_tokens` の制限に達してClaudeのレスポンスが途中で切れた場合は、より大きな `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を使用してレスポンスを段階的にストリーミングできます。

### SDKでのストリーミング

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

  ```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`、1つ以上の `content_block_delta` イベント、および `content_block_stop` があります。
3. 最終的な `Message` オブジェクトへのトップレベルの変更を示す、1つ以上の `message_delta` イベント。
4. 最後の `message_stop` イベント。

**警告：** `message_delta` イベントの `usage` フィールドに表示されるトークン数は*累積*です。

### コンテンツブロックデルタのタイプ

#### テキストデルタ

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

#### 入力JSONデルタ

`tool_use` コンテンツブロックの場合、デルタは*部分的なJSON文字列*です。

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

#### 思考デルタ

ストリーミングで思考を使用する場合：

```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"}
```
