---
title: コンテキスト編集
url: https://platform.claude.com/docs/ja/build-with-claude/context-editing
description: コンテキスト編集を使用して、会話の拡大に合わせて会話コンテキストを自動的に管理します。
featureMetadata:
  status: beta
  betaHeader: context-management-2025-06-27
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). コンテキスト編集（ツール使用の削除と思考の削除）はリアルタイムで適用されます。
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: beta
    Claude Platform on AWS: beta
    Amazon Bedrock: beta
    Amazon Bedrock (InvokeModel): beta
    Claude Models on Google Cloud (Google managed): beta
    Microsoft Foundry: beta
---

## 概要

<Note>
  ほとんどのユースケースでは、[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)が、長時間実行される会話でコンテキストを管理するための主要な戦略です。このページで説明する戦略は、どのコンテンツをクリアするかをより細かく制御する必要がある特定のシナリオで役立ちます。
</Note>

「context editing」（コンテキスト編集）を使用すると、会話履歴が大きくなるにつれて、特定のコンテンツを選択的にクリアできます。これはコストの最適化や制限内に収めることにとどまらず、Claudeが受け取る内容を積極的に厳選することでもあります。コンテキストは収穫逓減を伴う有限のリソースであり、無関係なコンテンツはモデルの集中力を低下させます。コンテキスト編集により、その厳選作業を実行時にきめ細かく制御できます。コンテキスト管理の背後にあるより広範な原則については、[効果的なコンテキストエンジニアリング](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents)を参照してください。このページでは以下を説明します。

* **ツール結果のクリア：** 古いツール結果が不要になる、ツール使用の多いエージェント型ワークフローに最適です
* **思考ブロックのクリア：** 以前のターンの思考ブロックを管理するためのもので、コンテキストの連続性のために最近の思考を保持するオプションがあります
* **クライアントサイドのSDKコンパクション：** 要約ベースのコンテキスト管理のためのSDKベースの代替手段です（一般的にはサーバーサイドのコンパクションが推奨されます）

| アプローチ         | 実行場所 | 戦略                                                                               | 仕組み                                                                                                                                                                                                                                                                                                                                                    |
| ------------- | ---- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **サーバーサイド**   | API  | ツール結果のクリア（`clear_tool_uses_20250919`）<br />思考ブロックのクリア（`clear_thinking_20251015`） | プロンプトがClaudeに届く前に適用されます。会話履歴から特定のコンテンツをクリアします。各戦略は個別に設定できます。                                                                                                                                                                                                                                                                                           |
| **クライアントサイド** | SDK  | コンパクション                                                                          | [`tool_runner`](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-runner)を使用する場合に[TypeScriptおよびRuby SDK](https://platform.claude.com/docs/ja/cli-sdks-libraries/overview)で利用できます。要約を生成し、会話履歴全体を置き換えます。[クライアントサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/context-editing#client-side-compaction-sdk)を参照してください。 |

## サーバーサイドの戦略

<Note>
  コンテキスト編集はベータ版で、ツール結果のクリアと思考ブロックのクリアをサポートしています。有効にするには、APIリクエストでベータヘッダー`context-management-2025-06-27`を使用してください。

  この機能に関するフィードバックは、[フィードバックフォーム](https://forms.gle/YXC2EKGMhjN1c4L88)からお寄せください。
</Note>

### ツール結果のクリア

`clear_tool_uses_20250919`戦略は、会話コンテキストが設定したしきい値を超えたときにツール結果をクリアします。これは、ツール使用の多いエージェント型ワークフローで特に役立ちます。古いツール結果（ファイルの内容や検索結果など）は、Claudeが処理した後は不要になります。

有効化されると、APIは最も古いツール結果から時系列順に自動的にクリアします。APIはクリアされた各結果を、それが削除されたことをClaudeに示すプレースホルダーテキストに置き換えます。デフォルトでは、ツール結果のみがクリアされます。`clear_tool_inputs`を`true`に設定すると、ツール結果とツール呼び出し（ツール使用のパラメータ）の両方をクリアすることもできます。

### 思考ブロックのクリア

`clear_thinking_20251015`戦略は、以前のアシスタントターンの`thinking`ブロックを管理します。この戦略により思考の保持を制御できます。推論の連続性を維持するためにより多くの思考ブロックを保持するか、コンテキストスペースを節約するためにより積極的にクリアするかを選択できます。

<Tip>
  **デフォルトの動作：** リクエストに`clear_thinking_20251015`戦略が含まれていない場合、デフォルトはモデルクラスによって異なります。

  | モデルクラス         | 以前のすべての思考を保持        | 進行中のターンの思考のみを保持          |
  | -------------- | ------------------- | ------------------------ |
  | Opus           | Claude Opus 4.5以降   | Claude Opus 4.1以前        |
  | Sonnet         | Claude Sonnet 4.6以降 | Claude Sonnet 4.5（非推奨）以前 |
  | Haiku          | Claude Haiku 5.5以降  | Claude Haiku 4.5以前       |
  | FableおよびMythos | すべてのモデル             | （なし）                     |

  デフォルトを上書きするには、この戦略を使用してください。コードが複数のモデルクラスにまたがって実行される場合は、モデルごとのデフォルトに頼らず、この戦略を含めて`keep`を明示的に設定してください。
</Tip>

アシスタントの会話ターンには、複数のコンテンツブロック（たとえばツールを使用する場合）や複数の思考ブロック（たとえば[インターリーブ思考](https://platform.claude.com/docs/ja/build-with-claude/thinking#interleaved-thinking)を使用する場合）が含まれることがあります。

### コンテキスト編集はサーバーサイドで行われる

コンテキスト編集は、プロンプトがClaudeに届く前にサーバーサイドで適用されます。クライアントアプリケーションは、変更されていない完全な会話履歴を保持します。クライアントの状態を編集後のバージョンと同期する必要はありません。通常どおり、完全な会話履歴をローカルで管理し続けてください。

Claude 5.1以降のモデルでは、サーバー側のコンテキスト管理によって思考ブロックが無効化されることはありません。以前のターンに対するクライアント側の編集は、それ以降のすべてのアシスタントターンにおける思考ブロックを無効化する可能性があります。[プレフィックスを変更せずに保つ](https://platform.claude.com/docs/ja/build-with-claude/preserved-thinking#prefix-check)を参照してください。

### コンテキスト編集とプロンプトキャッシング

コンテキスト編集と[プロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching)の相互作用は、戦略によって異なります。

* **ツール結果のクリア：** コンテンツがクリアされると、キャッシュされたプロンプトプレフィックスが無効化されます。これを考慮して、キャッシュの無効化に見合うだけの十分なトークンをクリアしてください。`clear_at_least`パラメータを使用して、毎回最低限のトークン数がクリアされるようにします。コンテンツがクリアされるたびにキャッシュ書き込みコストが発生しますが、後続のリクエストでは新しくキャッシュされたプレフィックスを再利用できます。

* **思考ブロックのクリア：** 思考ブロックがコンテキストに**保持**される（クリアされない）場合、プロンプトキャッシュは維持され、キャッシュヒットが可能になり、入力トークンのコストが削減されます。思考ブロックが**クリア**されると、クリアが発生した時点でキャッシュが無効化されます。キャッシュのパフォーマンスとコンテキストウィンドウの空き容量のどちらを優先するかに基づいて、`keep`パラメータを設定してください。

## サポートされているモデル

コンテキスト編集は、サポートされているすべてのClaudeモデルで利用できます。

## ツール結果のクリアの使用方法

ツール結果のクリアを有効にする最も簡単な方法は、戦略タイプのみを指定することです。その他のすべての[設定オプション](https://platform.claude.com/docs/ja/build-with-claude/context-editing#configuration-options-for-tool-result-clearing)はデフォルト値を使用します。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Search for recent developments in AI"
        }
      ],
      "tools": [
        {
          "type": "web_search_20250305",
          "name": "web_search"
        }
      ],
      "context_management": {
        "edits": [
          {"type": "clear_tool_uses_20250919"}
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: Search for recent developments in AI
  tools:
    - type: web_search_20250305
      name: web_search
  context_management:
    edits:
      - type: clear_tool_uses_20250919
  YAML
  ```

  ```python Python
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[{"role": "user", "content": "Search for recent developments in AI"}],
      tools=[{"type": "web_search_20250305", "name": "web_search"}],
      betas=["context-management-2025-06-27"],
      context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Search for recent developments in AI"
      }
    ],
    tools: [
      {
        type: "web_search_20250305",
        name: "web_search"
      }
    ],
    context_management: {
      edits: [{ type: "clear_tool_uses_20250919" }]
    },
    betas: ["context-management-2025-06-27"]
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new BetaUserMessageParam { Content = "Search for recent developments in AI" }],
      Tools = [
          new BetaWebSearchTool20250305()
      ],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [new BetaClearToolUses20250919Edit()]
      },
      Betas = [AnthropicBeta.ContextManagement2025_06_27]
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Search for recent developments in AI")),
  	},
  	Tools: []anthropic.BetaToolUnionParam{
  		{OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{}},
  	},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{}},
  		},
  	},
  	Betas: []anthropic.AnthropicBeta{
  		anthropic.AnthropicBetaContextManagement2025_06_27,
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;
  import com.anthropic.models.beta.messages.BetaContextManagementConfig;
  import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;
  import com.anthropic.models.beta.AnthropicBeta;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Search for recent developments in AI")
          .addTool(BetaWebSearchTool20250305.builder().build())
          .contextManagement(BetaContextManagementConfig.builder()
              .addEdit(BetaClearToolUses20250919Edit.builder().build())
              .build())
          .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
          .build();

      BetaMessage response = client.beta().messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Search for recent developments in AI']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      tools: [
          ['type' => 'web_search_20250305', 'name' => 'web_search']
      ],
      contextManagement: [
          'edits' => [
              ['type' => 'clear_tool_uses_20250919']
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      { role: "user", content: "Search for recent developments in AI" }
    ],
    tools: [
      { type: "web_search_20250305", name: "web_search" }
    ],
    context_management: {
      edits: [
        { type: "clear_tool_uses_20250919" }
      ]
    },
    betas: ["context-management-2025-06-27"]
  )
  puts response
  ```
</CodeGroup>

### 高度な設定

追加のパラメータを使用して、ツール結果のクリアの動作をカスタマイズできます。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Create a simple command line calculator app using Python"
        }
      ],
      "tools": [
        {
          "type": "text_editor_20250728",
          "name": "str_replace_based_edit_tool",
          "max_characters": 10000
        },
        {
          "type": "web_search_20250305",
          "name": "web_search",
          "max_uses": 3
        }
      ],
      "context_management": {
        "edits": [
          {
            "type": "clear_tool_uses_20250919",
            "trigger": {
              "type": "input_tokens",
              "value": 30000
            },
            "keep": {
              "type": "tool_uses",
              "value": 3
            },
            "clear_at_least": {
              "type": "input_tokens",
              "value": 5000
            },
            "exclude_tools": ["web_search"]
          }
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: Create a simple command line calculator app using Python
  tools:
    - type: text_editor_20250728
      name: str_replace_based_edit_tool
      max_characters: 10000
    - type: web_search_20250305
      name: web_search
      max_uses: 3
  context_management:
    edits:
      - type: clear_tool_uses_20250919
        trigger:
          type: input_tokens
          value: 30000
        keep:
          type: tool_uses
          value: 3
        clear_at_least:
          type: input_tokens
          value: 5000
        exclude_tools:
          - web_search
  YAML
  ```

  ```python Python
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Create a simple command line calculator app using Python",
          }
      ],
      tools=[
          {
              "type": "text_editor_20250728",
              "name": "str_replace_based_edit_tool",
              "max_characters": 10000,
          },
          {"type": "web_search_20250305", "name": "web_search", "max_uses": 3},
      ],
      betas=["context-management-2025-06-27"],
      context_management={
          "edits": [
              {
                  "type": "clear_tool_uses_20250919",
                  # しきい値を超えたときにクリアをトリガーします
                  "trigger": {"type": "input_tokens", "value": 30000},
                  # クリア後に保持するツール使用の数
                  "keep": {"type": "tool_uses", "value": 3},
                  # オプション: 少なくともこのトークン数をクリアします
                  "clear_at_least": {"type": "input_tokens", "value": 5000},
                  # これらのツールをクリア対象から除外します
                  "exclude_tools": ["web_search"],
              }
          ]
      },
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Create a simple command line calculator app using Python"
      }
    ],
    tools: [
      {
        type: "text_editor_20250728",
        name: "str_replace_based_edit_tool",
        max_characters: 10000
      },
      {
        type: "web_search_20250305",
        name: "web_search",
        max_uses: 3
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_tool_uses_20250919",
          // しきい値を超えたときにクリアをトリガーします
          trigger: {
            type: "input_tokens",
            value: 30000
          },
          // クリア後に保持するツール使用の数
          keep: {
            type: "tool_uses",
            value: 3
          },
          // オプション: 少なくともこのトークン数をクリアします
          clear_at_least: {
            type: "input_tokens",
            value: 5000
          },
          // これらのツールをクリア対象から除外します
          exclude_tools: ["web_search"]
        }
      ]
    }
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [
          new BetaUserMessageParam { Content = "Create a simple command line calculator app using Python" }
      ],
      Tools = [
          new BetaToolTextEditor20250728 { MaxCharacters = 10000 },
          new BetaWebSearchTool20250305 { MaxUses = 3 }
      ],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [
              new BetaClearToolUses20250919Edit
              {
                  Trigger = new BetaInputTokensTrigger(30000),
                  Keep = new BetaToolUsesKeep(3),
                  ClearAtLeast = new BetaInputTokensClearAtLeast(5000),
                  ExcludeTools = ["web_search"]
              }
          ]
      }
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Create a simple command line calculator app using Python")),
  	},
  	Tools: []anthropic.BetaToolUnionParam{
  		{OfTextEditor20250728: &anthropic.BetaToolTextEditor20250728Param{
  			MaxCharacters: anthropic.Int(10000),
  		}},
  		{OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{
  			MaxUses: anthropic.Int(3),
  		}},
  	},
  	Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{
  				Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{
  					OfInputTokens: &anthropic.BetaInputTokensTriggerParam{
  						Value: 30000,
  					},
  				},
  				Keep: anthropic.BetaToolUsesKeepParam{
  					Value: 3,
  				},
  				ClearAtLeast: anthropic.BetaInputTokensClearAtLeastParam{
  					Value: 5000,
  				},
  				ExcludeTools: []string{"web_search"},
  			}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaToolTextEditor20250728;
  import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;
  import com.anthropic.models.beta.messages.BetaContextManagementConfig;
  import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;
  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;
  import com.anthropic.models.beta.messages.BetaInputTokensClearAtLeast;
  import com.anthropic.models.beta.messages.BetaToolUsesKeep;
  import com.anthropic.models.beta.AnthropicBeta;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Create a simple command line calculator app using Python")
          .addTool(BetaToolTextEditor20250728.builder()
              .maxCharacters(10000L)
              .build())
          .addTool(BetaWebSearchTool20250305.builder()
              .maxUses(3L)
              .build())
          .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
          .contextManagement(BetaContextManagementConfig.builder()
              .addEdit(BetaClearToolUses20250919Edit.builder()
                  .trigger(BetaInputTokensTrigger.builder()
                      .value(30000L)
                      .build())
                  .keep(BetaToolUsesKeep.builder()
                      .value(3L)
                      .build())
                  .clearAtLeast(BetaInputTokensClearAtLeast.builder()
                      .value(5000L)
                      .build())
                  .addExcludeTool("web_search")
                  .build())
              .build())
          .build();

      BetaMessage response = client.beta().messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => 'Create a simple command line calculator app using Python'
          ]
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      tools: [
          [
              'type' => 'text_editor_20250728',
              'name' => 'str_replace_based_edit_tool',
              'max_characters' => 10000
          ],
          [
              'type' => 'web_search_20250305',
              'name' => 'web_search',
              'max_uses' => 3
          ]
      ],
      contextManagement: [
          'edits' => [
              [
                  'type' => 'clear_tool_uses_20250919',
                  'trigger' => [
                      'type' => 'input_tokens',
                      'value' => 30000
                  ],
                  'keep' => [
                      'type' => 'tool_uses',
                      'value' => 3
                  ],
                  'clear_at_least' => [
                      'type' => 'input_tokens',
                      'value' => 5000
                  ],
                  'exclude_tools' => ['web_search']
              ]
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Create a simple command line calculator app using Python"
      }
    ],
    tools: [
      {
        type: "text_editor_20250728",
        name: "str_replace_based_edit_tool",
        max_characters: 10000
      },
      {
        type: "web_search_20250305",
        name: "web_search",
        max_uses: 3
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_tool_uses_20250919",
          trigger: {
            type: "input_tokens",
            value: 30000
          },
          keep: {
            type: "tool_uses",
            value: 3
          },
          clear_at_least: {
            type: "input_tokens",
            value: 5000
          },
          exclude_tools: ["web_search"]
        }
      ]
    }
  )
  puts response
  ```
</CodeGroup>

## 思考ブロックのクリアの使用方法

以前のターンの思考ブロックを含む会話で、コンテキストとプロンプトキャッシングを管理するには、思考ブロックのクリアを使用します。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 16000,
      "messages": [{"role": "user", "content": "Hello"}],
      "context_management": {
        "edits": [
          {
            "type": "clear_thinking_20251015",
            "keep": {
              "type": "thinking_turns",
              "value": 2
            }
          }
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 16000
  messages:
    - role: user
      content: Hello
  context_management:
    edits:
      - type: clear_thinking_20251015
        keep:
          type: thinking_turns
          value: 2
  YAML
  ```

  ```python Python
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      messages=[{"role": "user", "content": "Hello"}],
      betas=["context-management-2025-06-27"],
      context_management={
          "edits": [
              {
                  "type": "clear_thinking_20251015",
                  "keep": {"type": "thinking_turns", "value": 2},
              }
          ]
      },
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    messages: [{ role: "user", content: "Hello" }],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: {
            type: "thinking_turns",
            value: 2
          }
        }
      ]
    }
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 16000,
      Messages = [new BetaUserMessageParam { Content = "Hello" }],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [
              new BetaClearThinking20251015Edit
              {
                  Keep = new BetaThinkingTurns(2)
              }
          ]
      }
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 16000,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),
  	},
  	Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{
  				Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{
  					OfThinkingTurns: &anthropic.BetaThinkingTurnsParam{
  						Value: 2,
  					},
  				},
  			}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaContextManagementConfig;
  import com.anthropic.models.beta.messages.BetaClearThinking20251015Edit;
  import com.anthropic.models.beta.messages.BetaThinkingTurns;
  import com.anthropic.models.beta.AnthropicBeta;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(16000L)
          .addUserMessage("Hello")
          .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
          .contextManagement(BetaContextManagementConfig.builder()
              .addEdit(BetaClearThinking20251015Edit.builder()
                  .keep(BetaThinkingTurns.builder()
                      .value(2L)
                      .build())
                  .build())
              .build())
          .build();

      BetaMessage response = client.beta().messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 16000,
      messages: [
          ['role' => 'user', 'content' => 'Hello']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      contextManagement: [
          'edits' => [
              [
                  'type' => 'clear_thinking_20251015',
                  'keep' => [
                      'type' => 'thinking_turns',
                      'value' => 2
                  ]
              ]
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 16000,
    messages: [{ role: "user", content: "Hello" }],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: {
            type: "thinking_turns",
            value: 2
          }
        }
      ]
    }
  )
  puts response
  ```
</CodeGroup>

### 思考ブロックのクリアの設定オプション

`clear_thinking_20251015`戦略は、次の設定をサポートしています。

| 設定オプション | デフォルト                                | 説明                                                                                                                                      |
| ------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| `keep`  | `{type: "thinking_turns", value: 1}` | 思考ブロックを保持する最近のアシスタントターンの数を定義します。最後のNターンを保持するには`{type: "thinking_turns", value: N}`（Nは0より大きい必要があります）を使用し、すべての思考ブロックを保持するには`"all"`を使用します。 |

この戦略を含み`keep`を指定しないリクエストは、[モデルごとのデフォルト](https://platform.claude.com/docs/ja/build-with-claude/context-editing#thinking-block-clearing)がすべての思考を保持するモデルを含め、すべてのモデルで`{type: "thinking_turns", value: 1}`が適用されます。この戦略を含まないリクエストには、モデルごとのデフォルトが適用されます。

Nには、進行中のアシスタントターンと、思考ブロックを含まないターンも数えられます。`tool_result`ブロックのみを含むユーザーメッセージは、進行中のターンを継続します。それ以外のユーザーメッセージは新しいターンを開始します。リクエストが新しいターンを開始するメッセージで終わる場合、値が1であれば、それ以前のすべてのアシスタントターンの思考がクリアされます。

**設定例：**

進行中のターンを含めて、最後の3つのアシスタントターンの思考ブロックを保持する：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 16000,
      "messages": [{"role": "user", "content": "Hello"}],
      "context_management": {
        "edits": [
          {
            "type": "clear_thinking_20251015",
            "keep": {
              "type": "thinking_turns",
              "value": 3
            }
          }
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 16000
  messages:
    - role: user
      content: Hello
  context_management:
    edits:
      - type: clear_thinking_20251015
        keep:
          type: thinking_turns
          value: 3
  YAML
  ```

  ```python Python
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      messages=[{"role": "user", "content": "Hello"}],
      betas=["context-management-2025-06-27"],
      context_management={
          "edits": [
              {
                  "type": "clear_thinking_20251015",
                  "keep": {"type": "thinking_turns", "value": 3},
              }
          ]
      },
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    messages: [{ role: "user", content: "Hello" }],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: {
            type: "thinking_turns",
            value: 3
          }
        }
      ]
    }
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 16000,
      Messages = [new BetaUserMessageParam { Content = "Hello" }],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [
              new BetaClearThinking20251015Edit
              {
                  Keep = new BetaThinkingTurns(3)
              }
          ]
      }
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 16000,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),
  	},
  	Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{
  				Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{
  					OfThinkingTurns: &anthropic.BetaThinkingTurnsParam{
  						Value: 3,
  					},
  				},
  			}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(16000L)
      .addUserMessage("Hello")
      .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
      .contextManagement(BetaContextManagementConfig.builder()
          .addEdit(BetaClearThinking20251015Edit.builder()
              .keep(BetaThinkingTurns.builder()
                  .value(3L)
                  .build())
              .build())
          .build())
      .build();

  BetaMessage response = client.beta().messages().create(params);
  IO.println(response);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 16000,
      messages: [
          ['role' => 'user', 'content' => 'Hello']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      contextManagement: [
          'edits' => [
              [
                  'type' => 'clear_thinking_20251015',
                  'keep' => [
                      'type' => 'thinking_turns',
                      'value' => 3
                  ]
              ]
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 16000,
    messages: [{ role: "user", content: "Hello" }],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: {
            type: "thinking_turns",
            value: 3
          }
        }
      ]
    }
  )
  puts response
  ```
</CodeGroup>

すべての思考ブロックを保持する（キャッシュヒットを最大化）：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 16000,
      "messages": [{"role": "user", "content": "Hello"}],
      "context_management": {
        "edits": [
          {
            "type": "clear_thinking_20251015",
            "keep": "all"
          }
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 16000
  messages:
    - role: user
      content: Hello
  context_management:
    edits:
      - type: clear_thinking_20251015
        keep: all
  YAML
  ```

  ```python Python
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      messages=[{"role": "user", "content": "Hello"}],
      betas=["context-management-2025-06-27"],
      context_management={
          "edits": [
              {
                  "type": "clear_thinking_20251015",
                  "keep": "all",
              }
          ]
      },
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    messages: [{ role: "user", content: "Hello" }],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: "all"
        }
      ]
    }
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 16000,
      Messages = [new BetaUserMessageParam { Content = "Hello" }],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [
              new BetaClearThinking20251015Edit
              {
                  Keep = new All()
              }
          ]
      }
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 16000,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),
  	},
  	Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{
  				Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{
  					OfAll: constant.ValueOf[constant.All](),
  				},
  			}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(16000L)
      .addUserMessage("Hello")
      .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
      .contextManagement(BetaContextManagementConfig.builder()
          .addEdit(BetaClearThinking20251015Edit.builder()
              .keepAll()
              .build())
          .build())
      .build();

  BetaMessage response = client.beta().messages().create(params);
  IO.println(response);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 16000,
      messages: [
          ['role' => 'user', 'content' => 'Hello']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      contextManagement: [
          'edits' => [
              [
                  'type' => 'clear_thinking_20251015',
                  'keep' => 'all'
              ]
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 16000,
    messages: [{ role: "user", content: "Hello" }],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: "all"
        }
      ]
    }
  )
  puts response
  ```
</CodeGroup>

### 戦略の組み合わせ

思考ブロックのクリアとツール結果のクリアを併用できます。

<Note>
  複数の戦略を使用する場合は、`edits`配列の最初に`clear_thinking_20251015`戦略を記載する必要があります。
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 16000,
      "messages": [
        {
          "role": "user",
          "content": "Search for the latest developments in quantum error correction and summarize the key breakthroughs."
        }
      ],
      "tools": [
        {
          "type": "web_search_20250305",
          "name": "web_search",
          "max_uses": 5
        }
      ],
      "context_management": {
        "edits": [
          {
            "type": "clear_thinking_20251015",
            "keep": {
              "type": "thinking_turns",
              "value": 2
            }
          },
          {
            "type": "clear_tool_uses_20250919",
            "trigger": {
              "type": "input_tokens",
              "value": 50000
            },
            "keep": {
              "type": "tool_uses",
              "value": 5
            }
          }
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 16000
  messages:
    - role: user
      content: Search for the latest developments in quantum error correction and summarize the key breakthroughs.
  tools:
    - type: web_search_20250305
      name: web_search
      max_uses: 5
  context_management:
    edits:
      - type: clear_thinking_20251015
        keep:
          type: thinking_turns
          value: 2
      - type: clear_tool_uses_20250919
        trigger:
          type: input_tokens
          value: 50000
        keep:
          type: tool_uses
          value: 5
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=16000,
      messages=[
          {
              "role": "user",
              "content": "Search for the latest developments in quantum error correction and summarize the key breakthroughs.",
          }
      ],
      tools=[
          {
              "type": "web_search_20250305",
              "name": "web_search",
              "max_uses": 5,
          }
      ],
      betas=["context-management-2025-06-27"],
      context_management={
          "edits": [
              {
                  "type": "clear_thinking_20251015",
                  "keep": {"type": "thinking_turns", "value": 2},
              },
              {
                  "type": "clear_tool_uses_20250919",
                  "trigger": {"type": "input_tokens", "value": 50000},
                  "keep": {"type": "tool_uses", "value": 5},
              },
          ]
      },
  )

  print(response)
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    messages: [
      {
        role: "user",
        content:
          "Search for the latest developments in quantum error correction and summarize the key breakthroughs."
      }
    ],
    tools: [
      {
        type: "web_search_20250305",
        name: "web_search",
        max_uses: 5
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: {
            type: "thinking_turns",
            value: 2
          }
        },
        {
          type: "clear_tool_uses_20250919",
          trigger: {
            type: "input_tokens",
            value: 50000
          },
          keep: {
            type: "tool_uses",
            value: 5
          }
        }
      ]
    }
  });

  console.log(response);
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 16000,
      Messages = [
          new BetaUserMessageParam { Content = "Search for the latest developments in quantum error correction and summarize the key breakthroughs." }
      ],
      Tools = [
          new BetaWebSearchTool20250305 { MaxUses = 5 }
      ],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [
              new BetaClearThinking20251015Edit
              {
                  Keep = new BetaThinkingTurns(2)
              },
              new BetaClearToolUses20250919Edit
              {
                  Trigger = new BetaInputTokensTrigger(50000),
                  Keep = new BetaToolUsesKeep(5)
              }
          ]
      }
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 16000,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Search for the latest developments in quantum error correction and summarize the key breakthroughs.")),
  	},
  	Tools: []anthropic.BetaToolUnionParam{
  		{OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{
  			MaxUses: anthropic.Int(5),
  		}},
  	},
  	Betas: []anthropic.AnthropicBeta{
  		anthropic.AnthropicBetaContextManagement2025_06_27,
  	},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{
  				Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{
  					OfThinkingTurns: &anthropic.BetaThinkingTurnsParam{
  						Value: 2,
  					},
  				},
  			}},
  			{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{
  				Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{
  					OfInputTokens: &anthropic.BetaInputTokensTriggerParam{
  						Value: 50000,
  					},
  				},
  				Keep: anthropic.BetaToolUsesKeepParam{
  					Value: 5,
  				},
  			}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;
  import com.anthropic.models.beta.messages.BetaContextManagementConfig;
  import com.anthropic.models.beta.messages.BetaClearThinking20251015Edit;
  import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;
  import com.anthropic.models.beta.messages.BetaThinkingTurns;
  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;
  import com.anthropic.models.beta.messages.BetaToolUsesKeep;
  import com.anthropic.models.beta.AnthropicBeta;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(16000L)
          .addUserMessage("Search for the latest developments in quantum error correction and summarize the key breakthroughs.")
          .addTool(BetaWebSearchTool20250305.builder()
              .maxUses(5L)
              .build())
          .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
          .contextManagement(BetaContextManagementConfig.builder()
              .addEdit(BetaClearThinking20251015Edit.builder()
                  .keep(BetaThinkingTurns.builder()
                      .value(2L)
                      .build())
                  .build())
              .addEdit(BetaClearToolUses20250919Edit.builder()
                  .trigger(BetaInputTokensTrigger.builder()
                      .value(50000L)
                      .build())
                  .keep(BetaToolUsesKeep.builder()
                      .value(5L)
                      .build())
                  .build())
              .build())
          .build();

      BetaMessage response = client.beta().messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 16000,
      messages: [
          [
              'role' => 'user',
              'content' => 'Search for the latest developments in quantum error correction and summarize the key breakthroughs.'
          ]
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      tools: [
          [
              'type' => 'web_search_20250305',
              'name' => 'web_search',
              'max_uses' => 5
          ]
      ],
      contextManagement: [
          'edits' => [
              [
                  'type' => 'clear_thinking_20251015',
                  'keep' => [
                      'type' => 'thinking_turns',
                      'value' => 2
                  ]
              ],
              [
                  'type' => 'clear_tool_uses_20250919',
                  'trigger' => [
                      'type' => 'input_tokens',
                      'value' => 50000
                  ],
                  'keep' => [
                      'type' => 'tool_uses',
                      'value' => 5
                  ]
              ]
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 16000,
    messages: [
      {
        role: "user",
        content: "Search for the latest developments in quantum error correction and summarize the key breakthroughs."
      }
    ],
    tools: [
      {
        type: "web_search_20250305",
        name: "web_search",
        max_uses: 5
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_thinking_20251015",
          keep: {
            type: "thinking_turns",
            value: 2
          }
        },
        {
          type: "clear_tool_uses_20250919",
          trigger: {
            type: "input_tokens",
            value: 50000
          },
          keep: {
            type: "tool_uses",
            value: 5
          }
        }
      ]
    }
  )
  puts response
  ```
</CodeGroup>

## ツール結果のクリアの設定オプション

| 設定オプション             | デフォルト         | 説明                                                                                                                       |
| ------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `trigger`           | 100,000入力トークン | コンテキスト編集戦略が有効になるタイミングを定義します。プロンプトがこのしきい値を超えると、クリアが開始されます。この値は`input_tokens`または`tool_uses`のいずれかで指定できます。                   |
| `keep`              | 3ツール使用        | クリアが発生した後に保持する最近のツール使用/結果のペアの数を定義します。APIは最も古いツールのやり取りから削除し、最新のものを保持します。                                                  |
| `clear_at_least`    | なし            | 戦略が有効になるたびに、最低限のトークン数がクリアされるようにします。APIが指定された量以上をクリアできない場合、戦略は適用されません。これは、コンテキストのクリアがプロンプトキャッシュを破棄するに値するかどうかを判断するのに役立ちます。 |
| `exclude_tools`     | なし            | ツール使用と結果を決してクリアしないツール名のリストです。重要なコンテキストを保持するのに役立ちます。                                                                      |
| `clear_tool_inputs` | `false`       | ツール結果とともにツール呼び出しのパラメータもクリアするかどうかを制御します。デフォルトでは、ツール結果のみがクリアされ、Claudeの元のツール呼び出しは表示されたままになります。                              |

## コンテキスト編集のレスポンス

`context_management`レスポンスフィールドを使用すると、リクエストにどのコンテキスト編集が適用されたかを、クリアされたコンテンツと入力トークンに関する有用な統計とともに確認できます。

```json Output
{
  "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message",
  "role": "assistant",
  "content": [
    // ...
  ],
  "usage": {
    // ...
  },
  "context_management": {
    "applied_edits": [
      // When using `clear_thinking_20251015`
      {
        "type": "clear_thinking_20251015",
        "cleared_thinking_turns": 3,
        "cleared_input_tokens": 15000
      },
      // When using `clear_tool_uses_20250919`
      {
        "type": "clear_tool_uses_20250919",
        "cleared_tool_uses": 8,
        "cleared_input_tokens": 50000
      }
    ]
  }
}
```

ストリーミングレスポンスの場合、コンテキスト編集は最後の`message_delta`イベントに含まれます。

```json Streaming Response
{
  "type": "message_delta",
  "delta": {
    "stop_reason": "end_turn",
    "stop_sequence": null
  },
  "usage": {
    "output_tokens": 1024
  },
  "context_management": {
    "applied_edits": [
      // ...
    ]
  }
}
```

## トークンカウント

[トークンカウント](https://platform.claude.com/docs/ja/build-with-claude/token-counting)エンドポイントはコンテキスト管理をサポートしており、コンテキスト編集が適用された後にプロンプトが使用するトークン数をプレビューできます。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "messages": [
        {
          "role": "user",
          "content": "Continue our conversation..."
        }
      ],
      "context_management": {
        "edits": [
          {
            "type": "clear_tool_uses_20250919",
            "trigger": {
              "type": "input_tokens",
              "value": 30000
            },
            "keep": {
              "type": "tool_uses",
              "value": 5
            }
          }
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages count-tokens --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  messages:
    - role: user
      content: Continue our conversation...
  context_management:
    edits:
      - type: clear_tool_uses_20250919
        trigger:
          type: input_tokens
          value: 30000
        keep:
          type: tool_uses
          value: 5
  YAML
  ```

  ```python Python
  response = client.beta.messages.count_tokens(
      model="claude-opus-5-5",
      messages=[{"role": "user", "content": "Continue our conversation..."}],
      betas=["context-management-2025-06-27"],
      context_management={
          "edits": [
              {
                  "type": "clear_tool_uses_20250919",
                  "trigger": {"type": "input_tokens", "value": 30000},
                  "keep": {"type": "tool_uses", "value": 5},
              }
          ]
      },
  )

  print(f"Original tokens: {response.context_management.original_input_tokens}")
  print(f"After clearing: {response.input_tokens}")
  print(
      f"Savings: {response.context_management.original_input_tokens - response.input_tokens} tokens"
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.countTokens({
    model: "claude-opus-5-5",
    messages: [
      {
        role: "user",
        content: "Continue our conversation..."
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_tool_uses_20250919",
          trigger: {
            type: "input_tokens",
            value: 30000
          },
          keep: {
            type: "tool_uses",
            value: 5
          }
        }
      ]
    }
  });

  console.log(`Original tokens: ${response.context_management?.original_input_tokens}`);
  console.log(`After clearing: ${response.input_tokens}`);
  console.log(
    `Savings: ${
      (response.context_management?.original_input_tokens || 0) - response.input_tokens
    } tokens`
  );
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      Messages = [new BetaUserMessageParam { Content = "Continue our conversation..." }],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [
              new BetaClearToolUses20250919Edit
              {
                  Trigger = new BetaInputTokensTrigger(30000),
                  Keep = new BetaToolUsesKeep(5)
              }
          ]
      }
  };

  var response = await client.Beta.Messages.CountTokens(parameters);

  Console.WriteLine($"Original tokens: {response.ContextManagement?.OriginalInputTokens}");
  Console.WriteLine($"After clearing: {response.InputTokens}");
  Console.WriteLine($"Savings: {(response.ContextManagement?.OriginalInputTokens ?? 0) - response.InputTokens} tokens");
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.CountTokens(context.TODO(), anthropic.BetaMessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Continue our conversation...")),
  	},
  	Betas: []anthropic.AnthropicBeta{
  		anthropic.AnthropicBetaContextManagement2025_06_27,
  	},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{
  				Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{
  					OfInputTokens: &anthropic.BetaInputTokensTriggerParam{
  						Value: 30000,
  					},
  				},
  				Keep: anthropic.BetaToolUsesKeepParam{
  					Value: 5,
  				},
  			}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Printf("Original tokens: %d\n", response.ContextManagement.OriginalInputTokens)
  fmt.Printf("After clearing: %d\n", response.InputTokens)
  fmt.Printf("Savings: %d tokens\n", response.ContextManagement.OriginalInputTokens-response.InputTokens)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaMessageTokensCount;
  import com.anthropic.models.beta.messages.MessageCountTokensParams;
  import com.anthropic.models.beta.messages.BetaContextManagementConfig;
  import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;
  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;
  import com.anthropic.models.beta.messages.BetaToolUsesKeep;
  import com.anthropic.models.beta.AnthropicBeta;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCountTokensParams params = MessageCountTokensParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .addUserMessage("Continue our conversation...")
          .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
          .contextManagement(BetaContextManagementConfig.builder()
              .addEdit(BetaClearToolUses20250919Edit.builder()
                  .trigger(BetaInputTokensTrigger.builder()
                      .value(30000L)
                      .build())
                  .keep(BetaToolUsesKeep.builder()
                      .value(5L)
                      .build())
                  .build())
              .build())
          .build();

      BetaMessageTokensCount response = client.beta().messages().countTokens(params);

      IO.println("Original tokens: " + response.contextManagement().get().originalInputTokens());
      IO.println("After clearing: " + response.inputTokens());
      IO.println("Savings: " + (response.contextManagement().get().originalInputTokens() - response.inputTokens()) + " tokens");
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->countTokens(
      messages: [
          ['role' => 'user', 'content' => 'Continue our conversation...']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      contextManagement: [
          'edits' => [
              [
                  'type' => 'clear_tool_uses_20250919',
                  'trigger' => [
                      'type' => 'input_tokens',
                      'value' => 30000
                  ],
                  'keep' => [
                      'type' => 'tool_uses',
                      'value' => 5
                  ]
              ]
          ]
      ],
  );

  echo 'Original tokens: ' . $response->contextManagement->originalInputTokens . "\n";
  echo 'After clearing: ' . $response->inputTokens . "\n";
  echo 'Savings: ' . ($response->contextManagement->originalInputTokens - $response->inputTokens) . " tokens\n";
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    messages: [
      { role: "user", content: "Continue our conversation..." }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        {
          type: "clear_tool_uses_20250919",
          trigger: {
            type: "input_tokens",
            value: 30000
          },
          keep: {
            type: "tool_uses",
            value: 5
          }
        }
      ]
    }
  )

  puts "Original tokens: #{response.context_management.original_input_tokens}"
  puts "After clearing: #{response.input_tokens}"
  puts "Savings: #{response.context_management.original_input_tokens - response.input_tokens} tokens"
  ```
</CodeGroup>

```json Output
{
  "input_tokens": 25000,
  "context_management": {
    "original_input_tokens": 70000
  }
}
```

レスポンスには、コンテキスト管理が適用された後の最終的なトークン数（`input_tokens`）と、クリアが行われる前の元のトークン数（`original_input_tokens`）の両方が表示されます。

## メモリツールとの併用

コンテキスト編集は[メモリツール](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/memory-tool)と組み合わせることができます。会話コンテキストが設定されたクリアのしきい値に近づくと、Claudeは重要な情報を保存するよう自動的に警告を受け取ります。これにより、Claudeはツール結果やコンテキストが会話履歴からクリアされる前に、それらをメモリファイルに保存できます。

この組み合わせにより、次のことが可能になります。

* **重要なコンテキストの保持：** Claudeは、ツール結果がクリアされる前に、その結果から重要な情報をメモリファイルに書き込むことができます。
* **長時間実行されるワークフローの維持：** Claudeは、情報を永続ストレージにオフロードすることで、本来であればコンテキストの制限を超えてしまうエージェント型ワークフローを継続できます。
* **オンデマンドでの情報アクセス：** Claudeは、すべてをアクティブなコンテキストウィンドウに保持するのではなく、必要に応じて以前にクリアされた情報をメモリファイルから参照できます。

たとえば、Claudeが多数の操作を実行するファイル編集ワークフローでは、コンテキストが大きくなるにつれて、Claudeは完了した変更をメモリファイルに要約できます。ツール結果がクリアされても、Claudeはメモリシステムを通じてその情報にアクセスでき、効果的に作業を続けることができます。

両方の機能を併用するには、APIリクエストで両方を有効にします。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -H "anthropic-beta: context-management-2025-06-27" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Hello"
        }
      ],
      "tools": [
        {
          "type": "memory_20250818",
          "name": "memory"
        }
      ],
      "context_management": {
        "edits": [
          {"type": "clear_tool_uses_20250919"}
        ]
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: Hello
  tools:
    - type: memory_20250818
      name: memory
  context_management:
    edits:
      - type: clear_tool_uses_20250919
  YAML
  ```

  ```python Python
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[{"role": "user", "content": "Hello"}],
      tools=[{"type": "memory_20250818", "name": "memory"}],
      betas=["context-management-2025-06-27"],
      context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
  )
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
  });

  const response = await anthropic.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [{ role: "user", content: "Hello" }],
    tools: [
      {
        type: "memory_20250818",
        name: "memory"
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [{ type: "clear_tool_uses_20250919" }]
    }
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta;
  using Anthropic.Models.Beta.Messages;
  using Messages = Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new BetaUserMessageParam { Content = "Hello" }],
      Tools = [
          new BetaMemoryTool20250818()
      ],
      Betas = [AnthropicBeta.ContextManagement2025_06_27],
      ContextManagement = new BetaContextManagementConfig
      {
          Edits = [new BetaClearToolUses20250919Edit()]
      }
  };

  var response = await client.Beta.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),
  	},
  	Tools: []anthropic.BetaToolUnionParam{
  		{OfMemoryTool20250818: &anthropic.BetaMemoryTool20250818Param{}},
  	},
  	Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},
  	ContextManagement: anthropic.BetaContextManagementConfigParam{
  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
  			{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{}},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaMemoryTool20250818;
  import com.anthropic.models.beta.messages.BetaContextManagementConfig;
  import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;
  import com.anthropic.models.beta.AnthropicBeta;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Hello")
          .addTool(BetaMemoryTool20250818.builder().build())
          .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
          .contextManagement(BetaContextManagementConfig.builder()
              .addEdit(BetaClearToolUses20250919Edit.builder().build())
              .build())
          .build();

      BetaMessage response = client.beta().messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->beta->messages->create(
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Hello']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['context-management-2025-06-27'],
      tools: [
          [
              'type' => 'memory_20250818',
              'name' => 'memory'
          ]
      ],
      contextManagement: [
          'edits' => [
              ['type' => 'clear_tool_uses_20250919']
          ]
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [{ role: "user", content: "Hello" }],
    tools: [
      {
        type: "memory_20250818",
        name: "memory"
      }
    ],
    betas: ["context-management-2025-06-27"],
    context_management: {
      edits: [
        { type: "clear_tool_uses_20250919" }
      ]
    }
  )
  puts response
  ```
</CodeGroup>

コマンドや例を含むメモリツールの完全なリファレンスについては、[メモリツール](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/memory-tool)を参照してください。

## クライアントサイドのコンパクション（SDK）

<Warning>
  **Anthropicは、SDKコンパクションよりもサーバーサイドのコンパクションを推奨しています。** [サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)は、統合の複雑さが少なく、トークン使用量の計算がより正確で、クライアントサイドの制限もない状態で、コンテキスト管理を自動的に処理します。要約プロセスをクライアントサイドで制御する必要が特にある場合にのみ、SDKコンパクションを使用してください。

  `compaction_control`パラメータはTypeScriptおよびRuby SDKで非推奨となっており、将来のバージョンで削除されます。TypeScriptおよびRuby SDKは、これが有効になっている場合に非推奨の警告を出力します。Python SDKではv1.0で削除されました。ツールランナーでサーバーサイドのコンパクションを使用するには、リクエストの`context_management`パラメータで`compact_20260112`編集を渡してください。
</Warning>

<Note>
  コンパクションは、[`tool_runner`メソッド](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-runner)を使用する場合に[TypeScriptおよびRuby SDK](https://platform.claude.com/docs/ja/cli-sdks-libraries/overview)で利用できます。
</Note>

「compaction」（コンパクション）は、トークン使用量が大きくなりすぎたときに要約を生成することで、会話コンテキストを自動的に管理するSDKの機能です。コンテンツをクリアするサーバーサイドのコンテキスト編集戦略とは異なり、コンパクションはClaudeに会話履歴を要約するよう指示し、その後、履歴全体をその要約に置き換えます。これにより、Claudeは本来であれば[コンテキストウィンドウ](https://platform.claude.com/docs/ja/build-with-claude/context-windows)を超えてしまう長時間実行タスクの作業を継続できます。

### コンパクションの仕組み

コンパクションが有効になっている場合、SDKは各モデルレスポンスの後にトークン使用量を監視します。

1. **しきい値のチェック：** SDKは合計トークン数を`input_tokens + cache_creation_input_tokens + cache_read_input_tokens + output_tokens`として計算します（キャッシュトークンのフィールドについては[プロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching)を参照してください）。
2. **要約の生成：** しきい値を超えると、要約プロンプトがユーザーターンとして挿入され、Claudeは`<summary></summary>`タグで囲まれた構造化された要約を生成します。
3. **コンテキストの置き換え：** SDKは要約を抽出し、メッセージ履歴全体をそれに置き換えます。
4. **継続：** 会話は要約から再開され、Claudeは中断したところから作業を続けます。

### コンパクションの使用

トークン使用量がしきい値を超えたときに自動要約を有効にするには、`tool_runner`呼び出しに`compaction_control`を追加します。

<Tabs>
  <Tab title="cURL">
    <Note>
      コンパクションはSDKの`tool_runner`ヘルパー内でクライアントサイドで実行されるため、直接対応するHTTPの手段はありません。代わりに、Anthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="CLI">
    <Note>
      CLIには`tool_runner`ヘルパーが含まれていません。代わりに、SDK側の統合なしでAnthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Python">
    <Note>
      v1.0以降、Python SDKのツールランナーはクライアントサイドの`compaction_control`をサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="TypeScript">
    ```typescript TypeScript
    const client = new Anthropic();

    const runner = client.beta.messages.toolRunner({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [readFile],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compactionControl: { enabled: true, contextTokenThreshold: 100000 }
    });

    for await (const message of runner) {
      console.log(`Tokens used: ${message.usage.input_tokens}`);
    }
    ```
  </Tab>

  <Tab title="C#">
    <Note>
      C# SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Go">
    <Note>
      Go SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Java">
    <Note>
      Java SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="PHP">
    <Note>
      PHP SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Ruby">
    ```ruby Ruby
    client = Anthropic::Client.new

    runner = client.beta.messages.tool_runner(
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [ReadFile.new],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compaction_control: { enabled: true, context_token_threshold: 100000 }
    )

    runner.each_message do |message|
      puts "Tokens used: #{message.usage.input_tokens}"
    end
    ```
  </Tab>
</Tabs>

#### コンパクション中に何が起こるか

会話が大きくなるにつれて、メッセージ履歴が蓄積されます。

**コンパクション前（100kトークンに近づいている状態）：**

```json
[
  { "role": "user", "content": "Analyze all files and write a report..." },
  { "role": "assistant", "content": "I'll help. Let me start by reading..." },
  {
    "role": "user",
    "content": [{ "type": "tool_result", "tool_use_id": "...", "content": "..." }]
  },
  { "role": "assistant", "content": "Based on file1.txt, I see..." },
  {
    "role": "user",
    "content": [{ "type": "tool_result", "tool_use_id": "...", "content": "..." }]
  },
  { "role": "assistant", "content": "After analyzing file2.txt..." }
  // ... 50 more exchanges like this ...
]
```

トークンがしきい値を超えると、SDKは要約リクエストを挿入し、Claudeが要約を生成します。その後、履歴全体が置き換えられます。

**コンパクション後（約2〜3kトークンに戻った状態）：**

```json
[
  {
    "role": "assistant",
    "content": "# Task Overview\nThe user requested analysis of directory files to produce a summary report...\n\n# Current State\nAnalyzed 52 files across 3 subdirectories. Key findings documented in report.md...\n\n# Important Discoveries\n- Configuration files use YAML format\n- Found 3 deprecated dependencies\n- Test coverage at 67%\n\n# Next Steps\n1. Analyze remaining files in /src/legacy\n2. Complete final report sections...\n\n# Context to Preserve\nUser prefers markdown format with executive summary first..."
  }
]
```

Claudeは、この要約を元の会話履歴であるかのようにして作業を続けます。

### 設定オプション

| パラメータ                     | 型       | 必須  | デフォルト                                                                                                            | 説明                   |
| ------------------------- | ------- | --- | ---------------------------------------------------------------------------------------------------------------- | -------------------- |
| `enabled`                 | boolean | はい  | -                                                                                                                | 自動コンパクションを有効にするかどうか  |
| `context_token_threshold` | number  | いいえ | 100,000                                                                                                          | コンパクションがトリガーされるトークン数 |
| `model`                   | string  | いいえ | メインモデルと同じ                                                                                                        | 要約の生成に使用するモデル        |
| `summary_prompt`          | string  | いいえ | [デフォルトの要約プロンプト](https://platform.claude.com/docs/ja/build-with-claude/context-editing#default-summary-prompt)を参照 | 要約生成用のカスタムプロンプト      |

#### トークンしきい値の選択

しきい値は、コンパクションが発生するタイミングを決定します。しきい値が低いほど、より小さなコンテキストウィンドウでより頻繁にコンパクションが行われます。しきい値が高いほど、より多くのコンテキストを保持できますが、制限に達するリスクがあります。

<Tabs>
  <Tab title="cURL">
    <Note>
      コンパクションはSDKの`tool_runner`ヘルパー内でクライアントサイドで実行されるため、直接対応するHTTPの手段はありません。代わりに、Anthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="CLI">
    <Note>
      CLIには`tool_runner`ヘルパーが含まれていません。代わりに、SDK側の統合なしでAnthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Python">
    <Note>
      v1.0以降、Python SDKのツールランナーはクライアントサイドの`compaction_control`をサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="TypeScript">
    ```typescript TypeScript
    const client = new Anthropic();

    const runner = client.beta.messages.toolRunner({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [readFile],
      messages: [{ role: "user", content: "What's in config.json?" }],
      // 値を小さくするとコンパクションの頻度が上がります。タスクにより多くのコンテキストが必要な場合は150000に引き上げてください
      compactionControl: { enabled: true, contextTokenThreshold: 50000 }
    });

    for await (const message of runner) {
      console.log(`Tokens used: ${message.usage.input_tokens}`);
    }
    ```
  </Tab>

  <Tab title="C#">
    <Note>
      C# SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Go">
    <Note>
      Go SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Java">
    <Note>
      Java SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="PHP">
    <Note>
      PHP SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Ruby">
    ```ruby Ruby
    client = Anthropic::Client.new

    runner = client.beta.messages.tool_runner(
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [ReadFile.new],
      messages: [{ role: "user", content: "What's in config.json?" }],
      # 値を小さくするほど頻繁にコンパクションされます。タスクでより多くのコンテキストが必要な場合は150000に上げてください
      compaction_control: { enabled: true, context_token_threshold: 50000 }
    )

    runner.each_message do |message|
      puts "Tokens used: #{message.usage.input_tokens}"
    end
    ```
  </Tab>
</Tabs>

#### 要約に別のモデルを使用する

要約の生成には、より高速または安価なモデルを使用できます。

<Tabs>
  <Tab title="cURL">
    <Note>
      コンパクションはSDKの`tool_runner`ヘルパー内でクライアントサイドで実行されるため、直接対応するHTTPの手段はありません。代わりに、Anthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="CLI">
    <Note>
      CLIには`tool_runner`ヘルパーが含まれていません。代わりに、SDK側の統合なしでAnthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Python">
    <Note>
      v1.0以降、Python SDKのツールランナーはクライアントサイドの`compaction_control`をサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="TypeScript">
    ```typescript TypeScript
    const client = new Anthropic();

    const runner = client.beta.messages.toolRunner({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [readFile],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compactionControl: {
        enabled: true,
        contextTokenThreshold: 100000,
        model: "claude-haiku-4-5"
      }
    });

    for await (const message of runner) {
      console.log(`Tokens used: ${message.usage.input_tokens}`);
    }
    ```
  </Tab>

  <Tab title="C#">
    <Note>
      C# SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Go">
    <Note>
      Go SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Java">
    <Note>
      Java SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="PHP">
    <Note>
      PHP SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Ruby">
    ```ruby Ruby
    client = Anthropic::Client.new

    runner = client.beta.messages.tool_runner(
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [ReadFile.new],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compaction_control: {
        enabled: true,
        context_token_threshold: 100000,
        model: "claude-haiku-4-5"
      }
    )

    runner.each_message do |message|
      puts "Tokens used: #{message.usage.input_tokens}"
    end
    ```
  </Tab>
</Tabs>

#### カスタム要約プロンプト

ドメイン固有のニーズに合わせて、カスタムプロンプトを指定できます。プロンプトでは、要約を`<summary></summary>`タグで囲むようClaudeに指示する必要があります。

<Tabs>
  <Tab title="cURL">
    <Note>
      コンパクションはSDKの`tool_runner`ヘルパー内でクライアントサイドで実行されるため、直接対応するHTTPの手段はありません。代わりに、Anthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="CLI">
    <Note>
      CLIには`tool_runner`ヘルパーが含まれていません。代わりに、SDK側の統合なしでAnthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Python">
    <Note>
      v1.0以降、Python SDKのツールランナーはクライアントサイドの`compaction_control`をサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="TypeScript">
    ```typescript TypeScript
    const client = new Anthropic();

    const runner = client.beta.messages.toolRunner({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [readFile],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compactionControl: {
        enabled: true,
        contextTokenThreshold: 100000,
        summaryPrompt: `Summarize the research conducted so far, including:
    - Sources consulted and key findings
    - Questions answered and remaining unknowns
    - Recommended next steps

    Wrap your summary in <summary></summary> tags.`
      }
    });

    for await (const message of runner) {
      console.log(`Tokens used: ${message.usage.input_tokens}`);
    }
    ```
  </Tab>

  <Tab title="C#">
    <Note>
      C# SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Go">
    <Note>
      Go SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Java">
    <Note>
      Java SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="PHP">
    <Note>
      PHP SDKにはツールランナーが含まれていますが、クライアントサイドの`compaction_control`はサポートしていません。代わりに[トークンしきい値でのサーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction-threshold)を使用してください。これは、リクエストの`context_management`パラメータで`compact_20260112`編集を渡すことでツールランナーと連携します。
    </Note>
  </Tab>

  <Tab title="Ruby">
    ```ruby Ruby
    client = Anthropic::Client.new

    runner = client.beta.messages.tool_runner(
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [ReadFile.new],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compaction_control: {
        enabled: true,
        context_token_threshold: 100000,
        summary_prompt: <<~PROMPT
          Summarize the research conducted so far, including:
          - Sources consulted and key findings
          - Questions answered and remaining unknowns
          - Recommended next steps

          Wrap your summary in <summary></summary> tags.
        PROMPT
      }
    )

    runner.each_message do |message|
      puts "Tokens used: #{message.usage.input_tokens}"
    end
    ```
  </Tab>
</Tabs>

### デフォルトの要約プロンプト

組み込みの要約プロンプトは、次の内容を含む構造化された継続用の要約を作成するようClaudeに指示します。

1. **タスクの概要：** ユーザーの中心的なリクエスト、成功基準、および制約。
2. **現在の状態：** 完了した内容、変更されたファイル、および生成された成果物。
3. **重要な発見：** 技術的な制約、行われた決定、解決したエラー、および失敗したアプローチ。
4. **次のステップ：** 必要な具体的なアクション、ブロッカー、および優先順位。
5. **保持すべきコンテキスト：** ユーザーの好み、ドメイン固有の詳細、および行った約束。

この構造により、Claudeは重要なコンテキストを失ったり、ミスを繰り返したりすることなく、効率的に作業を再開できます。

<Accordion title="デフォルトのプロンプト全文を表示">
  ```text wrap
  You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:

  1. Task Overview
  The user's core request and success criteria
  Any clarifications or constraints they specified

  2. Current State
  What has been completed so far
  Files created, modified, or analyzed (with paths if relevant)
  Key outputs or artifacts produced

  3. Important Discoveries
  Technical constraints or requirements uncovered
  Decisions made and their rationale
  Errors encountered and how they were resolved
  What approaches were tried that didn't work (and why)

  4. Next Steps
  Specific actions needed to complete the task
  Any blockers or open questions to resolve
  Priority order if multiple steps remain

  5. Context to Preserve
  User preferences or style requirements
  Domain-specific details that aren't obvious
  Any promises made to the user

  Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.

  Wrap your summary in <summary></summary> tags.
  ```
</Accordion>

### 制限事項

#### サーバーサイドツール

<Warning>
  [ウェブ検索](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-search-tool)や[ウェブフェッチ](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-fetch-tool)などのサーバーサイドツールを使用する場合、コンパクションには特別な配慮が必要です。
</Warning>

サーバーサイドツールを使用する場合、SDKがトークン使用量を誤って計算し、コンパクションが誤ったタイミングでトリガーされる可能性があります。

たとえば、ウェブ検索操作の後、APIレスポンスに次のように表示される場合があります。

```json Output
{
  "usage": {
    "input_tokens": 63000,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 270000,
    "output_tokens": 1400
  }
}
```

SDKは合計使用量を63,000 + 0 + 270,000 + 1,400 = 334,400トークンと計算します。しかし、`cache_read_input_tokens`の値には、実際の会話コンテキストではなく、サーバーサイドツールが行った複数の内部API呼び出しによって蓄積された読み取りが含まれています。実際のコンテキスト長は63,000の`input_tokens`のみである可能性がありますが、SDKは334kと計算し、コンパクションを早期にトリガーしてしまいます。

**回避策：**

* 正確なコンテキスト長を取得するには、[トークンカウント](https://platform.claude.com/docs/ja/build-with-claude/token-counting)エンドポイントを使用してください。
* サーバーサイドツールを多用する場合は、コンパクションを避けてください。

#### ツール使用のエッジケース

ツール使用のレスポンスが保留中のときにSDKがコンパクションをトリガーすると、要約を生成する前にメッセージ履歴からツール使用ブロックが削除されます。まだ必要であれば、Claudeは要約から再開した後にツール呼び出しを再発行します。

### コンパクションの監視

コンパクションがいつトリガーされるかを把握することで、しきい値を調整し、期待どおりの動作を確認できます。

<Tabs>
  <Tab title="cURL">
    <Note>
      コンパクションはSDKの`tool_runner`ヘルパー内でクライアントサイドで実行されるため、直接対応するHTTPの仕組みはありません。代わりに、Anthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="CLI">
    <Note>
      CLIには`tool_runner`ヘルパーが含まれていません。代わりに、SDK側の統合なしにAnthropicのサーバー上でコンパクションを処理する[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Python">
    <Note>
      v1.0以降、Python SDKのツールランナーは`compaction_control`をサポートしていません。代わりに[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="TypeScript">
    TypeScript SDKの`toolRunner`はコンパクションをサポートしていますが、イベントをログに記録しません。ターン間で`runner.params.messages.length`が減少するのを監視することで、コンパクションを検出します：

    ```typescript TypeScript
    let prevMsgCount = 0;
    for await (const message of runner) {
      const currMsgCount = runner.params.messages.length;
      if (currMsgCount < prevMsgCount) {
        console.log(`Compaction occurred: ${prevMsgCount} -> ${currMsgCount} messages`);
        console.log(`Input tokens after compaction: ${message.usage.input_tokens}`);
      }
      prevMsgCount = currMsgCount;
    }
    ```
  </Tab>

  <Tab title="C#">
    <Note>
      C# SDKのツールランナーは`compaction_control`をサポートしていません。代わりに[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Go">
    <Note>
      Go SDKのツールランナーは`compaction_control`をサポートしていません。代わりに[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Java">
    <Note>
      Java SDKのツールランナーは`compaction_control`をサポートしていません。代わりに[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="PHP">
    <Note>
      PHP SDKのツールランナーは`compaction_control`をサポートしていません。代わりに[サーバーサイドのコンパクション](https://platform.claude.com/docs/ja/build-with-claude/compaction)を使用してください。
    </Note>
  </Tab>

  <Tab title="Ruby">
    Ruby SDKは、コンパクションが発生したときに呼び出される`on_compact:`コールバックをサポートしています。これを`compaction_control`の設定に追加してください：

    ```ruby Ruby
    client = Anthropic::Client.new

    runner = client.beta.messages.tool_runner(
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: [ReadFile.new],
      messages: [{ role: "user", content: "What's in config.json?" }],
      compaction_control: {
        enabled: true,
        context_token_threshold: 100000,
        on_compact: ->(tokens_before, tokens_after) do
          puts "Compaction occurred: #{tokens_before} -> #{tokens_after} tokens"
        end
      }
    )

    runner.each_message do |message|
      puts "Tokens: #{message.usage.input_tokens}"
    end
    ```
  </Tab>
</Tabs>

### コンパクションを使用すべき場合

**適したユースケース：**

* 多数のファイルやデータソースを処理する長時間実行のエージェントタスク
* 大量の情報を蓄積するリサーチワークフロー
* 明確で測定可能な進捗がある複数ステップのタスク
* 会話の外部に残る成果物（ファイル、レポート）を生成するタスク

**あまり適さないユースケース：**

* 会話の初期の詳細を正確に思い出す必要があるタスク
* サーバーサイドツールを多用するワークフロー
* 多数の変数にわたって正確な状態を維持する必要があるタスク

## 次のステップ

<CardGroup cols={2}>
  <Card title="コンパクション" icon="arrows-clockwise" href="https://platform.claude.com/docs/ja/build-with-claude/compaction">
    ほとんどのユースケースで推奨される戦略であるサーバーサイドのコンパクションを使用して、長い会話を管理します。
  </Card>

  <Card title="プロンプトキャッシング" icon="database" href="https://platform.claude.com/docs/ja/build-with-claude/prompt-caching">
    プロンプトのプレフィックスをキャッシュすることでコストとレイテンシを削減し、コンテキスト編集がキャッシュとどのように相互作用するかを学びます。
  </Card>
</CardGroup>

## 利用可能状況

コンテキスト編集はすべてのモデルでベータ版であり、ゼロデータ保持の対象です。

### APIサポート

#### [Messages API](https://platform.claude.com/docs/ja/build-with-claude/working-with-messages)

* 利用可能状況：利用可能

| ステータス | クラウドプラットフォーム                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ベータ   | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws), [Amazon Bedrock](https://platform.claude.com/docs/ja/build-with-claude/claude-in-amazon-bedrock), [Amazon Bedrock (InvokeModel)](https://platform.claude.com/docs/ja/build-with-claude/claude-on-amazon-bedrock-legacy), [Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/ja/build-with-claude/claude-models-on-google-cloud/google-managed), [Microsoft Foundry](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry) |

### 必須のベータヘッダー

[ベータヘッダーの概要](https://platform.claude.com/docs/ja/api/beta-headers)

ベータヘッダーを使用すると、実験的な機能や新しいモデル機能が標準APIに組み込まれる前にアクセスできます。

* `context-management-2025-06-27`

### データの取り扱い

[データの取り扱いの概要](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention#feature-eligibility)

| 項目    | ゼロデータ保持                                                                                                                             | HIPAA |
| ----- | ----------------------------------------------------------------------------------------------------------------------------------- | ----- |
| ステータス | 対象（[対象モデル](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)を除く） | 対象外   |
| 詳細    | コンテキスト編集（ツール使用の削除と思考の削除）はリアルタイムで適用されます。                                                                                             | —     |

対象エンドポイント：

* `/v1/messages` `context_management`を指定した場合
