SPB Git

Repository Public

compaction.md 133.0 KB 3,846 lines markdown

1---2title: Compaction3url: https://platform.claude.com/docs/en/build-with-claude/compaction4description: Server-side context compaction for managing long conversations that approach context window limits.5---67## Compatibility8- Status: Beta9- [Beta header](https://platform.claude.com/docs/en/api/beta-headers): `compact-2026-01-12`10- [ZDR](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention): eligible (excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements))11- Supported models: `claude-fable-5-1`, `claude-mythos-5-1`, `claude-fable-5`, `claude-mythos-5`, `claude-mythos-preview`, `claude-opus-5`, `claude-opus-4-8`, `claude-opus-4-7`, `claude-opus-4-6`, `claude-sonnet-5`, `claude-sonnet-4-6`12- Platforms: Claude API (beta), Claude Platform on AWS (beta), Amazon Bedrock (beta), Google Cloud (beta), Microsoft Foundry (beta)1314<Tip>15  Server-side compaction is the recommended strategy for managing context in long-running conversations and agentic workflows. It handles context management automatically, without client-side summarization code.16</Tip>1718Compaction extends the effective context length for long-running conversations and tasks by automatically summarizing older context when approaching the context window limit. It also keeps the active context small: as a conversation grows, response quality degrades, so compaction replaces older content with a concise summary.1920<Tip>21  For a deeper look at why long contexts degrade and how compaction helps, see [Effective context engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents).22</Tip>2324This is ideal for:2526* Chat-based, multi-turn conversations where you want users to use one chat for a long period of time27* Task-oriented prompts that require a lot of follow-up work (often tool use) that might exceed the context window2829## How compaction works3031When compaction is enabled, Claude automatically summarizes your conversation when it reaches the configured token threshold. The API:32331. Detects when input tokens reach your specified trigger threshold.342. Generates a summary of the current conversation.353. Creates a `compaction` block containing the summary.364. Continues the response with the compacted context.3738On subsequent requests, append the response to your messages. The API automatically drops all content blocks prior to the `compaction` block, continuing the conversation from the summary.3940![Compaction flow: when input tokens reach the trigger, Claude writes a summary into a compaction block and continues](https://platform.claude.com/docs/images/compaction-flow.svg)4142The previous steps describe threshold compaction, which most of this page covers. With the `compact-2026-09-04` beta header, you can instead request a summary on demand. That request is separate from your conversation turns and returns only the summary, so it can run in the background. When the block arrives, you swap it in for the messages it summarizes. See [Compact on demand with the `compaction` parameter](https://platform.claude.com/docs/en/build-with-claude/compaction#compact-on-demand-with-the-compaction-parameter).4344## Basic usage4546Enable compaction by adding the `compact_20260112` strategy to `context_management.edits` in your Messages API request.4748<CodeGroup>49  ```bash cURL50  curl https://api.anthropic.com/v1/messages \51    -H "x-api-key: $ANTHROPIC_API_KEY" \52    -H "anthropic-version: 2023-06-01" \53    -H "anthropic-beta: compact-2026-01-12" \54    -H "content-type: application/json" \55    -d '{56      "model": "claude-opus-5",57      "max_tokens": 4096,58      "messages": [59        {60          "role": "user",61          "content": "Help me build a website"62        }63      ],64      "context_management": {65        "edits": [66          {67            "type": "compact_20260112"68          }69        ]70      }71    }'72  ```7374  ```bash CLI75  ant beta:messages create --beta compact-2026-01-12 <<'YAML'76  model: claude-opus-577  max_tokens: 409678  messages:79    - role: user80      content: Help me build a website81  context_management:82    edits:83      - type: compact_2026011284  YAML85  ```8687  ```python Python88  client = anthropic.Anthropic()8990  messages = [{"role": "user", "content": "Help me build a website"}]9192  response = client.beta.messages.create(93      betas=["compact-2026-01-12"],94      model="claude-opus-5",95      max_tokens=4096,96      messages=messages,97      context_management={"edits": [{"type": "compact_20260112"}]},98  )99100  # Append the response (including any compaction block) to continue the conversation101  messages.append({"role": "assistant", "content": response.content})102  ```103104  ```typescript TypeScript105  const client = new Anthropic();106107  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [108    { role: "user", content: "Help me build a website" }109  ];110111  const response = await client.beta.messages.create({112    betas: ["compact-2026-01-12"],113    model: "claude-opus-5",114    max_tokens: 4096,115    messages,116    context_management: {117      edits: [118        {119          type: "compact_20260112"120        }121      ]122    }123  });124125  // Append the response (including any compaction block) to continue the conversation126  messages.push({127    role: "assistant",128    content: response.content129  });130  ```131132  ```csharp C#133  AnthropicClient client = new();134135  var messages = new List<BetaMessageParam>136  {137      new() { Role = Role.User, Content = "Help me build a website" }138  };139140  var parameters = new MessageCreateParams141  {142      Betas = ["compact-2026-01-12"],143      Model = "claude-opus-5",144      MaxTokens = 4096,145      Messages = messages,146      ContextManagement = new BetaContextManagementConfig147      {148          Edits = [new BetaCompact20260112Edit()]149      }150  };151152  var response = await client.Beta.Messages.Create(parameters);153154  // Append the response (including any compaction block) to continue the conversation155  messages.Add(new BetaMessageParam156  {157      Role = Role.Assistant,158      Content = response.Content.Select(block => new BetaContentBlockParam(block.Json)).ToList()159  });160161  Console.WriteLine(response);162  ```163164  ```go Go165  client := anthropic.NewClient()166167  messages := []anthropic.BetaMessageParam{168  	anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Help me build a website")),169  }170171  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{172  	Model:     anthropic.ModelClaudeOpus5,173  	MaxTokens: 4096,174  	Messages:  messages,175  	ContextManagement: anthropic.BetaContextManagementConfigParam{176  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{177  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},178  		},179  	},180  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},181  })182  if err != nil {183  	log.Fatal(err)184  }185186  // Append the response (including any compaction block) to continue the conversation187  messages = append(messages, response.ToParam())188189  fmt.Println(response)190  ```191192  ```java Java193  import com.anthropic.models.beta.messages.BetaContextManagementConfig;194  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;195  // ...196          AnthropicClient client = AnthropicOkHttpClient.fromEnv();197198          MessageCreateParams params = MessageCreateParams.builder()199              .addBeta("compact-2026-01-12")200              .model("claude-opus-5")201              .maxTokens(4096L)202              .addUserMessage("Help me build a website")203              .contextManagement(BetaContextManagementConfig.builder()204                  .addEdit(BetaCompact20260112Edit.builder().build())205                  .build())206              .build();207208          BetaMessage response = client.beta().messages().create(params);209210          // Append the response (including any compaction block) to continue the conversation211          // by including it in the next request's messages212          System.out.println(response);213  ```214215  ```php PHP216  $client = new Client();217218  $messages = [219      ['role' => 'user', 'content' => 'Help me build a website']220  ];221222  $response = $client->beta->messages->create(223      maxTokens: 4096,224      messages: $messages,225      model: 'claude-opus-5',226      betas: ['compact-2026-01-12'],227      contextManagement: [228          'edits' => [229              ['type' => 'compact_20260112']230          ]231      ]232  );233234  // Append the response (including any compaction block) to continue the conversation235  $messages[] = ['role' => 'assistant', 'content' => $response->content];236237  echo json_encode($response, JSON_PRETTY_PRINT), PHP_EOL;238  ```239240  ```ruby Ruby241  client = Anthropic::Client.new242243  messages = [244    { role: "user", content: "Help me build a website" }245  ]246247  response = client.beta.messages.create(248    betas: ["compact-2026-01-12"],249    model: "claude-opus-5",250    max_tokens: 4096,251    messages: messages,252    context_management: {253      edits: [{ type: "compact_20260112" }]254    }255  )256257  # Append the response (including any compaction block) to continue the conversation258  messages << { role: "assistant", content: response.content }259260  puts response261  ```262</CodeGroup>263264## Parameters265266| Parameter                | Type    | Default                                     | Description                                                                                                            |267| ------------------------ | ------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |268| `type`                   | string  | Required                                    | Must be `"compact_20260112"`                                                                                           |269| `trigger`                | object  | `{"type": "input_tokens", "value": 150000}` | When to trigger compaction. `input_tokens` is the only supported trigger type. `value` must be at least 50,000 tokens. |270| `pause_after_compaction` | boolean | `false`                                     | Whether to pause after generating the compaction summary                                                               |271| `instructions`           | string  | `null`                                      | Custom summarization prompt. Completely replaces the default prompt when provided.                                     |272273### Trigger configuration274275Configure when compaction triggers using the `trigger` parameter:276277<CodeGroup>278  ```bash cURL279  curl https://api.anthropic.com/v1/messages \280    -H "x-api-key: $ANTHROPIC_API_KEY" \281    -H "anthropic-version: 2023-06-01" \282    -H "anthropic-beta: compact-2026-01-12" \283    -H "content-type: application/json" \284    -d '{285      "model": "claude-opus-5",286      "max_tokens": 4096,287      "messages": [288        {289          "role": "user",290          "content": "Hello, Claude"291        }292      ],293      "context_management": {294        "edits": [295          {296            "type": "compact_20260112",297            "trigger": {298              "type": "input_tokens",299              "value": 150000300            }301          }302        ]303      }304    }'305  ```306307  ```bash CLI308  ant beta:messages create --beta compact-2026-01-12 <<'YAML'309  model: claude-opus-5310  max_tokens: 4096311  messages:312    - role: user313      content: Hello, Claude314  context_management:315    edits:316      - type: compact_20260112317        trigger:318          type: input_tokens319          value: 150000320  YAML321  ```322323  ```python Python324  client = anthropic.Anthropic()325  messages = [{"role": "user", "content": "Hello, Claude"}]326  response = client.beta.messages.create(327      betas=["compact-2026-01-12"],328      model="claude-opus-5",329      max_tokens=4096,330      messages=messages,331      context_management={332          "edits": [333              {334                  "type": "compact_20260112",335                  "trigger": {"type": "input_tokens", "value": 150000},336              }337          ]338      },339  )340  ```341342  ```typescript TypeScript343  const client = new Anthropic();344  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [345    { role: "user", content: "Hello, Claude" }346  ];347348  const response = await client.beta.messages.create({349    betas: ["compact-2026-01-12"],350    model: "claude-opus-5",351    max_tokens: 4096,352    messages,353    context_management: {354      edits: [355        {356          type: "compact_20260112",357          trigger: {358            type: "input_tokens",359            value: 150000360          }361        }362      ]363    }364  });365  ```366367  ```csharp C#368  AnthropicClient client = new();369  List<BetaMessageParam> messages = [new() { Role = Role.User, Content = "Hello" }];370371  var parameters = new MessageCreateParams372  {373      Model = "claude-opus-5",374      MaxTokens = 4096,375      Betas = ["compact-2026-01-12"],376      Messages = messages,377      ContextManagement = new BetaContextManagementConfig378      {379          Edits = [new BetaCompact20260112Edit380          {381              Trigger = new BetaInputTokensTrigger(150000)382          }]383      }384  };385386  var message = await client.Beta.Messages.Create(parameters);387  Console.WriteLine(message);388  ```389390  ```go Go391  client := anthropic.NewClient()392  messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}393394  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{395  	Model:     anthropic.ModelClaudeOpus5,396  	MaxTokens: 4096,397  	Messages:  messages,398  	ContextManagement: anthropic.BetaContextManagementConfigParam{399  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{400  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{401  				Trigger: anthropic.BetaInputTokensTriggerParam{Value: 150000},402  			}},403  		},404  	},405  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},406  })407  if err != nil {408  	log.Fatal(err)409  }410  fmt.Println(response)411  ```412413  ```java Java414  import com.anthropic.models.beta.messages.BetaContextManagementConfig;415  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;416  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;417  // ...418          AnthropicClient client = AnthropicOkHttpClient.fromEnv();419420          MessageCreateParams params = MessageCreateParams.builder()421              .model("claude-opus-5")422              .maxTokens(4096L)423              .addBeta("compact-2026-01-12")424              .addUserMessage("Hello, Claude")425              .contextManagement(BetaContextManagementConfig.builder()426                  .addEdit(BetaCompact20260112Edit.builder()427                      .trigger(BetaInputTokensTrigger.builder()428                          .value(150000L)429                          .build())430                      .build())431                  .build())432              .build();433434          BetaMessage response = client.beta().messages().create(params);435          System.out.println(response);436  ```437438  ```php PHP439  $client = new Client();440  $messages = [['role' => 'user', 'content' => 'Hello, Claude']];441442  $message = $client->beta->messages->create(443      maxTokens: 4096,444      messages: $messages,445      model: 'claude-opus-5',446      betas: ['compact-2026-01-12'],447      contextManagement: [448          'edits' => [449              [450                  'type' => 'compact_20260112',451                  'trigger' => [452                      'type' => 'input_tokens',453                      'value' => 150000454                  ]455              ]456          ]457      ]458  );459460  echo $message;461  ```462463  ```ruby Ruby464  client = Anthropic::Client.new465  messages = [{ role: "user", content: "Hello, Claude" }]466467  response = client.beta.messages.create(468    betas: ["compact-2026-01-12"],469    model: "claude-opus-5",470    max_tokens: 4096,471    messages: messages,472    context_management: {473      edits: [474        {475          type: "compact_20260112",476          trigger: {477            type: "input_tokens",478            value: 150000479          }480        }481      ]482    }483  )484  puts response485  ```486</CodeGroup>487488### Custom summarization instructions489490The default summarization prompt varies by model. Each default instructs Claude to write a summary inside `<summary></summary>` tags with the information needed to continue the task in a future context window. For example, some models use the following prompt:491492```text wrap493You have written a partial transcript for the initial task above. Please write a summary of the transcript. The purpose of this summary is to provide continuity so you can continue to make progress towards solving the task in a future context, where the raw history above may not be accessible and will be replaced with this summary. Write down anything that would be helpful, including the state, next steps, learnings etc. You must wrap your summary in a <summary></summary> block.494```495496You can provide custom instructions through the `instructions` parameter. Custom instructions don't supplement the default prompt. They replace it completely:497498<CodeGroup>499  ```bash cURL500  curl https://api.anthropic.com/v1/messages \501    -H "x-api-key: $ANTHROPIC_API_KEY" \502    -H "anthropic-version: 2023-06-01" \503    -H "anthropic-beta: compact-2026-01-12" \504    -H "content-type: application/json" \505    -d '{506      "model": "claude-opus-5",507      "max_tokens": 4096,508      "messages": [509        {510          "role": "user",511          "content": "Hello, Claude"512        }513      ],514      "context_management": {515        "edits": [516          {517            "type": "compact_20260112",518            "instructions": "Focus on preserving code snippets, variable names, and technical decisions."519          }520        ]521      }522    }'523  ```524525  ```bash CLI526  ant beta:messages create --beta compact-2026-01-12 <<'YAML'527  model: claude-opus-5528  max_tokens: 4096529  messages:530    - role: user531      content: Hello, Claude532  context_management:533    edits:534      - type: compact_20260112535        instructions: >-536          Focus on preserving code snippets, variable names, and537          technical decisions.538  YAML539  ```540541  ```python Python542  client = anthropic.Anthropic()543  messages = [{"role": "user", "content": "Hello, Claude"}]544  response = client.beta.messages.create(545      betas=["compact-2026-01-12"],546      model="claude-opus-5",547      max_tokens=4096,548      messages=messages,549      context_management={550          "edits": [551              {552                  "type": "compact_20260112",553                  "instructions": "Focus on preserving code snippets, variable names, and technical decisions.",554              }555          ]556      },557  )558  ```559560  ```typescript TypeScript561  const client = new Anthropic();562  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [563    { role: "user", content: "Hello, Claude" }564  ];565566  const response = await client.beta.messages.create({567    betas: ["compact-2026-01-12"],568    model: "claude-opus-5",569    max_tokens: 4096,570    messages,571    context_management: {572      edits: [573        {574          type: "compact_20260112",575          instructions:576            "Focus on preserving code snippets, variable names, and technical decisions."577        }578      ]579    }580  });581  ```582583  ```csharp C#584  AnthropicClient client = new();585586  var parameters = new MessageCreateParams587  {588      Betas = ["compact-2026-01-12"],589      Model = "claude-opus-5",590      MaxTokens = 4096,591      Messages =592      [593          new BetaMessageParam { Role = Role.User, Content = "Help me build a Python web scraper" },594          new BetaMessageParam { Role = Role.Assistant, Content = "I'll help you build a web scraper..." },595          new BetaMessageParam { Role = Role.User, Content = "Add support for JavaScript-rendered pages" }596      ],597      ContextManagement = new BetaContextManagementConfig598      {599          Edits = [new BetaCompact20260112Edit600          {601              Instructions = "Focus on preserving code snippets, variable names, and technical decisions."602          }]603      }604  };605606  var message = await client.Beta.Messages.Create(parameters);607  Console.WriteLine(message);608  ```609610  ```go Go611  client := anthropic.NewClient()612613  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{614  	Model:     anthropic.ModelClaudeOpus5,615  	MaxTokens: 4096,616  	Messages: []anthropic.BetaMessageParam{617  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Help me build a Python web scraper")),618  		{Role: anthropic.BetaMessageParamRoleAssistant, Content: []anthropic.BetaContentBlockParamUnion{anthropic.NewBetaTextBlock("I'll help you build a web scraper...")}},619  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Add support for JavaScript-rendered pages")),620  	},621  	ContextManagement: anthropic.BetaContextManagementConfigParam{622  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{623  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{624  				Instructions: anthropic.String("Focus on preserving code snippets, variable names, and technical decisions."),625  			}},626  		},627  	},628  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},629  })630  if err != nil {631  	log.Fatal(err)632  }633  fmt.Println(response)634  ```635636  ```java Java637  import com.anthropic.models.beta.messages.BetaContextManagementConfig;638  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;639  // ...640          AnthropicClient client = AnthropicOkHttpClient.fromEnv();641642          MessageCreateParams params = MessageCreateParams.builder()643              .addBeta("compact-2026-01-12")644              .model("claude-opus-5")645              .maxTokens(4096L)646              .addUserMessage("Help me build a Python web scraper")647              .addAssistantMessage("I'll help you build a web scraper...")648              .addUserMessage("Add support for JavaScript-rendered pages")649              .contextManagement(BetaContextManagementConfig.builder()650                  .addEdit(BetaCompact20260112Edit.builder()651                      .instructions("Focus on preserving code snippets, variable names, and technical decisions.")652                      .build())653                  .build())654              .build();655656          BetaMessage response = client.beta().messages().create(params);657          System.out.println(response);658  ```659660  ```php PHP661  $client = new Client();662663  $response = $client->beta->messages->create(664      maxTokens: 4096,665      messages: [666          ['role' => 'user', 'content' => 'Help me build a Python web scraper'],667          ['role' => 'assistant', 'content' => "I'll help you build a web scraper..."],668          ['role' => 'user', 'content' => 'Add support for JavaScript-rendered pages']669      ],670      model: 'claude-opus-5',671      betas: ['compact-2026-01-12'],672      contextManagement: [673          'edits' => [674              [675                  'type' => 'compact_20260112',676                  'instructions' => 'Focus on preserving code snippets, variable names, and technical decisions.'677              ]678          ]679      ]680  );681682  echo json_encode($response, JSON_PRETTY_PRINT), PHP_EOL;683  ```684685  ```ruby Ruby686  client = Anthropic::Client.new687688  response = client.beta.messages.create(689    betas: ["compact-2026-01-12"],690    model: "claude-opus-5",691    max_tokens: 4096,692    messages: [693      { role: "user", content: "Help me build a Python web scraper" },694      { role: "assistant", content: "I'll help you build a web scraper..." },695      { role: "user", content: "Add support for JavaScript-rendered pages" }696    ],697    context_management: {698      edits: [699        {700          type: "compact_20260112",701          instructions:702            "Focus on preserving code snippets, variable names, and technical decisions."703        }704      ]705    }706  )707708  puts response709  ```710</CodeGroup>711712On Claude Fable 5.1 and Claude Mythos 5.1, a request with custom `instructions` summarizes from the visible conversation only: earlier thinking blocks are not part of the summarizer's input.713714### Pausing after compaction715716Use `pause_after_compaction` to pause the API after generating the compaction summary. This allows you to add additional content blocks (such as preserving recent messages or specific instruction-oriented messages) before the API continues with the response.717718When enabled, the API returns a message with the `compaction` stop reason after generating the compaction block:719720<CodeGroup>721  ```bash cURL722  # pause_after_compaction stops the response right after the compaction723  # summary so you can adjust the messages before continuing. The continue724  # step doesn't translate well to a one-off shell command; see the SDK tabs725  # for the full pause-and-continue flow. Single paused request:726  curl https://api.anthropic.com/v1/messages \727    -H "x-api-key: $ANTHROPIC_API_KEY" \728    -H "anthropic-version: 2023-06-01" \729    -H "anthropic-beta: compact-2026-01-12" \730    -H "content-type: application/json" \731    -d '{732      "model": "claude-opus-5",733      "max_tokens": 4096,734      "messages": [735        {736          "role": "user",737          "content": "Hello, Claude"738        }739      ],740      "context_management": {741        "edits": [742          {743            "type": "compact_20260112",744            "pause_after_compaction": true745          }746        ]747      }748    }'749  ```750751  ```bash CLI752  # pause_after_compaction stops the response right after the compaction753  # summary so you can adjust the messages before continuing. The continue754  # step doesn't translate well to a one-off CLI command; see the SDK tabs755  # for the full pause-and-continue flow. Single paused request:756  ant beta:messages create --beta compact-2026-01-12 --format jsonl <<'YAML'757  model: claude-opus-5758  max_tokens: 4096759  messages:760    - role: user761      content: Hello, Claude762  context_management:763    edits:764      - type: compact_20260112765        pause_after_compaction: true766  YAML767  ```768769  ```python Python770  client = anthropic.Anthropic()771  messages = [{"role": "user", "content": "Hello, Claude"}]772  response = client.beta.messages.create(773      betas=["compact-2026-01-12"],774      model="claude-opus-5",775      max_tokens=4096,776      messages=messages,777      context_management={778          "edits": [{"type": "compact_20260112", "pause_after_compaction": True}]779      },780  )781782  # Check if compaction triggered a pause783  if response.stop_reason == "compaction":784      # Response contains only the compaction block785      messages.append({"role": "assistant", "content": response.content})786787      # Continue the request788      response = client.beta.messages.create(789          betas=["compact-2026-01-12"],790          model="claude-opus-5",791          max_tokens=4096,792          messages=messages,793          context_management={"edits": [{"type": "compact_20260112"}]},794      )795  ```796797  ```typescript TypeScript798  const client = new Anthropic();799  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [800    { role: "user", content: "Hello, Claude" }801  ];802803  let response = await client.beta.messages.create({804    betas: ["compact-2026-01-12"],805    model: "claude-opus-5",806    max_tokens: 4096,807    messages,808    context_management: {809      edits: [810        {811          type: "compact_20260112",812          pause_after_compaction: true813        }814      ]815    }816  });817818  // Check if compaction triggered a pause819  if (response.stop_reason === "compaction") {820    // Response contains only the compaction block821    messages.push({822      role: "assistant",823      content: response.content824    });825826    // Continue the request827    response = await client.beta.messages.create({828      betas: ["compact-2026-01-12"],829      model: "claude-opus-5",830      max_tokens: 4096,831      messages,832      context_management: {833        edits: [{ type: "compact_20260112" }]834      }835    });836  }837  ```838839  ```csharp C#840  var client = new AnthropicClient();841  var messages = new List<BetaMessageParam>842  {843      new() { Role = Role.User, Content = "Hello, Claude" }844  };845846  var parameters = new MessageCreateParams847  {848      Model = "claude-opus-5",849      MaxTokens = 4096,850      Betas = ["compact-2026-01-12"],851      Messages = messages,852      ContextManagement = new BetaContextManagementConfig853      {854          Edits = [new BetaCompact20260112Edit855          {856              PauseAfterCompaction = true857          }]858      }859  };860861  var response = await client.Beta.Messages.Create(parameters);862863  if (response.StopReason == BetaStopReason.Compaction)864  {865      messages.Add(new BetaMessageParam866      {867          Role = Role.Assistant,868          Content = response.Content.Select(block => new BetaContentBlockParam(block.Json)).ToList()869      });870871      parameters = new()872      {873          Model = "claude-opus-5",874          MaxTokens = 4096,875          Betas = ["compact-2026-01-12"],876          Messages = messages,877          ContextManagement = new BetaContextManagementConfig878          {879              Edits = [new BetaCompact20260112Edit()]880          }881      };882883      response = await client.Beta.Messages.Create(parameters);884  }885886  Console.WriteLine(response);887  ```888889  ```go Go890  client := anthropic.NewClient()891  messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}892893  compactEdit := anthropic.BetaContextManagementConfigParam{894  	Edits: []anthropic.BetaContextManagementConfigEditUnionParam{895  		{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{896  			PauseAfterCompaction: anthropic.Bool(true),897  		}},898  	},899  }900901  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{902  	Model:             anthropic.ModelClaudeOpus5,903  	MaxTokens:         4096,904  	Messages:          messages,905  	ContextManagement: compactEdit,906  	Betas:             []anthropic.AnthropicBeta{"compact-2026-01-12"},907  })908  if err != nil {909  	log.Fatal(err)910  }911912  if response.StopReason == "compaction" {913  	messages = append(messages, response.ToParam())914915  	response, err = client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{916  		Model:     anthropic.ModelClaudeOpus5,917  		MaxTokens: 4096,918  		Messages:  messages,919  		ContextManagement: anthropic.BetaContextManagementConfigParam{920  			Edits: []anthropic.BetaContextManagementConfigEditUnionParam{921  				{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},922  			},923  		},924  		Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},925  	})926  	if err != nil {927  		log.Fatal(err)928  	}929  }930931  fmt.Println(response)932  ```933934  ```java Java935  import com.anthropic.models.beta.messages.BetaContextManagementConfig;936  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;937  import com.anthropic.models.beta.messages.BetaStopReason;938  // ...939          AnthropicClient client = AnthropicOkHttpClient.fromEnv();940941          MessageCreateParams params = MessageCreateParams.builder()942              .model("claude-opus-5")943              .maxTokens(4096L)944              .addBeta("compact-2026-01-12")945              .addUserMessage("Help me build a website")946              .contextManagement(BetaContextManagementConfig.builder()947                  .addEdit(BetaCompact20260112Edit.builder()948                      .pauseAfterCompaction(true)949                      .build())950                  .build())951              .build();952953          BetaMessage response = client.beta().messages().create(params);954955          // Check if compaction triggered a pause956          if (response.stopReason().isPresent()957                  && response.stopReason().get().equals(BetaStopReason.COMPACTION)) {958              // Append the compaction block and continue the request959              // by building a new request with the compacted context960              MessageCreateParams continueParams = MessageCreateParams.builder()961                  .model("claude-opus-5")962                  .maxTokens(4096L)963                  .addBeta("compact-2026-01-12")964                  .addUserMessage("Help me build a website")965                  .addMessage(response)966                  .contextManagement(BetaContextManagementConfig.builder()967                      .addEdit(BetaCompact20260112Edit.builder().build())968                      .build())969                  .build();970971              response = client.beta().messages().create(continueParams);972          }973974          System.out.println(response);975  ```976977  ```php PHP978  $client = new Client();979  $messages = [['role' => 'user', 'content' => 'Hello, Claude']];980981  $response = $client->beta->messages->create(982      maxTokens: 4096,983      messages: $messages,984      model: 'claude-opus-5',985      betas: ['compact-2026-01-12'],986      contextManagement: [987          'edits' => [988              [989                  'type' => 'compact_20260112',990                  'pause_after_compaction' => true991              ]992          ]993      ]994  );995996  if ($response->stopReason === 'compaction') {997      $messages[] = [998          'role' => 'assistant',999          'content' => $response->content1000      ];10011002      $response = $client->beta->messages->create(1003          maxTokens: 4096,1004          messages: $messages,1005          model: 'claude-opus-5',1006          betas: ['compact-2026-01-12'],1007          contextManagement: [1008              'edits' => [1009                  ['type' => 'compact_20260112']1010              ]1011          ]1012      );1013  }10141015  echo $response;1016  ```10171018  ```ruby Ruby1019  client = Anthropic::Client.new1020  messages = [{ role: "user", content: "Hello, Claude" }]10211022  response = client.beta.messages.create(1023    betas: ["compact-2026-01-12"],1024    model: "claude-opus-5",1025    max_tokens: 4096,1026    messages: messages,1027    context_management: {1028      edits: [1029        {1030          type: "compact_20260112",1031          pause_after_compaction: true1032        }1033      ]1034    }1035  )10361037  if response.stop_reason == :compaction1038    messages << { role: "assistant", content: response.content }10391040    response = client.beta.messages.create(1041      betas: ["compact-2026-01-12"],1042      model: "claude-opus-5",1043      max_tokens: 4096,1044      messages: messages,1045      context_management: {1046        edits: [{ type: "compact_20260112" }]1047      }1048    )1049  end10501051  puts response1052  ```1053</CodeGroup>10541055#### Enforcing a total token budget10561057When a model works on long tasks with many tool-use iterations, total token consumption can grow significantly. You can combine `pause_after_compaction` with a compaction counter to estimate cumulative usage and gracefully wrap up the task once a budget is reached.10581059This example appears in the SDK languages only: its value is the budget-tracking logic around the request. The raw request combines the `trigger` from [Trigger configuration](https://platform.claude.com/docs/en/build-with-claude/compaction#trigger-configuration) with `pause_after_compaction` from [Pausing after compaction](https://platform.claude.com/docs/en/build-with-claude/compaction#pausing-after-compaction).10601061<CodeGroup exclude="shell">1062  ```python Python1063  client = anthropic.Anthropic()1064  messages = [{"role": "user", "content": "Hello, Claude"}]1065  TRIGGER_THRESHOLD = 100_0001066  TOTAL_TOKEN_BUDGET = 3_000_0001067  n_compactions = 010681069  response = client.beta.messages.create(1070      betas=["compact-2026-01-12"],1071      model="claude-opus-5",1072      max_tokens=4096,1073      messages=messages,1074      context_management={1075          "edits": [1076              {1077                  "type": "compact_20260112",1078                  "trigger": {"type": "input_tokens", "value": TRIGGER_THRESHOLD},1079                  "pause_after_compaction": True,1080              }1081          ]1082      },1083  )10841085  if response.stop_reason == "compaction":1086      n_compactions += 11087      messages.append({"role": "assistant", "content": response.content})10881089      # Estimate total tokens consumed; prompt wrap-up if over budget1090      if n_compactions * TRIGGER_THRESHOLD >= TOTAL_TOKEN_BUDGET:1091          messages.append(1092              {1093                  "role": "user",1094                  "content": "Please wrap up your current work and summarize the final state.",1095              }1096          )1097  ```10981099  ```typescript TypeScript1100  const client = new Anthropic();1101  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [1102    { role: "user", content: "Hello, Claude" }1103  ];1104  const TRIGGER_THRESHOLD = 100_000;1105  const TOTAL_TOKEN_BUDGET = 3_000_000;1106  let compactionCount = 0;11071108  const response = await client.beta.messages.create({1109    betas: ["compact-2026-01-12"],1110    model: "claude-opus-5",1111    max_tokens: 4096,1112    messages,1113    context_management: {1114      edits: [1115        {1116          type: "compact_20260112",1117          trigger: { type: "input_tokens", value: TRIGGER_THRESHOLD },1118          pause_after_compaction: true1119        }1120      ]1121    }1122  });11231124  if (response.stop_reason === "compaction") {1125    compactionCount += 1;1126    messages.push({ role: "assistant", content: response.content });11271128    // Estimate total tokens consumed; prompt wrap-up if over budget1129    if (compactionCount * TRIGGER_THRESHOLD >= TOTAL_TOKEN_BUDGET) {1130      messages.push({1131        role: "user",1132        content: "Please wrap up your current work and summarize the final state."1133      });1134    }1135  }1136  ```11371138  ```csharp C#1139  AnthropicClient client = new();1140  List<BetaMessageParam> messages = [new() { Role = Role.User, Content = "Hello, Claude" }];11411142  const int TriggerThreshold = 100_000;1143  const int TotalTokenBudget = 3_000_000;1144  int compactionCount = 0;11451146  var response = await client.Beta.Messages.Create(new()1147  {1148      Betas = ["compact-2026-01-12"],1149      Model = "claude-opus-5",1150      MaxTokens = 4096,1151      Messages = messages,1152      ContextManagement = new BetaContextManagementConfig1153      {1154          Edits = [new BetaCompact20260112Edit1155          {1156              Trigger = new BetaInputTokensTrigger(TriggerThreshold),1157              PauseAfterCompaction = true1158          }]1159      }1160  });11611162  if (response.StopReason == BetaStopReason.Compaction)1163  {1164      compactionCount += 1;1165      messages.Add(new()1166      {1167          Role = Role.Assistant,1168          Content = response.Content.Select(b => new BetaContentBlockParam(b.Json)).ToList()1169      });11701171      // Estimate total tokens consumed; prompt wrap-up if over budget1172      if (compactionCount * TriggerThreshold >= TotalTokenBudget)1173      {1174          messages.Add(new()1175          {1176              Role = Role.User,1177              Content = "Please wrap up your current work and summarize the final state."1178          });1179      }1180  }11811182  Console.WriteLine(response);1183  ```11841185  ```go Go1186  client := anthropic.NewClient()1187  messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}11881189  const triggerThreshold = 100_0001190  const totalTokenBudget = 3_000_0001191  compactionCount := 011921193  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1194  	Model:     anthropic.ModelClaudeOpus5,1195  	MaxTokens: 4096,1196  	Messages:  messages,1197  	ContextManagement: anthropic.BetaContextManagementConfigParam{1198  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1199  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{1200  				Trigger:              anthropic.BetaInputTokensTriggerParam{Value: triggerThreshold},1201  				PauseAfterCompaction: anthropic.Bool(true),1202  			}},1203  		},1204  	},1205  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},1206  })1207  if err != nil {1208  	log.Fatal(err)1209  }12101211  if response.StopReason == "compaction" {1212  	compactionCount++1213  	messages = append(messages, response.ToParam())12141215  	// Estimate total tokens consumed; prompt wrap-up if over budget1216  	if compactionCount*triggerThreshold >= totalTokenBudget {1217  		messages = append(messages, anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Please wrap up your current work and summarize the final state.")))1218  	}1219  }12201221  fmt.Println(response)1222  ```12231224  ```java Java1225  import com.anthropic.models.beta.messages.BetaContextManagementConfig;1226  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;1227  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;1228  import com.anthropic.models.beta.messages.BetaStopReason;1229  // ...1230          AnthropicClient client = AnthropicOkHttpClient.fromEnv();12311232          long triggerThreshold = 100_000;1233          long totalTokenBudget = 3_000_000;1234          int compactionCount = 0;12351236          List<BetaMessageParam> messages = new ArrayList<>();1237          messages.add(BetaMessageParam.builder()1238              .role(BetaMessageParam.Role.USER)1239              .content("Hello, Claude")1240              .build());12411242          MessageCreateParams params = MessageCreateParams.builder()1243              .addBeta("compact-2026-01-12")1244              .model("claude-opus-5")1245              .maxTokens(4096L)1246              .messages(messages)1247              .contextManagement(BetaContextManagementConfig.builder()1248                  .addEdit(BetaCompact20260112Edit.builder()1249                      .trigger(BetaInputTokensTrigger.builder()1250                          .value(triggerThreshold)1251                          .build())1252                      .pauseAfterCompaction(true)1253                      .build())1254                  .build())1255              .build();12561257          BetaMessage response = client.beta().messages().create(params);12581259          if (response.stopReason().isPresent()1260                  && response.stopReason().get().equals(BetaStopReason.COMPACTION)) {1261              compactionCount += 1;1262              messages.add(response.toParam());12631264              // Estimate total tokens consumed; prompt wrap-up if over budget1265              if (compactionCount * triggerThreshold >= totalTokenBudget) {1266                  messages.add(BetaMessageParam.builder()1267                      .role(BetaMessageParam.Role.USER)1268                      .content("Please wrap up your current work and summarize the final state.")1269                      .build());1270              }1271          }12721273          System.out.println(response);1274  ```12751276  ```php PHP1277  $client = new Client();12781279  $triggerThreshold = 100_000;1280  $totalTokenBudget = 3_000_000;1281  $compactionCount = 0;12821283  $messages = [['role' => 'user', 'content' => 'Hello, Claude']];12841285  $response = $client->beta->messages->create(1286      maxTokens: 4096,1287      messages: $messages,1288      model: 'claude-opus-5',1289      betas: ['compact-2026-01-12'],1290      contextManagement: [1291          'edits' => [1292              [1293                  'type' => 'compact_20260112',1294                  'trigger' => ['type' => 'input_tokens', 'value' => $triggerThreshold],1295                  'pause_after_compaction' => true1296              ]1297          ]1298      ]1299  );13001301  if ($response->stopReason === 'compaction') {1302      $compactionCount += 1;1303      $messages[] = ['role' => 'assistant', 'content' => $response->content];13041305      // Estimate total tokens consumed; prompt wrap-up if over budget1306      if ($compactionCount * $triggerThreshold >= $totalTokenBudget) {1307          $messages[] = [1308              'role' => 'user',1309              'content' => 'Please wrap up your current work and summarize the final state.'1310          ];1311      }1312  }1313  ```13141315  ```ruby Ruby1316  client = Anthropic::Client.new1317  messages = [{ role: "user", content: "Hello, Claude" }]1318  TRIGGER_THRESHOLD = 100_0001319  TOTAL_TOKEN_BUDGET = 3_000_0001320  compaction_count = 013211322  response = client.beta.messages.create(1323    betas: ["compact-2026-01-12"],1324    model: "claude-opus-5",1325    max_tokens: 4096,1326    messages: messages,1327    context_management: {1328      edits: [1329        {1330          type: "compact_20260112",1331          trigger: { type: "input_tokens", value: TRIGGER_THRESHOLD },1332          pause_after_compaction: true1333        }1334      ]1335    }1336  )13371338  if response.stop_reason == :compaction1339    compaction_count += 11340    messages << { role: "assistant", content: response.content }13411342    # Estimate total tokens consumed; prompt wrap-up if over budget1343    if compaction_count * TRIGGER_THRESHOLD >= TOTAL_TOKEN_BUDGET1344      messages << {1345        role: "user",1346        content: "Please wrap up your current work and summarize the final state."1347      }1348    end1349  end1350  ```1351</CodeGroup>13521353## Working with compaction blocks13541355When compaction is triggered, the API returns a `compaction` block at the start of the assistant response.13561357A long-running conversation might result in multiple compactions. The last compaction block reflects the final state of the prompt, replacing content prior to it with the generated summary.13581359```json Output1360{1361  "content": [1362    {1363      "type": "compaction",1364      "content": "Summary of the conversation: The user requested help building a web scraper..."1365    },1366    {1367      "type": "text",1368      "text": "Based on our conversation so far..."1369    }1370  ]1371}1372```13731374### Passing compaction blocks back13751376You must pass the `compaction` block back to the API on subsequent requests to continue the conversation with the shortened prompt. The simplest approach is to append the entire response content to your messages:13771378<CodeGroup>1379  ```bash cURL1380  # The response content, including the compaction block, must go back to the1381  # API as the assistant turn of the next request. Managing that message list1382  # doesn't translate well to a one-off shell command; see the CLI and SDK1383  # tabs for the full flow. First request:1384  curl https://api.anthropic.com/v1/messages \1385    -H "x-api-key: $ANTHROPIC_API_KEY" \1386    -H "anthropic-version: 2023-06-01" \1387    -H "anthropic-beta: compact-2026-01-12" \1388    -H "content-type: application/json" \1389    -d '{1390      "model": "claude-opus-5",1391      "max_tokens": 4096,1392      "messages": [1393        {1394          "role": "user",1395          "content": "Hello, Claude"1396        }1397      ],1398      "context_management": {1399        "edits": [1400          {1401            "type": "compact_20260112"1402          }1403        ]1404      }1405    }'1406  ```14071408  ```bash CLI1409  ant beta:messages create \1410    --beta compact-2026-01-12 \1411    --transform content \1412    --format jsonl <<'YAML' > content.json1413  model: claude-opus-51414  max_tokens: 40961415  messages:1416    - role: user1417      content: Hello, Claude1418  context_management:1419    edits:1420      - type: compact_202601121421  YAML14221423  # After receiving a response with a compaction block, append it as the1424  # assistant turn and continue the conversation1425  ant beta:messages create --beta compact-2026-01-12 <<YAML1426  model: claude-opus-51427  max_tokens: 40961428  messages:1429    - role: user1430      content: Hello, Claude1431    - role: assistant1432      content: $(cat content.json)1433    - role: user1434      content: Now add error handling1435  context_management:1436    edits:1437      - type: compact_202601121438  YAML1439  ```14401441  ```python Python1442  client = anthropic.Anthropic()1443  messages = [{"role": "user", "content": "Hello, Claude"}]1444  response = client.beta.messages.create(1445      betas=["compact-2026-01-12"],1446      model="claude-opus-5",1447      max_tokens=4096,1448      messages=messages,1449      context_management={"edits": [{"type": "compact_20260112"}]},1450  )1451  # After receiving a response with a compaction block1452  messages.append({"role": "assistant", "content": response.content})14531454  # Continue the conversation1455  messages.append({"role": "user", "content": "Now add error handling"})14561457  response = client.beta.messages.create(1458      betas=["compact-2026-01-12"],1459      model="claude-opus-5",1460      max_tokens=4096,1461      messages=messages,1462      context_management={"edits": [{"type": "compact_20260112"}]},1463  )1464  ```14651466  ```typescript TypeScript1467  const client = new Anthropic();1468  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [1469    { role: "user", content: "Hello, Claude" }1470  ];14711472  const response = await client.beta.messages.create({1473    betas: ["compact-2026-01-12"],1474    model: "claude-opus-5",1475    max_tokens: 4096,1476    messages,1477    context_management: {1478      edits: [{ type: "compact_20260112" }]1479    }1480  });14811482  // After receiving a response with a compaction block1483  messages.push({1484    role: "assistant",1485    content: response.content1486  });14871488  // Continue the conversation1489  messages.push({ role: "user", content: "Now add error handling" });14901491  const nextResponse = await client.beta.messages.create({1492    betas: ["compact-2026-01-12"],1493    model: "claude-opus-5",1494    max_tokens: 4096,1495    messages,1496    context_management: {1497      edits: [{ type: "compact_20260112" }]1498    }1499  });1500  ```15011502  ```csharp C#1503  AnthropicClient client = new();15041505  var messages = new List<BetaMessageParam>1506  {1507      new() { Role = Role.User, Content = "Help me build a web scraper" }1508  };15091510  var response = await client.Beta.Messages.Create(new()1511  {1512      Betas = ["compact-2026-01-12"],1513      Model = "claude-opus-5",1514      MaxTokens = 4096,1515      Messages = messages,1516      ContextManagement = new BetaContextManagementConfig1517      {1518          Edits = [new BetaCompact20260112Edit()]1519      }1520  });15211522  messages.Add(new BetaMessageParam1523  {1524      Role = Role.Assistant,1525      Content = response.Content.Select(block => new BetaContentBlockParam(block.Json)).ToList()1526  });15271528  messages.Add(new BetaMessageParam { Role = Role.User, Content = "Now add error handling" });15291530  var nextResponse = await client.Beta.Messages.Create(new()1531  {1532      Betas = ["compact-2026-01-12"],1533      Model = "claude-opus-5",1534      MaxTokens = 4096,1535      Messages = messages,1536      ContextManagement = new BetaContextManagementConfig1537      {1538          Edits = [new BetaCompact20260112Edit()]1539      }1540  });15411542  Console.WriteLine(nextResponse);1543  ```15441545  ```go Go1546  client := anthropic.NewClient()15471548  messages := []anthropic.BetaMessageParam{1549  	anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Help me build a web scraper")),1550  }15511552  compactEdit := anthropic.BetaContextManagementConfigParam{1553  	Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1554  		{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},1555  	},1556  }15571558  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1559  	Model:             anthropic.ModelClaudeOpus5,1560  	MaxTokens:         4096,1561  	Messages:          messages,1562  	ContextManagement: compactEdit,1563  	Betas:             []anthropic.AnthropicBeta{"compact-2026-01-12"},1564  })1565  if err != nil {1566  	log.Fatal(err)1567  }15681569  messages = append(messages, response.ToParam())15701571  messages = append(messages, anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Now add error handling")))15721573  nextResponse, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1574  	Model:             anthropic.ModelClaudeOpus5,1575  	MaxTokens:         4096,1576  	Messages:          messages,1577  	ContextManagement: compactEdit,1578  	Betas:             []anthropic.AnthropicBeta{"compact-2026-01-12"},1579  })1580  if err != nil {1581  	log.Fatal(err)1582  }15831584  fmt.Println(nextResponse)1585  ```15861587  ```java Java1588  import com.anthropic.models.beta.messages.BetaContextManagementConfig;1589  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;1590  // ...1591          AnthropicClient client = AnthropicOkHttpClient.fromEnv();15921593          // First request1594          BetaMessage response = client.beta().messages().create(1595              MessageCreateParams.builder()1596                  .addBeta("compact-2026-01-12")1597                  .model("claude-opus-5")1598                  .maxTokens(4096L)1599                  .addUserMessage("Help me build a web scraper")1600                  .contextManagement(BetaContextManagementConfig.builder()1601                      .addEdit(BetaCompact20260112Edit.builder().build())1602                      .build())1603                  .build());16041605          // After receiving a response with a compaction block, append the full1606          // content (including compaction blocks) and continue the conversation1607          BetaMessage nextResponse = client.beta().messages().create(1608              MessageCreateParams.builder()1609                  .addBeta("compact-2026-01-12")1610                  .model("claude-opus-5")1611                  .maxTokens(4096L)1612                  .addUserMessage("Help me build a web scraper")1613                  .addMessage(response)1614                  .addUserMessage("Now add error handling")1615                  .contextManagement(BetaContextManagementConfig.builder()1616                      .addEdit(BetaCompact20260112Edit.builder().build())1617                      .build())1618                  .build());16191620          System.out.println(nextResponse);1621  ```16221623  ```php PHP1624  $client = new Client();16251626  $messages = [1627      ['role' => 'user', 'content' => 'Help me build a web scraper']1628  ];16291630  $response = $client->beta->messages->create(1631      maxTokens: 4096,1632      messages: $messages,1633      model: 'claude-opus-5',1634      betas: ['compact-2026-01-12'],1635      contextManagement: [1636          'edits' => [['type' => 'compact_20260112']]1637      ]1638  );16391640  $messages[] = ['role' => 'assistant', 'content' => $response->content];16411642  $messages[] = ['role' => 'user', 'content' => 'Now add error handling'];16431644  $nextResponse = $client->beta->messages->create(1645      maxTokens: 4096,1646      messages: $messages,1647      model: 'claude-opus-5',1648      betas: ['compact-2026-01-12'],1649      contextManagement: [1650          'edits' => [['type' => 'compact_20260112']]1651      ]1652  );16531654  echo json_encode($nextResponse, JSON_PRETTY_PRINT), PHP_EOL;1655  ```16561657  ```ruby Ruby1658  client = Anthropic::Client.new16591660  messages = [1661    { role: "user", content: "Help me build a web scraper" }1662  ]16631664  response = client.beta.messages.create(1665    betas: ["compact-2026-01-12"],1666    model: "claude-opus-5",1667    max_tokens: 4096,1668    messages: messages,1669    context_management: {1670      edits: [{ type: "compact_20260112" }]1671    }1672  )16731674  messages << { role: "assistant", content: response.content }16751676  messages << { role: "user", content: "Now add error handling" }16771678  next_response = client.beta.messages.create(1679    betas: ["compact-2026-01-12"],1680    model: "claude-opus-5",1681    max_tokens: 4096,1682    messages: messages,1683    context_management: {1684      edits: [{ type: "compact_20260112" }]1685    }1686  )16871688  puts next_response.content1689  ```1690</CodeGroup>16911692When the API receives a `compaction` block, all content blocks before it are ignored. You can either:16931694* Keep the original messages in your list and let the API handle removing the compacted content1695* Manually drop the compacted messages and only include the compaction block onwards16961697On Claude Fable 5.1 and Claude Mythos 5.1, thinking blocks from before a `compaction` block aren't carried forward, so the summary is all the model has of that earlier work. If you write your own `instructions`, tell the model what the summary must retain; see [Tell the model what to preserve in compaction summaries](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#tell-the-model-what-to-preserve-in-compaction-summaries).16981699### Streaming17001701The compaction block streams differently from text blocks. You receive a `content_block_start` event, followed by a single `content_block_delta` with the complete summary content (no intermediate streaming), and then a `content_block_stop` event.17021703<CodeGroup>1704  ```bash cURL1705  curl https://api.anthropic.com/v1/messages \1706    -H "x-api-key: $ANTHROPIC_API_KEY" \1707    -H "anthropic-version: 2023-06-01" \1708    -H "anthropic-beta: compact-2026-01-12" \1709    -H "content-type: application/json" \1710    -d '{1711      "model": "claude-opus-5",1712      "max_tokens": 4096,1713      "stream": true,1714      "messages": [1715        {1716          "role": "user",1717          "content": "Hello, Claude"1718        }1719      ],1720      "context_management": {1721        "edits": [1722          {1723            "type": "compact_20260112"1724          }1725        ]1726      }1727    }'1728  ```17291730  ```bash CLI1731  ant beta:messages create \1732    --stream \1733    --beta compact-2026-01-12 \1734    --format jsonl <<'YAML'1735  model: claude-opus-51736  max_tokens: 40961737  messages:1738    - role: user1739      content: Hello, Claude1740  context_management:1741    edits:1742      - type: compact_202601121743  YAML1744  ```17451746  ```python Python1747  client = anthropic.Anthropic()1748  messages = [{"role": "user", "content": "Hello, Claude"}]17491750  with client.beta.messages.stream(1751      betas=["compact-2026-01-12"],1752      model="claude-opus-5",1753      max_tokens=4096,1754      messages=messages,1755      context_management={"edits": [{"type": "compact_20260112"}]},1756  ) as stream:1757      for event in stream:1758          match event.type:1759              case "content_block_start":1760                  block = event.content_block1761                  match block.type:1762                      case "compaction":1763                          print("Compaction started...")1764                      case "text":1765                          print("Text response started...")17661767              case "content_block_delta":1768                  delta = event.delta1769                  match delta.type:1770                      case "compaction_delta":1771                          print(f"Compaction complete: {len(delta.content or '')} chars")1772                      case "text_delta":1773                          print(delta.text, end="", flush=True)17741775      # Get the final accumulated message1776      message = stream.get_final_message()1777      messages.append({"role": "assistant", "content": message.content})1778  ```17791780  ```typescript TypeScript1781  const client = new Anthropic();1782  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [1783    { role: "user", content: "Hello, Claude" }1784  ];17851786  const stream = await client.beta.messages.stream({1787    betas: ["compact-2026-01-12"],1788    model: "claude-opus-5",1789    max_tokens: 4096,1790    messages,1791    context_management: {1792      edits: [{ type: "compact_20260112" }]1793    }1794  });17951796  for await (const event of stream) {1797    switch (event.type) {1798      case "content_block_start":1799        switch (event.content_block.type) {1800          case "compaction":1801            console.log("Compaction started...");1802            break;1803          case "text":1804            console.log("Text response started...");1805            break;1806        }1807        break;1808      case "content_block_delta":1809        switch (event.delta.type) {1810          case "compaction_delta":1811            console.log(`Compaction complete: ${event.delta.content?.length ?? 0} chars`);1812            break;1813          case "text_delta":1814            process.stdout.write(event.delta.text);1815            break;1816        }1817        break;1818    }1819  }18201821  // Get the final accumulated message1822  const message = await stream.finalMessage();1823  messages.push({1824    role: "assistant",1825    content: message.content1826  });1827  ```18281829  ```csharp C#1830  var client = new AnthropicClient();1831  List<BetaMessageParam> messages = [new() { Role = Role.User, Content = "Hello" }];18321833  var parameters = new MessageCreateParams1834  {1835      Betas = ["compact-2026-01-12"],1836      Model = "claude-opus-5",1837      MaxTokens = 4096,1838      Messages = messages,1839      ContextManagement = new BetaContextManagementConfig1840      {1841          Edits = [new BetaCompact20260112Edit()]1842      }1843  };18441845  await foreach (var streamEvent in client.Beta.Messages.CreateStreaming(parameters))1846  {1847      if (streamEvent.TryPickContentBlockStart(out var startEvent))1848      {1849          if (startEvent.ContentBlock.TryPickBetaCompaction(out _))1850          {1851              Console.WriteLine("Compaction started...");1852          }1853          else if (startEvent.ContentBlock.TryPickBetaText(out _))1854          {1855              Console.WriteLine("Text response started...");1856          }1857      }1858      else if (streamEvent.TryPickContentBlockDelta(out var deltaEvent))1859      {1860          if (deltaEvent.Delta.TryPickCompaction(out var compactionDelta))1861          {1862              Console.WriteLine($"Compaction complete: {compactionDelta.Content?.Length ?? 0} chars");1863          }1864          else if (deltaEvent.Delta.TryPickText(out var textDelta))1865          {1866              Console.Write(textDelta.Text);1867          }1868      }1869  }1870  ```18711872  ```go Go1873  client := anthropic.NewClient()1874  messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}18751876  stream := client.Beta.Messages.NewStreaming(context.TODO(), anthropic.BetaMessageNewParams{1877  	Model:     anthropic.ModelClaudeOpus5,1878  	MaxTokens: 4096,1879  	Messages:  messages,1880  	ContextManagement: anthropic.BetaContextManagementConfigParam{1881  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1882  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},1883  		},1884  	},1885  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},1886  })18871888  for stream.Next() {1889  	event := stream.Current()1890  	switch eventVariant := event.AsAny().(type) {1891  	case anthropic.BetaRawContentBlockStartEvent:1892  		switch eventVariant.ContentBlock.AsAny().(type) {1893  		case anthropic.BetaCompactionBlock:1894  			fmt.Println("Compaction started...")1895  		case anthropic.BetaTextBlock:1896  			fmt.Println("Text response started...")1897  		}1898  	case anthropic.BetaRawContentBlockDeltaEvent:1899  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {1900  		case anthropic.BetaCompactionContentBlockDelta:1901  			fmt.Printf("Compaction complete: %d chars\n", len(deltaVariant.Content))1902  		case anthropic.BetaTextDelta:1903  			fmt.Print(deltaVariant.Text)1904  		}1905  	}1906  }1907  if err := stream.Err(); err != nil {1908  	log.Fatal(err)1909  }1910  ```19111912  ```java Java1913  import com.anthropic.models.beta.messages.BetaContextManagementConfig;1914  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;1915  // ...1916          AnthropicClient client = AnthropicOkHttpClient.fromEnv();19171918          MessageCreateParams params = MessageCreateParams.builder()1919              .model("claude-opus-5")1920              .maxTokens(4096L)1921              .addBeta("compact-2026-01-12")1922              .addUserMessage("Hello, Claude")1923              .contextManagement(BetaContextManagementConfig.builder()1924                  .addEdit(BetaCompact20260112Edit.builder().build())1925                  .build())1926              .build();19271928          try (var streamResponse = client.beta().messages().createStreaming(params)) {1929              streamResponse.stream().forEach(event -> {1930                  event.contentBlockStart().ifPresent(startEvent -> {1931                      startEvent.contentBlock().compaction().ifPresent(c ->1932                          System.out.println("Compaction started...")1933                      );1934                      startEvent.contentBlock().text().ifPresent(t ->1935                          System.out.println("Text response started...")1936                      );1937                  });19381939                  event.contentBlockDelta().ifPresent(deltaEvent -> {1940                      deltaEvent.delta().compaction().ifPresent(cd ->1941                          System.out.println("Compaction complete: " + cd.content().map(String::length).orElse(0) + " chars")1942                      );1943                      deltaEvent.delta().text().ifPresent(td ->1944                          System.out.print(td.text())1945                      );1946                  });1947              });1948          }1949  ```19501951  ```php PHP1952  use Anthropic\Beta\Messages\BetaCompactionBlock;1953  use Anthropic\Beta\Messages\BetaCompactionContentBlockDelta;1954  use Anthropic\Beta\Messages\BetaRawContentBlockDeltaEvent;1955  use Anthropic\Beta\Messages\BetaRawContentBlockStartEvent;1956  use Anthropic\Beta\Messages\BetaTextBlock;1957  use Anthropic\Beta\Messages\BetaTextDelta;19581959  $client = new Client();1960  $messages = [['role' => 'user', 'content' => 'Hello, Claude']];19611962  $stream = $client->beta->messages->createStream(1963      maxTokens: 4096,1964      messages: $messages,1965      model: 'claude-opus-5',1966      betas: ['compact-2026-01-12'],1967      contextManagement: [1968          'edits' => [1969              ['type' => 'compact_20260112']1970          ]1971      ]1972  );19731974  foreach ($stream as $event) {1975      switch (true) {1976          case $event instanceof BetaRawContentBlockStartEvent:1977              switch (true) {1978                  case $event->contentBlock instanceof BetaCompactionBlock:1979                      echo "Compaction started...\n";1980                      break;1981                  case $event->contentBlock instanceof BetaTextBlock:1982                      echo "Text response started...\n";1983                      break;1984              }1985              break;1986          case $event instanceof BetaRawContentBlockDeltaEvent:1987              switch (true) {1988                  case $event->delta instanceof BetaCompactionContentBlockDelta:1989                      echo "Compaction complete: " . strlen($event->delta->content ?? '') . " chars\n";1990                      break;1991                  case $event->delta instanceof BetaTextDelta:1992                      echo $event->delta->text;1993                      break;1994              }1995              break;1996      }1997  }1998  ```19992000  ```ruby Ruby2001  client = Anthropic::Client.new2002  messages = [{ role: "user", content: "Hello, Claude" }]20032004  stream = client.beta.messages.stream(2005    betas: ["compact-2026-01-12"],2006    model: "claude-opus-5",2007    max_tokens: 4096,2008    messages: messages,2009    context_management: {2010      edits: [{ type: "compact_20260112" }]2011    }2012  )20132014  stream.each do |event|2015    case event2016    when Anthropic::Models::BetaRawContentBlockStartEvent2017      case event.content_block2018      when Anthropic::Models::BetaCompactionBlock2019        puts "Compaction started..."2020      when Anthropic::Models::BetaTextBlock2021        puts "Text response started..."2022      end2023    when Anthropic::Models::BetaRawContentBlockDeltaEvent2024      delta = event.delta2025      case delta2026      when Anthropic::Models::BetaCompactionContentBlockDelta2027        puts "Compaction complete: #{(delta.content || "").length} chars"2028      when Anthropic::Models::BetaTextDelta2029        print delta.text2030      end2031    end2032  end2033  ```2034</CodeGroup>20352036### Prompt caching20372038Compaction works well with [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching). You can add a `cache_control` breakpoint on compaction blocks to cache the summarized content.20392040```json2041{2042  "role": "assistant",2043  "content": [2044    {2045      "type": "compaction",2046      "content": "[summary text]",2047      "cache_control": { "type": "ephemeral" }2048    },2049    {2050      "type": "text",2051      "text": "Based on our conversation..."2052    }2053  ]2054}2055```20562057#### Maximizing cache hits with system prompts20582059When compaction occurs, the summary becomes new content that needs to be written to the cache. Without additional cache breakpoints, this would also invalidate any cached system prompt, requiring it to be re-cached along with the compaction summary.20602061To maximize cache hit rates, add a `cache_control` breakpoint at the end of your system prompt. This keeps the system prompt cached separately from the conversation, so when compaction occurs:20622063* The system prompt cache remains valid and is read from cache2064* Only the compaction summary needs to be written as a new cache entry20652066<CodeGroup>2067  ```bash cURL2068  curl https://api.anthropic.com/v1/messages \2069    -H "x-api-key: $ANTHROPIC_API_KEY" \2070    -H "anthropic-version: 2023-06-01" \2071    -H "anthropic-beta: compact-2026-01-12" \2072    -H "content-type: application/json" \2073    -d '{2074      "model": "claude-opus-5",2075      "max_tokens": 4096,2076      "system": [2077        {2078          "type": "text",2079          "text": "You are a helpful coding assistant...",2080          "cache_control": {2081            "type": "ephemeral"2082          }2083        }2084      ],2085      "messages": [2086        {2087          "role": "user",2088          "content": "Hello, Claude"2089        }2090      ],2091      "context_management": {2092        "edits": [2093          {2094            "type": "compact_20260112"2095          }2096        ]2097      }2098    }'2099  ```21002101  ```bash CLI2102  ant beta:messages create --beta compact-2026-01-12 <<'YAML'2103  model: claude-opus-52104  max_tokens: 40962105  system:2106    - type: text2107      text: You are a helpful coding assistant...2108      cache_control:2109        type: ephemeral2110  messages:2111    - role: user2112      content: Hello, Claude2113  context_management:2114    edits:2115      - type: compact_202601122116  YAML2117  ```21182119  ```python Python2120  client = anthropic.Anthropic()2121  messages = [{"role": "user", "content": "Hello, Claude"}]2122  response = client.beta.messages.create(2123      betas=["compact-2026-01-12"],2124      model="claude-opus-5",2125      max_tokens=4096,2126      system=[2127          {2128              "type": "text",2129              "text": "You are a helpful coding assistant...",2130              "cache_control": {2131                  "type": "ephemeral"2132              },  # Cache the system prompt separately2133          }2134      ],2135      messages=messages,2136      context_management={"edits": [{"type": "compact_20260112"}]},2137  )2138  ```21392140  ```typescript TypeScript2141  const client = new Anthropic();2142  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [2143    { role: "user", content: "Hello, Claude" }2144  ];21452146  const response = await client.beta.messages.create({2147    betas: ["compact-2026-01-12"],2148    model: "claude-opus-5",2149    max_tokens: 4096,2150    system: [2151      {2152        type: "text",2153        text: "You are a helpful coding assistant...",2154        cache_control: { type: "ephemeral" } // Cache the system prompt separately2155      }2156    ],2157    messages,2158    context_management: {2159      edits: [{ type: "compact_20260112" }]2160    }2161  });2162  ```21632164  ```csharp C#2165  var client = new AnthropicClient();21662167  var parameters = new MessageCreateParams2168  {2169      Betas = ["compact-2026-01-12"],2170      Model = "claude-opus-5",2171      MaxTokens = 4096,2172      System = new List<BetaTextBlockParam>2173      {2174          new()2175          {2176              Text = "You are a helpful coding assistant...",2177              CacheControl = new BetaCacheControlEphemeral()2178          }2179      },2180      Messages = [new() { Role = Role.User, Content = "Hello, Claude" }],2181      ContextManagement = new BetaContextManagementConfig2182      {2183          Edits = [new BetaCompact20260112Edit()]2184      }2185  };21862187  var response = await client.Beta.Messages.Create(parameters);2188  Console.WriteLine(response);2189  ```21902191  ```go Go2192  client := anthropic.NewClient()21932194  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{2195  	Model:     anthropic.ModelClaudeOpus5,2196  	MaxTokens: 4096,2197  	System: []anthropic.BetaTextBlockParam{2198  		{2199  			Text:         "You are a helpful coding assistant...",2200  			CacheControl: anthropic.NewBetaCacheControlEphemeralParam(),2201  		},2202  	},2203  	Messages: []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))},2204  	ContextManagement: anthropic.BetaContextManagementConfigParam{2205  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{2206  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},2207  		},2208  	},2209  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},2210  })2211  if err != nil {2212  	log.Fatal(err)2213  }2214  fmt.Println(response)2215  ```22162217  ```java Java2218  import com.anthropic.models.beta.messages.BetaContextManagementConfig;2219  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;2220  import com.anthropic.models.beta.messages.BetaCacheControlEphemeral;2221  // ...2222          AnthropicClient client = AnthropicOkHttpClient.fromEnv();22232224          MessageCreateParams params = MessageCreateParams.builder()2225              .model("claude-opus-5")2226              .maxTokens(4096L)2227              .addBeta("compact-2026-01-12")2228              .systemOfBetaTextBlockParams(List.of(2229                  BetaTextBlockParam.builder()2230                      .text("You are a helpful coding assistant...")2231                      .cacheControl(BetaCacheControlEphemeral.builder().build())2232                      .build()2233              ))2234              .addUserMessage("Hello, Claude")2235              .contextManagement(BetaContextManagementConfig.builder()2236                  .addEdit(BetaCompact20260112Edit.builder().build())2237                  .build())2238              .build();22392240          BetaMessage response = client.beta().messages().create(params);2241          System.out.println(response);2242  ```22432244  ```php PHP2245  $client = new Client();22462247  $response = $client->beta->messages->create(2248      maxTokens: 4096,2249      messages: [['role' => 'user', 'content' => 'Hello, Claude']],2250      model: 'claude-opus-5',2251      betas: ['compact-2026-01-12'],2252      system: [2253          [2254              'type' => 'text',2255              'text' => 'You are a helpful coding assistant...',2256              'cache_control' => [2257                  'type' => 'ephemeral'2258              ]2259          ]2260      ],2261      contextManagement: [2262          'edits' => [2263              ['type' => 'compact_20260112']2264          ]2265      ]2266  );22672268  echo json_encode($response, JSON_PRETTY_PRINT), PHP_EOL;2269  ```22702271  ```ruby Ruby2272  client = Anthropic::Client.new22732274  response = client.beta.messages.create(2275    betas: ["compact-2026-01-12"],2276    model: "claude-opus-5",2277    max_tokens: 4096,2278    system: [2279      {2280        type: "text",2281        text: "You are a helpful coding assistant...",2282        cache_control: {2283          type: "ephemeral"2284        }2285      }2286    ],2287    messages: [{ role: "user", content: "Hello, Claude" }],2288    context_management: {2289      edits: [{ type: "compact_20260112" }]2290    }2291  )2292  puts response2293  ```2294</CodeGroup>22952296This keeps long system prompts cached across multiple compaction events throughout a conversation.22972298## Understanding usage22992300Compaction requires an additional sampling step, which contributes to rate limits and billing. The API returns detailed usage information in the response:23012302```json Output2303{2304  "usage": {2305    "input_tokens": 23000,2306    "output_tokens": 1000,2307    "iterations": [2308      {2309        "type": "compaction",2310        "input_tokens": 180000,2311        "output_tokens": 35002312      },2313      {2314        "type": "message",2315        "input_tokens": 23000,2316        "output_tokens": 10002317      }2318    ]2319  }2320}2321```23222323The `iterations` array shows usage for each sampling iteration. When compaction occurs, you'll see a `compaction` iteration followed by the main `message` iteration. The top-level `input_tokens` and `output_tokens` match the `message` iteration exactly in this example because there is only one non-compaction iteration. The final iteration's token counts reflect the effective context size after compaction.23242325<Note>2326  The top-level `input_tokens` and `output_tokens` do not include compaction iteration usage. They reflect the sum of all non-compaction iterations. To calculate total tokens consumed and billed for a request, sum across all entries in the `usage.iterations` array.23272328  If you previously relied on `usage.input_tokens` and `usage.output_tokens` for cost tracking or auditing, you'll need to update your tracking logic to aggregate across `usage.iterations` when compaction is enabled. With the compaction beta enabled, every response includes `usage.iterations`, even if no compaction occurred. A `compaction` entry appears only when a new compaction is triggered during the request. Re-applying a previous `compaction` block incurs no additional compaction cost, and the top-level usage fields remain accurate in that case.2329</Note>23302331## Combining with other features23322333### Server tools23342335When using server tools (such as web search), the compaction trigger is checked at the start of each sampling iteration. Compaction might occur multiple times within a single request depending on your trigger threshold and the amount of output generated.23362337### Token counting23382339The token counting endpoint (`/v1/messages/count_tokens`) applies existing `compaction` blocks in your prompt but does not trigger new compactions. Use it to check your effective token count after previous compactions:23402341<CodeGroup>2342  ```bash cURL2343  curl https://api.anthropic.com/v1/messages/count_tokens \2344    -H "x-api-key: $ANTHROPIC_API_KEY" \2345    -H "anthropic-version: 2023-06-01" \2346    -H "anthropic-beta: compact-2026-01-12" \2347    -H "content-type: application/json" \2348    -d '{2349      "model": "claude-opus-5",2350      "messages": [2351        {2352          "role": "user",2353          "content": "Hello, Claude"2354        }2355      ],2356      "context_management": {2357        "edits": [2358          {2359            "type": "compact_20260112"2360          }2361        ]2362      }2363    }'2364  ```23652366  ```bash CLI2367  cat > request.yaml <<'YAML'2368  model: claude-opus-52369  messages:2370    - role: user2371      content: Hello, Claude2372  context_management:2373    edits:2374      - type: compact_202601122375  YAML23762377  CURRENT=$(ant beta:messages count-tokens \2378    --beta compact-2026-01-12 \2379    --transform input_tokens \2380    --raw-output < request.yaml)23812382  ORIGINAL=$(ant beta:messages count-tokens \2383    --beta compact-2026-01-12 \2384    --transform context_management.original_input_tokens \2385    --raw-output < request.yaml)23862387  printf 'Current tokens: %s\n' "$CURRENT"2388  printf 'Original tokens: %s\n' "$ORIGINAL"2389  ```23902391  ```python Python2392  client = anthropic.Anthropic()2393  messages = [{"role": "user", "content": "Hello, Claude"}]2394  count_response = client.beta.messages.count_tokens(2395      betas=["compact-2026-01-12"],2396      model="claude-opus-5",2397      messages=messages,2398      context_management={"edits": [{"type": "compact_20260112"}]},2399  )24002401  print(f"Current tokens: {count_response.input_tokens}")2402  print(f"Original tokens: {count_response.context_management.original_input_tokens}")2403  ```24042405  ```typescript TypeScript2406  const client = new Anthropic();2407  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [2408    { role: "user", content: "Summarize the key points of our conversation so far." }2409  ];24102411  const countResponse = await client.beta.messages.countTokens({2412    betas: ["compact-2026-01-12"],2413    model: "claude-opus-5",2414    messages,2415    context_management: {2416      edits: [{ type: "compact_20260112" }]2417    }2418  });24192420  console.log(`Current tokens: ${countResponse.input_tokens}`);2421  console.log(`Original tokens: ${countResponse.context_management!.original_input_tokens}`);2422  ```24232424  ```csharp C#2425  AnthropicClient client = new();2426  List<BetaMessageParam> messages = [new() { Role = Role.User, Content = "Hello" }];24272428  var countParams = new MessageCountTokensParams2429  {2430      Model = "claude-opus-5",2431      Messages = messages,2432      ContextManagement = new BetaContextManagementConfig2433      {2434          Edits = [new BetaCompact20260112Edit()]2435      },2436      Betas = ["compact-2026-01-12"]2437  };24382439  var countResponse = await client.Beta.Messages.CountTokens(countParams);2440  Console.WriteLine($"Current tokens: {countResponse.InputTokens}");2441  Console.WriteLine($"Original tokens: {countResponse.ContextManagement?.OriginalInputTokens}");2442  ```24432444  ```go Go2445  client := anthropic.NewClient()2446  messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}24472448  countResponse, err := client.Beta.Messages.CountTokens(context.TODO(), anthropic.BetaMessageCountTokensParams{2449  	Model:    anthropic.ModelClaudeOpus5,2450  	Messages: messages,2451  	ContextManagement: anthropic.BetaContextManagementConfigParam{2452  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{2453  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},2454  		},2455  	},2456  	Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},2457  })2458  if err != nil {2459  	log.Fatal(err)2460  }24612462  fmt.Printf("Current tokens: %d\n", countResponse.InputTokens)2463  fmt.Printf("Original tokens: %d\n", countResponse.ContextManagement.OriginalInputTokens)2464  ```24652466  ```java Java2467  import com.anthropic.models.beta.messages.BetaMessageTokensCount;2468  import com.anthropic.models.beta.messages.MessageCountTokensParams;2469  import com.anthropic.models.beta.messages.BetaContextManagementConfig;2470  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;2471  // ...2472          AnthropicClient client = AnthropicOkHttpClient.fromEnv();24732474          MessageCountTokensParams params = MessageCountTokensParams.builder()2475              .model("claude-opus-5")2476              .addUserMessage("Hello, Claude")2477              .contextManagement(BetaContextManagementConfig.builder()2478                  .addEdit(BetaCompact20260112Edit.builder().build())2479                  .build())2480              .addBeta("compact-2026-01-12")2481              .build();24822483          BetaMessageTokensCount countResponse = client.beta().messages().countTokens(params);2484          System.out.println("Current tokens: " + countResponse.inputTokens());2485          System.out.println("Original tokens: " + countResponse.contextManagement().get().originalInputTokens());2486  ```24872488  ```php PHP2489  $client = new Client();2490  $messages = [['role' => 'user', 'content' => 'Hello, Claude']];24912492  $countResponse = $client->beta->messages->countTokens(2493      messages: $messages,2494      model: 'claude-opus-5',2495      betas: ['compact-2026-01-12'],2496      contextManagement: [2497          'edits' => [2498              ['type' => 'compact_20260112']2499          ]2500      ]2501  );25022503  echo "Current tokens: " . $countResponse->inputTokens . "\n";2504  echo "Original tokens: " . $countResponse->contextManagement->originalInputTokens . "\n";2505  ```25062507  ```ruby Ruby2508  client = Anthropic::Client.new2509  messages = [{ role: "user", content: "Hello, Claude" }]25102511  count_response = client.beta.messages.count_tokens(2512    betas: ["compact-2026-01-12"],2513    model: "claude-opus-5",2514    messages: messages,2515    context_management: {2516      edits: [{ type: "compact_20260112" }]2517    }2518  )25192520  puts "Current tokens: #{count_response.input_tokens}"2521  puts "Original tokens: #{count_response.context_management.original_input_tokens}"2522  ```2523</CodeGroup>25242525## Examples25262527Here's a complete example of a long-running conversation with compaction:25282529<CodeGroup>2530  ```bash cURL2531  # curl sends individual requests; maintain the messages array in the2532  # calling script. See the SDK tabs for the full chat() loop. Single-turn2533  # request shape:2534  curl https://api.anthropic.com/v1/messages \2535    -H "x-api-key: $ANTHROPIC_API_KEY" \2536    -H "anthropic-version: 2023-06-01" \2537    -H "anthropic-beta: compact-2026-01-12" \2538    -H "content-type: application/json" \2539    -d '{2540      "model": "claude-opus-5",2541      "max_tokens": 4096,2542      "messages": [2543        {2544          "role": "user",2545          "content": "Help me build a Python web scraper"2546        }2547      ],2548      "context_management": {2549        "edits": [2550          {2551            "type": "compact_20260112",2552            "trigger": {2553              "type": "input_tokens",2554              "value": 1000002555            }2556          }2557        ]2558      }2559    }'2560  ```25612562  ```bash CLI2563  # The CLI handles individual turns; maintain the messages array in the2564  # calling script. See the SDK tabs for the full chat() loop. Single-turn2565  # request shape:2566  ant beta:messages create \2567    --beta compact-2026-01-12 \2568    --transform 'content.#(type=="text").text' \2569    --raw-output <<'YAML'2570  model: claude-opus-52571  max_tokens: 40962572  messages:2573    - role: user2574      content: Help me build a Python web scraper2575  context_management:2576    edits:2577      - type: compact_202601122578        trigger:2579          type: input_tokens2580          value: 1000002581  YAML2582  ```25832584  ```python Python2585  client = anthropic.Anthropic()25862587  messages: list[dict] = []258825892590  def chat(user_message: str) -> str:2591      messages.append({"role": "user", "content": user_message})25922593      response = client.beta.messages.create(2594          betas=["compact-2026-01-12"],2595          model="claude-opus-5",2596          max_tokens=4096,2597          messages=messages,2598          context_management={2599              "edits": [2600                  {2601                      "type": "compact_20260112",2602                      "trigger": {"type": "input_tokens", "value": 100000},2603                  }2604              ]2605          },2606      )26072608      # Append response (compaction blocks are automatically included)2609      messages.append({"role": "assistant", "content": response.content})26102611      # Return the text content2612      return next(block.text for block in response.content if block.type == "text")261326142615  # Run a long conversation2616  print(chat("Help me build a Python web scraper"))2617  print(chat("Add support for JavaScript-rendered pages"))2618  print(chat("Now add rate limiting and error handling"))2619  # Continue calling chat() for as long as the conversation needs2620  ```26212622  ```typescript TypeScript2623  const client = new Anthropic();26242625  const messages: Anthropic.Beta.Messages.BetaMessageParam[] = [];26262627  async function chat(userMessage: string): Promise<string> {2628    messages.push({ role: "user", content: userMessage });26292630    const response = await client.beta.messages.create({2631      betas: ["compact-2026-01-12"],2632      model: "claude-opus-5",2633      max_tokens: 4096,2634      messages,2635      context_management: {2636        edits: [2637          {2638            type: "compact_20260112",2639            trigger: { type: "input_tokens", value: 100000 }2640          }2641        ]2642      }2643    });26442645    // Append response (compaction blocks are automatically included)2646    messages.push({ role: "assistant", content: response.content });26472648    // Return the text content2649    const textBlock = response.content.find((block) => block.type === "text");2650    return textBlock?.text ?? "";2651  }26522653  // Run a long conversation2654  console.log(await chat("Help me build a Python web scraper"));2655  console.log(await chat("Add support for JavaScript-rendered pages"));2656  console.log(await chat("Now add rate limiting and error handling"));2657  // Continue calling chat() for as long as the conversation needs2658  ```26592660  ```csharp C#2661  AnthropicClient client = new();2662  List<BetaMessageParam> messages = new();26632664  Console.WriteLine(await Chat(client, messages, "Help me build a Python web scraper"));2665  Console.WriteLine(await Chat(client, messages, "Add support for JavaScript-rendered pages"));2666  Console.WriteLine(await Chat(client, messages, "Now add rate limiting and error handling"));26672668  static async Task<string> Chat(AnthropicClient client, List<BetaMessageParam> messages, string userMessage)2669  {2670      messages.Add(new() { Role = Role.User, Content = userMessage });26712672      var parameters = new MessageCreateParams2673      {2674          Betas = ["compact-2026-01-12"],2675          Model = "claude-opus-5",2676          MaxTokens = 4096,2677          Messages = messages,2678          ContextManagement = new BetaContextManagementConfig2679          {2680              Edits = [new BetaCompact20260112Edit2681              {2682                  Trigger = new BetaInputTokensTrigger(100000)2683              }]2684          }2685      };26862687      var response = await client.Beta.Messages.Create(parameters);26882689      messages.Add(new()2690      {2691          Role = Role.Assistant,2692          Content = response.Content.Select(block => new BetaContentBlockParam(block.Json)).ToList()2693      });26942695      return response.Content2696          .Select(block => block.Value)2697          .OfType<BetaTextBlock>()2698          .Select(tb => tb.Text)2699          .FirstOrDefault() ?? "";2700  }2701  ```27022703  ```go Go2704  package main27052706  import (2707  	"context"2708  	"fmt"2709  	"log"27102711  	"github.com/anthropics/anthropic-sdk-go"2712  )27132714  var (2715  	client   = anthropic.NewClient()2716  	messages []anthropic.BetaMessageParam2717  )27182719  func chat(userMessage string) string {2720  	messages = append(messages, anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(userMessage)))27212722  	response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{2723  		Model:     anthropic.ModelClaudeOpus5,2724  		MaxTokens: 4096,2725  		Messages:  messages,2726  		ContextManagement: anthropic.BetaContextManagementConfigParam{2727  			Edits: []anthropic.BetaContextManagementConfigEditUnionParam{2728  				{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{2729  					Trigger: anthropic.BetaInputTokensTriggerParam{Value: 100000},2730  				}},2731  			},2732  		},2733  		Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},2734  	})2735  	if err != nil {2736  		log.Fatal(err)2737  	}27382739  	messages = append(messages, response.ToParam())27402741  	for _, block := range response.Content {2742  		if variant, ok := block.AsAny().(anthropic.BetaTextBlock); ok {2743  			return variant.Text2744  		}2745  	}2746  	return ""2747  }27482749  func main() {2750  	fmt.Println(chat("Help me build a Python web scraper"))2751  	fmt.Println(chat("Add support for JavaScript-rendered pages"))2752  	fmt.Println(chat("Now add rate limiting and error handling"))2753  }2754  ```27552756  ```java Java2757  import com.anthropic.models.beta.messages.BetaContextManagementConfig;2758  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;2759  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;2760  // ...2761      private static final AnthropicClient client = AnthropicOkHttpClient.fromEnv();2762      private static final List<BetaMessageParam> messages = new ArrayList<>();27632764      public static void main(String[] args) {2765          System.out.println(chat("Help me build a Python web scraper"));2766          System.out.println(chat("Add support for JavaScript-rendered pages"));2767          System.out.println(chat("Now add rate limiting and error handling"));2768      }27692770      private static String chat(String userMessage) {2771          messages.add(BetaMessageParam.builder()2772              .role(BetaMessageParam.Role.USER)2773              .content(userMessage)2774              .build());27752776          MessageCreateParams params = MessageCreateParams.builder()2777              .addBeta("compact-2026-01-12")2778              .model("claude-opus-5")2779              .maxTokens(4096L)2780              .messages(messages)2781              .contextManagement(BetaContextManagementConfig.builder()2782                  .addEdit(BetaCompact20260112Edit.builder()2783                      .trigger(BetaInputTokensTrigger.builder()2784                          .value(100000L)2785                          .build())2786                      .build())2787                  .build())2788              .build();27892790          BetaMessage response = client.beta().messages().create(params);27912792          // Append response (compaction blocks are automatically included)2793          messages.add(response.toParam());27942795          return response.content().stream()2796              .filter(block -> block.text().isPresent())2797              .map(block -> block.text().get().text())2798              .findFirst()2799              .orElse("");2800      }2801  ```28022803  ```php PHP2804  $client = new Client();2805  $messages = [];28062807  function chat($client, &$messages, $userMessage) {2808      $messages[] = ['role' => 'user', 'content' => $userMessage];28092810      $response = $client->beta->messages->create(2811          maxTokens: 4096,2812          messages: $messages,2813          model: 'claude-opus-5',2814          betas: ['compact-2026-01-12'],2815          contextManagement: [2816              'edits' => [2817                  [2818                      'type' => 'compact_20260112',2819                      'trigger' => ['type' => 'input_tokens', 'value' => 100000]2820                  ]2821              ]2822          ]2823      );28242825      $messages[] = ['role' => 'assistant', 'content' => $response->content];28262827      foreach ($response->content as $block) {2828          if ($block->type === 'text') {2829              return $block->text;2830          }2831      }2832      return '';2833  }28342835  echo chat($client, $messages, "Help me build a Python web scraper") . "\n";2836  echo chat($client, $messages, "Add support for JavaScript-rendered pages") . "\n";2837  echo chat($client, $messages, "Now add rate limiting and error handling") . "\n";2838  ```28392840  ```ruby Ruby2841  client = Anthropic::Client.new2842  messages = []28432844  def chat(client, messages, user_message)2845    messages << { role: "user", content: user_message }28462847    response = client.beta.messages.create(2848      betas: ["compact-2026-01-12"],2849      model: "claude-opus-5",2850      max_tokens: 4096,2851      messages: messages,2852      context_management: {2853        edits: [2854          {2855            type: "compact_20260112",2856            trigger: { type: "input_tokens", value: 100000 }2857          }2858        ]2859      }2860    )28612862    messages << { role: "assistant", content: response.content }28632864    response.content.find { |block| block.type == :text }&.text || ""2865  end28662867  puts chat(client, messages, "Help me build a Python web scraper")2868  puts chat(client, messages, "Add support for JavaScript-rendered pages")2869  puts chat(client, messages, "Now add rate limiting and error handling")2870  ```2871</CodeGroup>28722873On Claude Fable 5.1, remove the `thinking` and `redacted_thinking` blocks from any assistant turn you re-insert after the compaction block, or send `thinking.block_binding.prefix_mismatch_behavior: "drop_block"` with the `thinking-binding-controls-2026-08-01` [beta header](https://platform.claude.com/docs/en/api/beta-headers). Those blocks were produced when the full history was present, so they no longer pass the [conversation check](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation). Where the check is enforced, the continuation request is rejected with a 400 error. The preserved text and tool blocks can stay as they are. Letting the API summarize everything, without re-inserting earlier turns, avoids this.28742875Here's an example that uses `pause_after_compaction` to preserve the prior exchange and the current user message (three messages total) verbatim instead of summarizing them:28762877<CodeGroup>2878  ```bash cURL2879  # curl sends individual requests; maintain the messages array in the2880  # calling script. See the SDK tabs for the full chat() loop with2881  # pause-and-preserve handling. Single-turn request shape:2882  curl https://api.anthropic.com/v1/messages \2883    -H "x-api-key: $ANTHROPIC_API_KEY" \2884    -H "anthropic-version: 2023-06-01" \2885    -H "anthropic-beta: compact-2026-01-12" \2886    -H "content-type: application/json" \2887    -d '{2888      "model": "claude-opus-5",2889      "max_tokens": 4096,2890      "messages": [2891        {2892          "role": "user",2893          "content": "Help me build a Python web scraper"2894        }2895      ],2896      "context_management": {2897        "edits": [2898          {2899            "type": "compact_20260112",2900            "trigger": {2901              "type": "input_tokens",2902              "value": 1000002903            },2904            "pause_after_compaction": true2905          }2906        ]2907      }2908    }'2909  ```29102911  ```bash CLI2912  # The CLI handles individual turns; maintain the messages array in the2913  # calling script. See the SDK tabs for the full chat() loop with2914  # pause-and-preserve handling. Single-turn request shape:2915  ant beta:messages create \2916    --beta compact-2026-01-12 \2917    --transform 'content.#(type=="text").text' \2918    --raw-output <<'YAML'2919  model: claude-opus-52920  max_tokens: 40962921  messages:2922    - role: user2923      content: Help me build a Python web scraper2924  context_management:2925    edits:2926      - type: compact_202601122927        trigger:2928          type: input_tokens2929          value: 1000002930        pause_after_compaction: true2931  YAML2932  ```29332934  ```python Python2935  from typing import Any29362937  client = anthropic.Anthropic()29382939  messages: list[dict[str, Any]] = []294029412942  def chat(user_message: str) -> str:2943      messages.append({"role": "user", "content": user_message})29442945      response = client.beta.messages.create(2946          betas=["compact-2026-01-12"],2947          model="claude-opus-5",2948          max_tokens=4096,2949          messages=messages,2950          context_management={2951              "edits": [2952                  {2953                      "type": "compact_20260112",2954                      "trigger": {"type": "input_tokens", "value": 100000},2955                      "pause_after_compaction": True,2956                  }2957              ]2958          },2959      )29602961      # Check if compaction occurred and paused2962      if response.stop_reason == "compaction":2963          # Get the compaction block from the response2964          compaction_block = response.content[0]29652966          # Preserve the prior exchange + current user message (3 messages)2967          # by including them after the compaction block2968          preserved_messages = messages[-3:] if len(messages) >= 3 else messages29692970          # Build new message list: compaction + preserved messages2971          new_assistant_content = [compaction_block]2972          messages_after_compaction = [2973              {"role": "assistant", "content": new_assistant_content}2974          ] + preserved_messages29752976          # Continue the request with the compacted context + preserved messages2977          response = client.beta.messages.create(2978              betas=["compact-2026-01-12"],2979              model="claude-opus-5",2980              max_tokens=4096,2981              messages=messages_after_compaction,2982              context_management={"edits": [{"type": "compact_20260112"}]},2983          )29842985          # Update the message list to reflect the compaction2986          messages.clear()2987          messages.extend(messages_after_compaction)29882989      # Append the final response2990      messages.append({"role": "assistant", "content": response.content})29912992      # Return the text content2993      return next(block.text for block in response.content if block.type == "text")299429952996  # Run a long conversation2997  print(chat("Help me build a Python web scraper"))2998  print(chat("Add support for JavaScript-rendered pages"))2999  print(chat("Now add rate limiting and error handling"))3000  # Continue calling chat() for as long as the conversation needs3001  ```30023003  ```typescript TypeScript3004  const client = new Anthropic();30053006  let messages: Anthropic.Beta.Messages.BetaMessageParam[] = [];30073008  async function chat(userMessage: string): Promise<string> {3009    messages.push({ role: "user", content: userMessage });30103011    let response = await client.beta.messages.create({3012      betas: ["compact-2026-01-12"],3013      model: "claude-opus-5",3014      max_tokens: 4096,3015      messages,3016      context_management: {3017        edits: [3018          {3019            type: "compact_20260112",3020            trigger: { type: "input_tokens", value: 100000 },3021            pause_after_compaction: true3022          }3023        ]3024      }3025    });30263027    // Check if compaction occurred and paused3028    if (response.stop_reason === "compaction") {3029      // Get the compaction block from the response3030      const compactionBlock = response.content[0];30313032      // Preserve the prior exchange + current user message (3 messages)3033      // by including them after the compaction block3034      const preservedMessages = messages.length >= 3 ? messages.slice(-3) : [...messages];30353036      // Build new message list: compaction + preserved messages3037      const messagesAfterCompaction: Anthropic.Beta.Messages.BetaMessageParam[] = [3038        { role: "assistant", content: [compactionBlock] },3039        ...preservedMessages3040      ];30413042      // Continue the request with the compacted context + preserved messages3043      response = await client.beta.messages.create({3044        betas: ["compact-2026-01-12"],3045        model: "claude-opus-5",3046        max_tokens: 4096,3047        messages: messagesAfterCompaction,3048        context_management: {3049          edits: [{ type: "compact_20260112" }]3050        }3051      });30523053      // Update the message list to reflect the compaction3054      messages = messagesAfterCompaction;3055    }30563057    // Append the final response3058    messages.push({ role: "assistant", content: response.content });30593060    // Return the text content3061    const textBlock = response.content.find((block) => block.type === "text");3062    return textBlock?.text ?? "";3063  }30643065  // Run a long conversation3066  console.log(await chat("Help me build a Python web scraper"));3067  console.log(await chat("Add support for JavaScript-rendered pages"));3068  console.log(await chat("Now add rate limiting and error handling"));3069  // Continue calling chat() for as long as the conversation needs3070  ```30713072  ```csharp C#3073  AnthropicClient client = new();3074  List<BetaMessageParam> messages = new();30753076  Console.WriteLine(await Chat("Help me build a Python web scraper"));3077  Console.WriteLine(await Chat("Add support for JavaScript-rendered pages"));3078  Console.WriteLine(await Chat("Now add rate limiting and error handling"));30793080  async Task<string> Chat(string userMessage)3081  {3082      messages.Add(new() { Role = Role.User, Content = userMessage });30833084      var response = await client.Beta.Messages.Create(new()3085      {3086          Betas = ["compact-2026-01-12"],3087          Model = "claude-opus-5",3088          MaxTokens = 4096,3089          Messages = messages,3090          ContextManagement = new BetaContextManagementConfig3091          {3092              Edits = [new BetaCompact20260112Edit3093              {3094                  Trigger = new BetaInputTokensTrigger(100000),3095                  PauseAfterCompaction = true3096              }]3097          }3098      });30993100      if (response.StopReason == BetaStopReason.Compaction)3101      {3102          if (!response.Content[0].TryPickCompaction(out _))3103              throw new InvalidOperationException("Expected compaction block");31043105          var preserved = messages.Count >= 33106              ? messages.Skip(messages.Count - 3).ToList()3107              : new List<BetaMessageParam>(messages);31083109          var messagesAfterCompaction = new List<BetaMessageParam>3110          {3111              new()3112              {3113                  Role = Role.Assistant,3114                  Content = new List<BetaContentBlockParam> { new BetaContentBlockParam(response.Content[0].Json) }3115              }3116          };3117          messagesAfterCompaction.AddRange(preserved);31183119          response = await client.Beta.Messages.Create(new()3120          {3121              Betas = ["compact-2026-01-12"],3122              Model = "claude-opus-5",3123              MaxTokens = 4096,3124              Messages = messagesAfterCompaction,3125              ContextManagement = new BetaContextManagementConfig3126              {3127                  Edits = [new BetaCompact20260112Edit()]3128              }3129          });31303131          messages = messagesAfterCompaction;3132      }31333134      messages.Add(new()3135      {3136          Role = Role.Assistant,3137          Content = response.Content.Select(block => new BetaContentBlockParam(block.Json)).ToList()3138      });31393140      return response.Content3141          .Select(block => block.Value)3142          .OfType<BetaTextBlock>()3143          .Select(tb => tb.Text)3144          .FirstOrDefault() ?? "";3145  }3146  ```31473148  ```go Go3149  package main31503151  import (3152  	"context"3153  	"fmt"3154  	"log"31553156  	"github.com/anthropics/anthropic-sdk-go"3157  )31583159  var (3160  	client   = anthropic.NewClient()3161  	messages []anthropic.BetaMessageParam3162  )31633164  func chat(userMessage string) string {3165  	messages = append(messages, anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(userMessage)))31663167  	compactEdit := anthropic.BetaContextManagementConfigParam{3168  		Edits: []anthropic.BetaContextManagementConfigEditUnionParam{3169  			{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{3170  				Trigger:              anthropic.BetaInputTokensTriggerParam{Value: 100000},3171  				PauseAfterCompaction: anthropic.Bool(true),3172  			}},3173  		},3174  	}31753176  	response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{3177  		Model:             anthropic.ModelClaudeOpus5,3178  		MaxTokens:         4096,3179  		Messages:          messages,3180  		ContextManagement: compactEdit,3181  		Betas:             []anthropic.AnthropicBeta{"compact-2026-01-12"},3182  	})3183  	if err != nil {3184  		log.Fatal(err)3185  	}31863187  	if response.StopReason == "compaction" {3188  		compactionParam := response.Content[0].ToParam()31893190  		var preserved []anthropic.BetaMessageParam3191  		if len(messages) >= 3 {3192  			preserved = messages[len(messages)-3:]3193  		} else {3194  			preserved = messages3195  		}31963197  		messagesAfterCompaction := []anthropic.BetaMessageParam{3198  			{Role: anthropic.BetaMessageParamRoleAssistant, Content: []anthropic.BetaContentBlockParamUnion{compactionParam}},3199  		}3200  		messagesAfterCompaction = append(messagesAfterCompaction, preserved...)32013202  		response, err = client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{3203  			Model:     anthropic.ModelClaudeOpus5,3204  			MaxTokens: 4096,3205  			Messages:  messagesAfterCompaction,3206  			ContextManagement: anthropic.BetaContextManagementConfigParam{3207  				Edits: []anthropic.BetaContextManagementConfigEditUnionParam{3208  					{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},3209  				},3210  			},3211  			Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},3212  		})3213  		if err != nil {3214  			log.Fatal(err)3215  		}32163217  		messages = messagesAfterCompaction3218  	}32193220  	messages = append(messages, response.ToParam())32213222  	for _, block := range response.Content {3223  		if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {3224  			return textBlock.Text3225  		}3226  	}3227  	return ""3228  }32293230  func main() {3231  	fmt.Println(chat("Help me build a Python web scraper"))3232  	fmt.Println(chat("Add support for JavaScript-rendered pages"))3233  	fmt.Println(chat("Now add rate limiting and error handling"))3234  }3235  ```32363237  ```java Java3238  import com.anthropic.models.beta.messages.BetaContextManagementConfig;3239  import com.anthropic.models.beta.messages.BetaCompact20260112Edit;3240  import com.anthropic.models.beta.messages.BetaInputTokensTrigger;3241  import com.anthropic.models.beta.messages.BetaStopReason;3242  // ...3243      private static final AnthropicClient client = AnthropicOkHttpClient.fromEnv();3244      private static final List<BetaMessageParam> messages = new ArrayList<>();32453246      public static String chat(String userMessage) {3247          messages.add(BetaMessageParam.builder()3248              .role(BetaMessageParam.Role.USER)3249              .content(userMessage)3250              .build());32513252          MessageCreateParams params = MessageCreateParams.builder()3253              .addBeta("compact-2026-01-12")3254              .model("claude-opus-5")3255              .maxTokens(4096L)3256              .messages(messages)3257              .contextManagement(BetaContextManagementConfig.builder()3258                  .addEdit(BetaCompact20260112Edit.builder()3259                      .trigger(BetaInputTokensTrigger.builder()3260                          .value(100000L)3261                          .build())3262                      .pauseAfterCompaction(true)3263                      .build())3264                  .build())3265              .build();32663267          BetaMessage response = client.beta().messages().create(params);32683269          // Check if compaction occurred and paused3270          if (response.stopReason().isPresent()3271                  && response.stopReason().get().equals(BetaStopReason.COMPACTION)) {3272              // Preserve the prior exchange + current user message (3 messages)3273              List<BetaMessageParam> preservedMessages = messages.size() >= 33274                  ? new ArrayList<>(messages.subList(messages.size() - 3, messages.size()))3275                  : new ArrayList<>(messages);32763277              // Build new message list: compaction + preserved messages3278              List<BetaMessageParam> messagesAfterCompaction = new ArrayList<>();3279              messagesAfterCompaction.add(response.toParam());3280              messagesAfterCompaction.addAll(preservedMessages);32813282              // Continue the request with the compacted context + preserved messages3283              MessageCreateParams continueParams = MessageCreateParams.builder()3284                  .addBeta("compact-2026-01-12")3285                  .model("claude-opus-5")3286                  .maxTokens(4096L)3287                  .messages(messagesAfterCompaction)3288                  .contextManagement(BetaContextManagementConfig.builder()3289                      .addEdit(BetaCompact20260112Edit.builder().build())3290                      .build())3291                  .build();32923293              response = client.beta().messages().create(continueParams);32943295              // Update the message list to reflect the compaction3296              messages.clear();3297              messages.addAll(messagesAfterCompaction);3298          }32993300          // Append the final response3301          messages.add(response.toParam());33023303          return response.content().stream()3304              .filter(block -> block.text().isPresent())3305              .map(block -> block.text().get().text())3306              .findFirst()3307              .orElse("");3308      }33093310      public static void main(String[] args) {3311          System.out.println(chat("Help me build a Python web scraper"));3312          System.out.println(chat("Add support for JavaScript-rendered pages"));3313          System.out.println(chat("Now add rate limiting and error handling"));3314      }3315  ```33163317  ```php PHP3318  $client = new Client();3319  $messages = [];33203321  function chat($client, &$messages, $userMessage) {3322      $messages[] = ['role' => 'user', 'content' => $userMessage];33233324      $response = $client->beta->messages->create(3325          maxTokens: 4096,3326          messages: $messages,3327          model: 'claude-opus-5',3328          betas: ['compact-2026-01-12'],3329          contextManagement: [3330              'edits' => [3331                  [3332                      'type' => 'compact_20260112',3333                      'trigger' => ['type' => 'input_tokens', 'value' => 100000],3334                      'pause_after_compaction' => true3335                  ]3336              ]3337          ]3338      );33393340      if ($response->stopReason === 'compaction') {3341          $compactionBlock = $response->content[0];33423343          $preserved = count($messages) >= 33344              ? array_slice($messages, -3)3345              : $messages;33463347          $messagesAfterCompaction = array_merge(3348              [['role' => 'assistant', 'content' => [$compactionBlock]]],3349              $preserved3350          );33513352          $response = $client->beta->messages->create(3353              maxTokens: 4096,3354              messages: $messagesAfterCompaction,3355              model: 'claude-opus-5',3356              betas: ['compact-2026-01-12'],3357              contextManagement: [3358                  'edits' => [['type' => 'compact_20260112']]3359              ]3360          );33613362          $messages = $messagesAfterCompaction;3363      }33643365      $messages[] = ['role' => 'assistant', 'content' => $response->content];33663367      foreach ($response->content as $block) {3368          if ($block->type === 'text') {3369              return $block->text;3370          }3371      }3372      return '';3373  }33743375  echo chat($client, $messages, "Help me build a Python web scraper") . "\n";3376  echo chat($client, $messages, "Add support for JavaScript-rendered pages") . "\n";3377  echo chat($client, $messages, "Now add rate limiting and error handling") . "\n";3378  ```33793380  ```ruby Ruby3381  client = Anthropic::Client.new3382  messages = []33833384  def chat(client, messages, user_message)3385    messages << { role: "user", content: user_message }33863387    response = client.beta.messages.create(3388      betas: ["compact-2026-01-12"],3389      model: "claude-opus-5",3390      max_tokens: 4096,3391      messages: messages,3392      context_management: {3393        edits: [3394          {3395            type: "compact_20260112",3396            trigger: { type: "input_tokens", value: 100000 },3397            pause_after_compaction: true3398          }3399        ]3400      }3401    )34023403    if response.stop_reason == :compaction3404      compaction_block = response.content[0]34053406      preserved = messages.length >= 3 ? messages[-3..-1] : messages.dup34073408      messages_after_compaction = [3409        { role: "assistant", content: [compaction_block] }3410      ] + preserved34113412      response = client.beta.messages.create(3413        betas: ["compact-2026-01-12"],3414        model: "claude-opus-5",3415        max_tokens: 4096,3416        messages: messages_after_compaction,3417        context_management: {3418          edits: [{ type: "compact_20260112" }]3419        }3420      )34213422      messages.clear3423      messages.concat(messages_after_compaction)3424    end34253426    messages << { role: "assistant", content: response.content }34273428    response.content.find { |block| block.type == :text }&.text || ""3429  end34303431  puts chat(client, messages, "Help me build a Python web scraper")3432  puts chat(client, messages, "Add support for JavaScript-rendered pages")3433  puts chat(client, messages, "Now add rate limiting and error handling")3434  ```3435</CodeGroup>34363437## Current limitations34383439* **Same model for summarization:** The model specified in your request is used for summarization. There is no option to use a different (for example, cheaper) model for the summary.34403441* **Compaction might fail when tools are defined:** When your request includes `tools`, the model occasionally calls a tool during the internal summarization step instead of writing a summary. When this occurs, the response contains a `compaction` block with `content: null`. To prevent this, set [`instructions`](https://platform.claude.com/docs/en/build-with-claude/compaction#custom-summarization-instructions) to a prompt that explicitly tells the model not to call tools, for example:34423443  ```text wrap3444  Summarize the transcript inside <summary></summary> tags. Include relevant information in the summary for continuing the task in the next context window. Do not call any tools while writing this summary; respond with text only.3445  ```34463447## Compact on demand with the `compaction` parameter34483449The `compact-2026-09-04` beta adds a second way to compact. Threshold compaction summarizes partway through a request once the threshold you set is reached. With this beta, you instead send the top-level `compaction` parameter on a request of your choosing. The response contains a single signed `compaction` block and no reply. From then on, send that block first in `messages`, in place of the messages it summarizes, followed by any turns taken since. Claude sees the summary where those messages were. Everything after the summary reaches Claude unchanged. A threshold compaction block follows the messages it summarizes, but a signed block replaces them. Leaving the summarized messages in front of a signed block is a 400 error.34503451Compacting this way gives you three things. First, you decide when to compact. Second, the summarization request can run in the background while the conversation continues on its full history, and you swap the block in when it arrives. This is often called async or background compaction. Third, you can keep recent turns word for word after the summary, which is often called keep-tail compaction. Models with [preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking) check earlier thinking blocks against the conversation. On those models, the thinking in turns that follow the summary, from either pattern, can stay valid after the swap, under the conditions in [Continue from the summary](https://platform.claude.com/docs/en/build-with-claude/compaction#continue-from-the-summary). That lets a long-running agent keep its train of thought. Use threshold compaction when you want the API to manage context inside ordinary requests. Use the `compaction` parameter when your application needs to control when compaction happens, can't pause while a summary is written, or must keep recent turns and their thinking after the summary.34523453Send the `compact-2026-09-04` beta header on the request that asks for the summary and on every later request that carries the signed block. On-demand compaction is available on the Claude API but not on Amazon Bedrock or Google Cloud. It works on Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, Claude Mythos Preview, Claude Opus 5, Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, Claude Sonnet 5, and Claude Sonnet 4.6. You can also call the [Models API](https://platform.claude.com/docs/en/api/beta/models/list) with the beta header and read each model's `capabilities.compaction`. You can't combine `compaction` with `context_management` on one request.34543455### Request a summary34563457Send the conversation as it stands with `"compaction": {"type": "summarize"}`. The API summarizes every message in the request once, generates no reply after it, and returns the block alone with `stop_reason` `"compaction"`. Send the same `system` prompt and `tools` that you use for the rest of the conversation. The summarizer reads them, and on models with preserved thinking, the turns you keep stay valid only if they match. The conversation in this example has no `system` prompt or tools, so the request sends neither:34583459<CodeGroup>3460  ```bash cURL3461  # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3462  curl https://api.anthropic.com/v1/messages \3463    -H "x-api-key: $ANTHROPIC_API_KEY" \3464    -H "anthropic-version: 2023-06-01" \3465    -H "anthropic-beta: compact-2026-09-04" \3466    -H "content-type: application/json" \3467    -d '{3468      "model": "claude-opus-5",3469      "max_tokens": 4096,3470      "messages": [3471        {"role": "user", "content": "I am building a recipe app. Help me name the main entities in the data model."},3472        {"role": "assistant", "content": "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe."},3473        {"role": "user", "content": "Good. Now suggest field names for Recipe."}3474      ],3475      "compaction": {"type": "summarize"}3476    }'3477  ```34783479  <MultiFileExample language="cli" label="CLI">3480    ```bash CLI3481    ant beta:messages create --beta compact-2026-09-04 < request.yaml3482    ```34833484    <File filename="request.yaml">3485      ```yaml3486      model: claude-opus-53487      # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3488      max_tokens: 40963489      messages:3490        - role: user3491          content: I am building a recipe app. Help me name the main entities in the data model.3492        - role: assistant3493          content: Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.3494        - role: user3495          content: Good. Now suggest field names for Recipe.3496      compaction:3497        type: summarize3498      ```3499    </File>3500  </MultiFileExample>35013502  ```python Python3503  from anthropic.types.beta import BetaMessageParam35043505  client = anthropic.Anthropic()35063507  history: list[BetaMessageParam] = [3508      {3509          "role": "user",3510          "content": "I am building a recipe app. Help me name the main entities in the data model.",3511      },3512      {3513          "role": "assistant",3514          "content": "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.",3515      },3516      {"role": "user", "content": "Good. Now suggest field names for Recipe."},3517  ]35183519  response = client.beta.messages.create(3520      model="claude-opus-5",3521      # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3522      max_tokens=4096,3523      betas=["compact-2026-09-04"],3524      messages=history,3525      compaction={"type": "summarize"},3526  )3527  print(f"Stop reason: {response.stop_reason}")3528  ```35293530  ```typescript TypeScript3531  const client = new Anthropic();35323533  const history: Anthropic.Beta.Messages.BetaMessageParam[] = [3534    {3535      role: "user",3536      content: "I am building a recipe app. Help me name the main entities in the data model."3537    },3538    {3539      role: "assistant",3540      content:3541        "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe."3542    },3543    { role: "user", content: "Good. Now suggest field names for Recipe." }3544  ];35453546  const response = await client.beta.messages.create({3547    model: "claude-opus-5",3548    // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3549    max_tokens: 4096,3550    betas: ["compact-2026-09-04"],3551    messages: history,3552    compaction: { type: "summarize" }3553  });3554  console.log(`Stop reason: ${response.stop_reason}`);3555  ```35563557  ```csharp C#3558  using Anthropic.Models.Beta;3559  using Anthropic.Models.Beta.Messages;3560  using Model = Anthropic.Models.Messages.Model;35613562  AnthropicClient client = new();35633564  List<BetaMessageParam> history =3565  [3566      new()3567      {3568          Role = Role.User,3569          Content = "I am building a recipe app. Help me name the main entities in the data model.",3570      },3571      new()3572      {3573          Role = Role.Assistant,3574          Content = "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.",3575      },3576      new() { Role = Role.User, Content = "Good. Now suggest field names for Recipe." },3577  ];35783579  var response = await client.Beta.Messages.Create(new MessageCreateParams3580  {3581      Model = Model.ClaudeOpus5,3582      // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3583      MaxTokens = 4096,3584      Betas = [AnthropicBeta.Compact2026_09_04],3585      Messages = history,3586      Compaction = new BetaCompactionConfig(), // type defaults to "summarize"3587  });35883589  Console.WriteLine($"Stop reason: {response.StopReason?.Raw()}");3590  ```35913592  ```go Go3593  client := anthropic.NewClient()35943595  history := []anthropic.BetaMessageParam{3596  	anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("I am building a recipe app. Help me name the main entities in the data model.")),3597  	{3598  		Role:    anthropic.BetaMessageParamRoleAssistant,3599  		Content: []anthropic.BetaContentBlockParamUnion{anthropic.NewBetaTextBlock("Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.")},3600  	},3601  	anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Good. Now suggest field names for Recipe.")),3602  }36033604  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{3605  	Model: anthropic.ModelClaudeOpus5,3606  	// max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3607  	MaxTokens: 4096,3608  	Betas:     []anthropic.AnthropicBeta{anthropic.AnthropicBetaCompact2026_09_04},3609  	Messages:  history,3610  	Compaction: anthropic.BetaCompactionConfigUnionParam{3611  		OfSummarize: &anthropic.BetaSummarizeCompactionParam{},3612  	},3613  })3614  if err != nil {3615  	log.Fatal(err)3616  }3617  fmt.Println("Stop reason:", response.StopReason)3618  ```36193620  ```java Java3621  import com.anthropic.models.beta.AnthropicBeta;3622  import com.anthropic.models.beta.messages.BetaCompactionConfig;3623  import com.anthropic.models.beta.messages.MessageCreateParams;36243625  void main() {3626      var client = AnthropicOkHttpClient.fromEnv();36273628      var params = MessageCreateParams.builder()3629          .model(Model.CLAUDE_OPUS_5)3630          // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3631          .maxTokens(4096)3632          .addBeta(AnthropicBeta.COMPACT_2026_09_04)3633          .addUserMessage("I am building a recipe app. Help me name the main entities in the data model.")3634          .addAssistantMessage("Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.")3635          .addUserMessage("Good. Now suggest field names for Recipe.")3636          .compaction(BetaCompactionConfig.builder().build()) // type defaults to "summarize"3637          .build();36383639      var response = client.beta().messages().create(params);3640      response.stopReason().ifPresent(reason -> IO.println("Stop reason: " + reason));3641  }3642  ```36433644  ```php PHP3645  use Anthropic\Beta\AnthropicBeta;3646  use Anthropic\Beta\Messages\BetaCompactionConfig;3647  use Anthropic\Beta\Messages\BetaMessageParam;3648  use Anthropic\Beta\Messages\BetaMessageParam\Role;36493650  $client = new Client();36513652  $history = [3653      BetaMessageParam::with(3654          role: Role::USER,3655          content: 'I am building a recipe app. Help me name the main entities in the data model.',3656      ),3657      BetaMessageParam::with(3658          role: Role::ASSISTANT,3659          content: 'Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.',3660      ),3661      BetaMessageParam::with(role: Role::USER, content: 'Good. Now suggest field names for Recipe.'),3662  ];36633664  $response = $client->beta->messages->create(3665      model: Model::CLAUDE_OPUS_5,3666      // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3667      maxTokens: 4096,3668      betas: [AnthropicBeta::COMPACT_2026_09_04],3669      messages: $history,3670      compaction: BetaCompactionConfig::with(), // type defaults to 'summarize'3671  );36723673  echo "Stop reason: {$response->stopReason}", PHP_EOL;3674  ```36753676  ```ruby Ruby3677  client = Anthropic::Client.new36783679  history = [3680    {3681      role: "user",3682      content: "I am building a recipe app. Help me name the main entities in the data model."3683    },3684    {3685      role: "assistant",3686      content: "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe."3687    },3688    { role: "user", content: "Good. Now suggest field names for Recipe." }3689  ]36903691  response = client.beta.messages.create(3692    model: Anthropic::Model::CLAUDE_OPUS_5,3693    # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.3694    max_tokens: 4096,3695    betas: [Anthropic::AnthropicBeta::COMPACT_2026_09_04],3696    messages: history,3697    compaction: { type: "summarize" }3698  )3699  puts "Stop reason: #{response.stop_reason}"3700  ```3701</CodeGroup>37023703```json Response3704{3705  "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",3706  "type": "message",3707  "role": "assistant",3708  "model": "claude-opus-5",3709  "content": [3710    {3711      "type": "compaction",3712      "content": "Summary of the conversation: the user is designing the data model for a recipe app. The entities agreed so far are Recipe, Ingredient, Step, and RecipeIngredient, which holds the quantity and unit. The user then asked for field names for Recipe.",3713      "signature": "EuYBCkQY..."3714    }3715  ],3716  "stop_reason": "compaction",3717  "usage": {3718    "input_tokens": 0,3719    "output_tokens": 0,3720    "iterations": [{ "type": "compaction", "input_tokens": 144, "output_tokens": 276 }]3721  }3722}3723```37243725The summarization call uses the request's model, `system`, `tools`, thinking settings, and `max_tokens`. The summarizer reads the tool definitions but never runs a tool, and the response carries no thinking. `max_tokens` caps the whole call, including any thinking the model does before it writes the summary, so allow several thousand tokens. It is billed and rate-limited like any other request, and `usage.iterations` reports it as the `compaction` entry. The top-level `input_tokens` and `output_tokens` are zero because no reply was generated.37263727If the last `assistant` turn ends in a tool call with no result yet, the API rejects the request. Send that turn's tool results first. Also leave out `stop_sequences`, structured-output `output_config.format`, and a `tool_choice` of type `any` or `tool`. They would do nothing on a summarization call, and the API rejects them. The conversation must still fit the model's context window, so compact before you outgrow it, not after.37283729When you stream the response, the block arrives whole. You get one `content_block_start` event carrying the complete block, then `content_block_stop`, with no `content_block_delta` events. `ping` events can arrive before or between them.37303731### Continue from the summary37323733In your history, replace the messages you sent with the returned assistant message. Keep the `compaction` block exactly as the API returned it, including its `signature`. Send it first on every later request, with the beta header:37343735```json3736{3737  "model": "claude-opus-5",3738  "max_tokens": 2048,3739  "messages": [3740    {3741      "role": "assistant",3742      "content": [3743        {3744          "type": "compaction",3745          "content": "Summary of the conversation: the user is designing the data model for a recipe app. The entities agreed so far are Recipe, Ingredient, Step, and RecipeIngredient, which holds the quantity and unit. The user then asked for field names for Recipe.",3746          "signature": "EuYBCkQY..."3747        }3748      ]3749    },3750    {3751      "role": "assistant",3752      "content": "For Recipe, use title, description, servings, prep_minutes, and cook_minutes. Add created_at and updated_at timestamps."3753    },3754    { "role": "user", "content": "Now do the same for Ingredient." }3755  ]3756}3757```37583759Here the second `assistant` message is the reply to the last summarized `user` turn. It arrived while the summary was being written, so it was not among the messages summarized. Two `assistant` messages in a row are fine here, because the block still comes first.37603761The API puts the summary where the block stands and passes every later message to Claude unchanged. Follow these rules:37623763* Put the block first in `messages`, either as an `assistant` message of its own or as the first content block of the first message, whether that is a `user` or `assistant` message.3764* Remove the summarized messages. If any remain in front of the block, the request returns a 400 error (`compaction_block_misplaced`). If any remain after it, the API doesn't reject the request for that reason and sends them to the model again.3765* Send exactly one `compaction` block per request, on every later request. A request without the block reaches Claude without the summary.37663767To keep a tail of recent turns word for word, leave those turns out of the compaction request. The API summarizes every message it is sent, so send only the older turns, then put the block in front of the turns you kept.37683769If the conversation took more turns while a background summary request ran, drop exactly the messages you sent in the compaction request from the front of your history. Put the returned message in their place, and keep everything appended since:37703771```python3772# sent_count = len(messages sent in the compaction request)3773# response   = that request's result, arriving while the agent kept working3774if response.stop_reason == "compaction":3775    compaction_message = {"role": "assistant", "content": response.content}3776    history = [compaction_message] + history[sent_count:]3777# Otherwise keep the full history and try again later (see "When no summary comes back").3778```37793780Don't edit your history between sending the compaction request and making the swap, and make the swap on the first request after the block arrives. That way, thinking produced while the summary was being written stays valid.37813782On models with preserved thinking, the thinking blocks in the kept turns stay valid as long as both of these conditions hold:37833784* The kept turns directly followed the summarized messages.3785* The `system` parameter and the `tools` not marked `defer_loading: true` are unchanged from the compaction request.37863787The first condition also rules out a first kept message that the API would merge into the last summarized message: one with the same role as the last summarized message, or a `role: "system"` message. The simplest way to meet it is to compact exactly the `messages` of a request you already made. To change `system` or `tools` without invalidating any kept thinking, compact the whole conversation first, so no turns are kept. Then change them on the next request.37883789A later request can use a different model, `system`, or `tools` than the compaction request, and the API still accepts the block. Such a change can invalidate the thinking in the kept turns, but it has no other effect.37903791To compact a conversation that already starts with a block, send `compaction` again. The new block summarizes the old summary and everything after it. From then on, send only the newest block.37923793### Write your own summarization prompt37943795Without `instructions`, the API uses its own summarization prompt. A non-blank `instructions` string (up to 16,384 characters) replaces that prompt entirely, as it does for threshold compaction (see [Custom summarization instructions](https://platform.claude.com/docs/en/build-with-claude/compaction#custom-summarization-instructions)). For example:37963797```json3798{3799  "compaction": {3800    "type": "summarize",3801    "instructions": "Summarize this recipe app design conversation. Preserve every entity and field name agreed so far, and the user's latest open request. Do not call tools; respond with the summary text only."3802  }3803}3804```38053806The summarizer reads the whole conversation, earlier thinking included, with or without `instructions`. That differs from threshold compaction on Claude Fable 5.1 and Claude Mythos 5.1, where custom `instructions` leave earlier thinking out. In your `instructions`, say what the summary must retain and tell the model not to call tools. The summarization call runs under the same safeguards as any other request.38073808### When no summary comes back38093810A summary is produced only when the summarization call ends normally with text and no tool call. Otherwise, the response is still a 200 with empty `content`. The call is still billed and reported in `usage.iterations`, with zero usage when no call could be made. The `stop_reason` is the one the summarization call ended with:38113812* `"max_tokens"`: the summary was cut off.3813* `"model_context_window_exceeded"`: there was no room for the summarization prompt.3814* `"refusal"`: the request was declined. It is subject to the same safeguards as your other requests, and [`stop_details`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#refusal) identifies the policy category behind it.3815* `"tool_use"`: the model called a tool instead of writing the summary.3816* `"end_turn"`: the call returned no text.38173818Resend with a larger `max_tokens` after `"max_tokens"`, with shorter `instructions` or fewer messages after `"model_context_window_exceeded"`, or with `instructions` that tell the model not to call tools after `"tool_use"`. You can also continue without a summary.38193820A transient server problem while producing a block, or while reading one you sent back, returns a retryable 529 `overloaded_error` with `error.details.error_code` set to `compaction_unavailable`. Retry the request. Other rejections specific to this beta are 400 errors, and most have a message that says what to remove or resend. The exception is a request that leaves out the beta header: it fails with a generic validation error, such as `compaction: Extra inputs are not permitted`, that doesn't mention the header. Some also carry an `error.details.error_code` that starts with `compaction_`, mostly the errors about the block itself: an altered, misplaced, or duplicated block, or a request with nothing left to summarize. Parameter errors, such as a field that can't be combined with `compaction`, carry the message only.38213822### How it fits with the rest of the API38233824* **Threshold compaction and context editing.** You can't send `compaction` and `context_management` on the same request. Threshold compaction (`compact_20260112`) can't run on a request that carries a signed block.3825* **Prompt caching.** `cache_control` on the block places a breakpoint after the summary.3826* **Mid-conversation system messages and tool changes.** `role: "system"` messages inside the summarized range are summarized. What they declared stops applying once the block replaces them. If an instruction or a [tool change](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes) still matters, state it again in a `role: "system"` message. Send that message right after your next new `user` turn, which comes after the kept turns, and leave it in your history from then on. Don't put it between the block and the kept turns, because that breaks the kept turns' thinking.3827* **Task budgets.** Don't send the `remaining` value of a [task budget](https://platform.claude.com/docs/en/build-with-claude/task-budgets) (`output_config.task_budget.remaining`) with `compaction` or on requests that carry the block. Doing so returns a 400 error.3828* **Token counting.** The [token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) endpoint ignores the `compaction` parameter.3829* **Content the summary can't carry.** Images, documents, `container_upload` blocks, and fetched URLs inside the summarized messages are gone once the block replaces them. Restate or re-upload anything a later turn still needs.38303831## Next steps38323833<CardGroup cols={3}>3834  <Card title="Context editing" icon="edit" href="https://platform.claude.com/docs/en/build-with-claude/context-editing">3835    Automatically manage conversation context as it grows with context editing.3836  </Card>38373838  <Card title="Context windows" icon="arrows-left-right" href="https://platform.claude.com/docs/en/build-with-claude/context-windows">3839    Learn about context window sizes and management strategies.3840  </Card>38413842  <Card title="Session memory compaction cookbook" icon="book" href="https://platform.claude.com/cookbook/misc-session-memory-compaction">3843    Explore a practical implementation that manages long-running conversations with instant session memory compaction using background threading and prompt caching.3844  </Card>3845</CardGroup>3846
Files main
Menu

Theme