Repository Public
1---2title: Preserved thinking3url: https://platform.claude.com/docs/en/build-with-claude/preserved-thinking4description: Preserved thinking lets a model use a thinking block from an earlier turn only if that model or an earlier one produced it and nothing before the block has changed.5---67Preserved thinking is a property of newer Claude models that guards against distillation. It decides whether the model can use a thinking block that you send back from an earlier turn. Starting with Claude Fable 5.1, when a `thinking` or `redacted_thinking` block comes back in a request, the API checks the block's `signature` for two things:89* **The model is the one that produced the block, or a newer one.** A model reads its own thinking blocks and those of earlier models. Claude Fable 5.1 reads blocks from Claude Opus 5, but Claude Opus 5 can't read blocks from Claude Fable 5.1. If the current model can't read a block, the API drops it from that request without an error. See [Switching models mid-conversation](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#switching-models).10* **Nothing before the thinking block has changed.** The top-level `system` prompt, `tools`, and `messages` before the block are its prefix. If the prefix differs from what you sent when the block was produced, that block and every later thinking block are invalid, and the API rejects the request with a 400 error or drops the invalid blocks, whichever you choose. See [Keeping the prefix unchanged](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#prefix-check).1112The model check applies to every account. The API enforces the prefix check by default for accounts created on or after August 31, 2026, 00:00 UTC. On older accounts, it enforces the prefix check only on requests that set `thinking.block_binding.prefix_mismatch_behavior`. **Later models will enforce the prefix check for all accounts**, so make your integration append-only now.1314## Who needs to change anything1516Nothing changes for you if Claude Code, claude.ai, Claude Managed Agents, or the Claude Agent SDK builds your requests, or if your code keeps `system` and `tools` fixed for a session and only ever appends to `messages`. Claude Mythos 5.1 and models before Claude Fable 5.1 don't run the prefix check. If you never send thinking blocks back, the prefix check has nothing to reject, and the model gets none of its earlier reasoning.1718Check your integration if, between two requests in one conversation, it does any of the following. Each item links to what to do instead:1920* [Rebuilds the `system` prompt](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions): the date, a mode flag, re-read project instructions, or a plugin or MCP server that connects after the first turn21* [Re-renders the context in the first user message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#changing-context)22* [Clears or shortens old tool results, or re-encodes old images](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming)23* [Summarizes or drops old turns on the client](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client) and keeps recent turns with their thinking24* [Adds, removes, or edits entries in `tools`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#tool-changes)25* [Adds a reminder to a user turn](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) and removes or rewrites it later26* [Drops some `thinking` blocks and keeps later ones](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#append-assistant-turns-exactly-as-returned), or removes them and [later puts them back](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#prefix-check)27* [Rebuilds a saved session from templates](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#faq) instead of replaying what it sent2829On an older account, none of these produces an error unless the request sets `prefix_mismatch_behavior`, so a run with no errors on your own key doesn't show whether your code is affected. If people run your tool with their own API keys, those on newer accounts get the 400 error before you do. [Set `prefix_mismatch_behavior` in your tests](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#how-to-tell-whether-your-integration-is-impacted) to see what they see.3031## Switching models mid-conversation3233Claude Fable 5.1 and Claude Mythos 5.1 read thinking blocks produced by each other and by earlier Claude models. No earlier model reads thinking blocks from Claude Fable 5.1 or Claude Mythos 5.1.3435* **A conversation that moves up to Claude Fable 5.1 keeps its reasoning.** The earlier model's thinking blocks stay readable, so the model thinks as usual from the first turn after the switch.36* **A conversation that moves down to an earlier model loses Claude Fable 5.1's reasoning for that request.** This happens when a router sends a turn to a cheaper model, after a [classifier refusal fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback), or during a [server-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#server-side-fallback). The API removes the unreadable blocks before the prompt reaches the model. They aren't billed and don't count toward `input_tokens`.3738Keep sending the full history on every request, thinking blocks included, and let the API drop what the current model can't read. The API never edits your `messages` array, so the dropped blocks stay in your history. When the same history goes back to Claude Fable 5.1, its blocks are readable again, along with the earlier model's thinking. The reasoning is lost for good only if your client removes the blocks itself, for example a harness that strips thinking on a model switch or rebuilds the history from what each model used.39404142With the `thinking-binding-controls-2026-08-01` [beta header](https://platform.claude.com/docs/en/api/beta-headers), the response lists each dropped block in a top-level `input_transformations` array with `reason: "model_binding_mismatch"`:4344```json45{46 "input_transformations": [47 {48 "type": "thinking_dropped",49 "path": "messages.3.content.0",50 "reason": "model_binding_mismatch"51 }52 ]53}54```5556Without the header, the drop is silent. This entry isn't a bug in your integration, and `prefix_mismatch_behavior` has no effect on it: a block the current model can't read is always dropped.5758## Keeping the prefix unchanged5960On Claude Fable 5.1, a thinking block stays valid only while everything you sent before it is unchanged on later requests. The checked prefix has three parts:6162* The top-level `system` prompt63* The set of `tools`64* Every `message` before the block6566Note: With server-side [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction), the checked prefix starts at the most recent compaction block.6768Request parameters outside those three fields, such as `effort`, `max_tokens`, `output_config`, `tool_choice`, and `metadata`, aren't part of the prefix check, and neither are `cache_control` markers. [What counts as an edit](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#what-counts-as-an-edit) has the full list.6970Earlier thinking blocks aren't in the prefix, but each thinking block records which thinking block came before it, across turns. You can remove thinking blocks from the start of the history (oldest first), from the end, or all of them. What fails is a gap: the thinking blocks you keep must be an unbroken run of the original sequence, so removing one from the middle invalidates the thinking blocks after it. Once you remove a block, leave it out. Putting it back invalidates the thinking blocks produced while it was gone.7172Keep `system` and `tools` fixed for the session and treat `messages` as append-only. The same discipline keeps the prefix stable for [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): the edits that invalidate thinking are the edits that restart the cache.7374### What the API does with an invalid block7576You choose with `thinking.block_binding.prefix_mismatch_behavior`:7778* **`"error"` (the default):** the API rejects the request with a 400 `invalid_request_error` that names the first failing block.79* **`"drop_block"`:** the API drops each failing block and every thinking block after it, and the request succeeds. Dropped blocks aren't billed. The model answers that turn without using reasoning from dropped blocks, and the prompt cache restarts at the edit. The response lists each dropped block in `input_transformations` (on the `message_start` event when streaming) with `reason: "prefix_binding_mismatch"`.8081`"drop_block"` keeps requests succeeding but doesn't fix the edit. Count the responses in each session whose `input_transformations` has a `prefix_binding_mismatch` entry, and alert on them. In the Message Batches API, an item that leaves the field unset drops failing blocks instead of erroring, so set `"error"` explicitly there if you want batch items to fail.8283Both the field and the `input_transformations` array require the `thinking-binding-controls-2026-08-01` [beta header](https://platform.claude.com/docs/en/api/beta-headers). [Set the mismatch behavior and read `input_transformations`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#preserved-thinking-controls) shows the request in each SDK.8485The 400 message begins:8687```text wrap88messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to "drop_block".89```9091If the request didn't send the beta header, the message continues:9293```text wrap94That setting requires the `thinking-binding-controls-2026-08-01` value in the `anthropic-beta` header.95```9697It usually ends with a sentence naming what changed, for example that the `system` prompt or the `tools` list differs from when the block was created. [Troubleshooting thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#error-thinking-block-signature) describes what that sentence can name.9899A tampered or undecryptable signature is a different failure. It always returns a 400 (``Invalid `signature` in `thinking` block`` with no sentence about the conversation), and `prefix_mismatch_behavior` doesn't apply to it.100101#### Handle the error in code102103This is the 400 `invalid_request_error` shown earlier in this section. Don't resend the same body: it fails the same way every time. Retry once with the beta header and `prefix_mismatch_behavior: "drop_block"`, and store that choice with the session so every later request sends it too, including after a restart. If you can't send the beta header, remove every `thinking` and `redacted_thinking` block from the history once, leave them out, and continue. Then fix the edit that caused the mismatch.104105### Set the mismatch behavior and read `input_transformations`106107The `thinking-binding-controls-2026-08-01` [beta header](https://platform.claude.com/docs/en/api/beta-headers) adds:108109* A top-level `input_transformations` array on every response110* A `block_binding` object on the `thinking` configuration, whose one field is `prefix_mismatch_behavior`111112`block_binding` is accepted alongside `thinking.type: "adaptive"` and `thinking.type: "enabled"`. Sending it without the beta header returns a 400 error whose message ends `block_binding: Extra inputs are not permitted`. Models that don't run the prefix check accept the object and report only model-check drops, so one request body works across models. The API reference calls the prefix check the conversation check.113114The following request opts into dropping rather than rejecting. On a first turn there's nothing to replay, so `input_transformations` comes back empty:115116<CodeGroup>117 ```bash cURL118 curl https://api.anthropic.com/v1/messages \119 -H "x-api-key: $ANTHROPIC_API_KEY" \120 -H "anthropic-version: 2023-06-01" \121 -H "anthropic-beta: thinking-binding-controls-2026-08-01" \122 -H "content-type: application/json" \123 -d '{124 "model": "claude-fable-5-1",125 "max_tokens": 16000,126 "thinking": {127 "type": "adaptive",128 "block_binding": {129 "prefix_mismatch_behavior": "drop_block"130 }131 },132 "messages": [133 {134 "role": "user",135 "content": "What is the greatest common divisor of 1071 and 462?"136 }137 ]138 }'139 ```140141 ```bash CLI142 ant beta:messages create --beta thinking-binding-controls-2026-08-01 \143 --format yaml <<'YAML'144 model: claude-fable-5-1145 max_tokens: 16000146 thinking:147 type: adaptive148 block_binding:149 prefix_mismatch_behavior: drop_block150 messages:151 - role: user152 content: What is the greatest common divisor of 1071 and 462?153 YAML154 ```155156 ```python Python157 client = anthropic.Anthropic()158159 response = client.beta.messages.create(160 model="claude-fable-5-1",161 max_tokens=16000,162 thinking={163 "type": "adaptive",164 "block_binding": {"prefix_mismatch_behavior": "drop_block"},165 },166 messages=[167 {168 "role": "user",169 "content": "What is the greatest common divisor of 1071 and 462?",170 }171 ],172 betas=["thinking-binding-controls-2026-08-01"],173 )174175 for block in response.content:176 if block.type == "text":177 print(block.text)178179 print(f"Input transformations: {len(response.input_transformations or [])}")180 ```181182 ```typescript TypeScript183 const client = new Anthropic();184185 const response = await client.beta.messages.create({186 model: "claude-fable-5-1",187 max_tokens: 16000,188 thinking: {189 type: "adaptive",190 block_binding: { prefix_mismatch_behavior: "drop_block" }191 },192 messages: [193 { role: "user", content: "What is the greatest common divisor of 1071 and 462?" }194 ],195 betas: ["thinking-binding-controls-2026-08-01"]196 });197198 for (const block of response.content) {199 if (block.type === "text") {200 console.log(block.text);201 }202 }203 console.log(`Input transformations: ${response.input_transformations?.length ?? 0}`);204 ```205206 ```csharp C#207 AnthropicClient client = new();208209 var response = await client.Beta.Messages.Create(210 new()211 {212 Model = "claude-fable-5-1",213 MaxTokens = 16000,214 Thinking = new BetaThinkingConfigAdaptive215 {216 BlockBinding = new()217 {218 PrefixMismatchBehavior = BetaThinkingPrefixMismatchBehavior.DropBlock,219 },220 },221 Messages =222 [223 new()224 {225 Role = Role.User,226 Content = "What is the greatest common divisor of 1071 and 462?",227 },228 ],229 Betas = [AnthropicBeta.ThinkingBindingControls2026_08_01],230 }231 );232233 foreach (var block in response.Content)234 {235 if (block.TryPickText(out var textBlock))236 {237 Console.WriteLine(textBlock.Text);238 }239 }240241 Console.WriteLine($"Input transformations: {response.InputTransformations?.Count ?? 0}");242 ```243244 ```go Go245 client := anthropic.NewClient()246247 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{248 Model: "claude-fable-5-1",249 MaxTokens: 16000,250 Thinking: anthropic.BetaThinkingConfigParamUnion{251 OfAdaptive: &anthropic.BetaThinkingConfigAdaptiveParam{252 BlockBinding: anthropic.BetaThinkingBlockBindingParam{253 PrefixMismatchBehavior: anthropic.BetaThinkingPrefixMismatchBehaviorDropBlock,254 },255 },256 },257 Messages: []anthropic.BetaMessageParam{258 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What is the greatest common divisor of 1071 and 462?")),259 },260 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaThinkingBindingControls2026_08_01},261 })262 if err != nil {263 log.Fatal(err)264 }265266 for _, block := range response.Content {267 if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {268 fmt.Println(textBlock.Text)269 }270 }271 fmt.Printf("Input transformations: %d\n", len(response.InputTransformations))272 ```273274 ```java Java275 import com.anthropic.models.beta.AnthropicBeta;276 import com.anthropic.models.beta.messages.BetaMessage;277 import com.anthropic.models.beta.messages.BetaThinkingBlockBinding;278 import com.anthropic.models.beta.messages.BetaThinkingConfigAdaptive;279 import com.anthropic.models.beta.messages.BetaThinkingPrefixMismatchBehavior;280 import com.anthropic.models.beta.messages.MessageCreateParams;281282 void main() {283 AnthropicClient client = AnthropicOkHttpClient.fromEnv();284285 MessageCreateParams params = MessageCreateParams.builder()286 .model("claude-fable-5-1")287 .maxTokens(16000L)288 .addBeta(AnthropicBeta.THINKING_BINDING_CONTROLS_2026_08_01)289 .thinking(BetaThinkingConfigAdaptive.builder()290 .blockBinding(BetaThinkingBlockBinding.builder()291 .prefixMismatchBehavior(BetaThinkingPrefixMismatchBehavior.DROP_BLOCK)292 .build())293 .build())294 .addUserMessage("What is the greatest common divisor of 1071 and 462?")295 .build();296297 BetaMessage response = client.beta().messages().create(params);298299 response.content().stream()300 .flatMap(block -> block.text().stream())301 .forEach(textBlock -> IO.println(textBlock.text()));302 IO.println("Input transformations: "303 + response.inputTransformations().map(List::size).orElse(0));304 }305 ```306307 ```php PHP308 use Anthropic\Beta\AnthropicBeta;309 use Anthropic\Beta\Messages\BetaThinkingBlockBinding;310 use Anthropic\Beta\Messages\BetaThinkingConfigAdaptive;311 use Anthropic\Beta\Messages\BetaThinkingPrefixMismatchBehavior;312 use Anthropic\Client;313314 $client = new Client();315316 $response = $client->beta->messages->create(317 model: 'claude-fable-5-1',318 maxTokens: 16000,319 thinking: BetaThinkingConfigAdaptive::with(320 blockBinding: BetaThinkingBlockBinding::with(321 prefixMismatchBehavior: BetaThinkingPrefixMismatchBehavior::DROP_BLOCK,322 ),323 ),324 messages: [325 ['role' => 'user', 'content' => 'What is the greatest common divisor of 1071 and 462?'],326 ],327 betas: [AnthropicBeta::THINKING_BINDING_CONTROLS_2026_08_01],328 );329330 foreach ($response->content as $block) {331 if ($block->type === 'text') {332 echo $block->text, PHP_EOL;333 }334 }335336 echo 'Input transformations: ', count($response->inputTransformations ?? []), PHP_EOL;337 ```338339 ```ruby Ruby340 client = Anthropic::Client.new341342 response = client.beta.messages.create(343 model: "claude-fable-5-1",344 max_tokens: 16_000,345 thinking: {346 type: "adaptive",347 block_binding: {prefix_mismatch_behavior: "drop_block"}348 },349 messages: [350 {role: "user", content: "What is the greatest common divisor of 1071 and 462?"}351 ],352 betas: [Anthropic::AnthropicBeta::THINKING_BINDING_CONTROLS_2026_08_01]353 )354355 response.content.each do |block|356 puts block.text if block.type == :text357 end358359 puts "Input transformations: #{response.input_transformations&.length || 0}"360 ```361</CodeGroup>362363```text Output wrap364The greatest common divisor of 1071 and 462 is 21.365Input transformations: 0366```367368Under the beta header, every response from a thinking-capable model carries `input_transformations`. It's empty when nothing was dropped. Each entry has `type: "thinking_dropped"`, the `path` of the dropped block (for example `messages.1.content.0`), and a `reason` of `prefix_binding_mismatch` or `model_binding_mismatch` (see [Switching models mid-conversation](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#switching-models)). Ignore entries whose `type` or `reason` you don't recognize, because later checks add values.369370When [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming), the array arrives on the `message` object in the `message_start` event. After a mid-stream server-side fallback, the final `message_delta` event carries it again with the serving model's entries. In a [message batch](https://platform.claude.com/docs/en/build-with-claude/batch-processing), an item whose block fails the prefix check under an explicit `"error"` resolves as `errored`, and an item that leaves the field unset drops the failing blocks instead. The [token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) endpoint runs the same prefix check and returns the same 400.371372### When the API enforces the check373374The prefix check runs on Claude Fable 5.1 for new accounts.375376* **Accounts created on or after August 31, 2026, 00:00 UTC:** the API checks Claude Fable 5.1 requests and applies `"error"` unless you set `"drop_block"`. The same definition of a new account applies to the Claude API and to cloud platforms.377* **Older accounts:** the API checks requests that set `prefix_mismatch_behavior`. This parameter opts a request in, so you can see what a new account sees without creating one.378* **Later models:** every account, on every request.379380To find out which group your account is in, take a Claude Fable 5.1 conversation that contains a thinking block, change something before that block, and send it to Claude Fable 5.1 without the beta header or the `block_binding` field. A 400 response that names the header means your account is enforced by default.381382### What counts as an edit383384Each row compares two consecutive requests:385386| Change between requests | Later thinking blocks |387| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |388| Append messages at the end | Valid |389| Add a tool with `defer_loading: true` that nothing has referenced yet | Valid |390| Remove `thinking` blocks from the start of the history, from the end, or all of them | Valid (the model loses that reasoning) |391| Change any request parameter outside `system`, `tools`, and `messages` (`effort`, `max_tokens`, `output_config`, `tool_choice`, `metadata`, `thinking.display`, and so on) | Valid |392| Add, move, or remove `cache_control` markers | Valid |393| A rotating signed URL that returns the same bytes | Valid |394| Server-side compaction or context editing removes or replaces content | Valid (the check compares what you sent, not the server's edited copy) |395| A cleared [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) left in place | Valid |396| Edit, reorder, or delete any earlier `user`, `assistant`, or `system` message | Invalid, except when the signed block from [on-demand compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming) replaces the messages it summarizes, under the conditions in [Keep-tail compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#keep-tail-compaction) |397| Re-render the context you put in the first user message with a changed value | Invalid for every thinking block |398| Clear or shorten an earlier `tool_result`, re-encode an earlier image, or change an earlier `tool_use` input | Invalid for every later thinking block |399| Add a text block to an earlier user turn, or remove one you added last time | Invalid |400| Change the top-level `system` string or blocks | Invalid |401| Add, remove, rename, or edit a tool in `tools` | Invalid |402| Remove a `thinking` block from the middle of the history and keep later ones | Invalid for every later thinking block |403| Put back a `thinking` block you removed on an earlier request | Invalid for thinking blocks produced while it was gone |404| An image or document URL that returns different bytes on the next request | Invalid |405| The same turn-scoped message deleted or reworded on a later request | Invalid |406407### Check whether your code edits the prefix408409First, diff what you send. Capture the request bodies your integration sends over a few normal turns, including a compaction or a tool change. For each pair of consecutive requests, compare `system`, `tools`, and the `messages` they share. They should be identical up to the newly appended turns.410411Then confirm against the API. Add the `thinking-binding-controls-2026-08-01` beta header, set `prefix_mismatch_behavior` to `"drop_block"`, and run a normal multi-turn session through your integration on claude-fable-5-1. The following example runs two turns the way your integration should: `messages` only grows, each assistant turn goes back exactly as the API returned it, `thinking` blocks included, and `block_binding` is set on every request. After each turn it prints the number of `thinking` blocks in the response and the number of dropped blocks:412413<CodeGroup>414 ```bash cURL415 # Counts the thinking blocks in a response and the blocks the API dropped416 COUNTS='"thinking blocks: \([.content[] | select(.type == "thinking")] | length), " +417 "dropped: \(.input_transformations | length)"'418419 FIRST=$(curl -s https://api.anthropic.com/v1/messages \420 -H "content-type: application/json" \421 -H "x-api-key: $ANTHROPIC_API_KEY" \422 -H "anthropic-version: 2023-06-01" \423 -H "anthropic-beta: thinking-binding-controls-2026-08-01" \424 -d '{425 "model": "claude-fable-5-1",426 "max_tokens": 16000,427 "thinking": {428 "type": "adaptive",429 "block_binding": { "prefix_mismatch_behavior": "drop_block" }430 },431 "messages": [432 {433 "role": "user",434 "content": "How many positive integers below 500 have exactly 6 positive divisors?"435 }436 ]437 }')438 echo "$FIRST" | jq -r "$COUNTS"439440 # Turn 2: the assistant turn goes back exactly as returned, then the next user message441 MESSAGES=$(jq -n --argjson first "$FIRST" '[442 {443 role: "user",444 content: "How many positive integers below 500 have exactly 6 positive divisors?"445 },446 { role: "assistant", content: $first.content },447 { role: "user", content: "How many of those are odd?" }448 ]')449450 jq -n --argjson messages "$MESSAGES" '{451 model: "claude-fable-5-1",452 max_tokens: 16000,453 thinking: {454 type: "adaptive",455 block_binding: { prefix_mismatch_behavior: "drop_block" }456 },457 messages: $messages458 }' | curl -s https://api.anthropic.com/v1/messages \459 -H "content-type: application/json" \460 -H "x-api-key: $ANTHROPIC_API_KEY" \461 -H "anthropic-version: 2023-06-01" \462 -H "anthropic-beta: thinking-binding-controls-2026-08-01" \463 -d @- | jq -r "$COUNTS"464 ```465466 ```bash CLI467 # Counts the thinking blocks in a response and the blocks the API dropped468 COUNTS='"thinking blocks: \([.content[] | select(.type == "thinking")] | length), " +469 "dropped: \(.input_transformations | length)"'470471 FIRST=$(ant beta:messages create --beta thinking-binding-controls-2026-08-01 \472 --format json <<'YAML'473 model: claude-fable-5-1474 max_tokens: 16000475 thinking:476 type: adaptive477 block_binding:478 prefix_mismatch_behavior: drop_block479 messages:480 - role: user481 content: How many positive integers below 500 have exactly 6 positive divisors?482 YAML483 )484 echo "$FIRST" | jq -r "$COUNTS"485486 # Turn 2: the assistant turn goes back exactly as returned, then the next user message487 ant beta:messages create --beta thinking-binding-controls-2026-08-01 \488 --format json <<YAML | jq -r "$COUNTS"489 model: claude-fable-5-1490 max_tokens: 16000491 thinking:492 type: adaptive493 block_binding:494 prefix_mismatch_behavior: drop_block495 messages:496 - role: user497 content: How many positive integers below 500 have exactly 6 positive divisors?498 - role: assistant499 content: $(echo "$FIRST" | jq -c .content)500 - role: user501 content: How many of those are odd?502 YAML503 ```504505 ```python Python506 client = anthropic.Anthropic()507508 user_turns = [509 "How many positive integers below 500 have exactly 6 positive divisors?",510 "How many of those are odd?",511 ]512513 # messages grows across turns: each assistant turn goes back exactly as returned514 messages = []515 for user_turn in user_turns:516 messages.append({"role": "user", "content": user_turn})517 response = client.beta.messages.create(518 model="claude-fable-5-1",519 max_tokens=16000,520 thinking={521 "type": "adaptive",522 "block_binding": {"prefix_mismatch_behavior": "drop_block"},523 },524 messages=messages,525 betas=["thinking-binding-controls-2026-08-01"],526 )527 messages.append({"role": "assistant", "content": response.content})528 thinking_blocks = sum(block.type == "thinking" for block in response.content)529 dropped = len(response.input_transformations or [])530 print(f"thinking blocks: {thinking_blocks}, dropped: {dropped}")531 ```532533 ```typescript TypeScript534 const client = new Anthropic();535536 const userTurns = [537 "How many positive integers below 500 have exactly 6 positive divisors?",538 "How many of those are odd?"539 ];540541 // messages grows across turns: each assistant turn goes back exactly as returned542 const messages: Anthropic.Beta.BetaMessageParam[] = [];543 for (const userTurn of userTurns) {544 messages.push({ role: "user", content: userTurn });545 const response = await client.beta.messages.create({546 model: "claude-fable-5-1",547 max_tokens: 16000,548 thinking: {549 type: "adaptive",550 block_binding: { prefix_mismatch_behavior: "drop_block" }551 },552 messages,553 betas: ["thinking-binding-controls-2026-08-01"]554 });555 messages.push({ role: "assistant", content: response.content });556 const thinkingBlocks = response.content.filter((block) => block.type === "thinking");557 const dropped = response.input_transformations ?? [];558 console.log(`thinking blocks: ${thinkingBlocks.length}, dropped: ${dropped.length}`);559 }560 ```561562 ```csharp C#563 AnthropicClient client = new();564565 string[] userTurns =566 [567 "How many positive integers below 500 have exactly 6 positive divisors?",568 "How many of those are odd?",569 ];570571 // messages grows across turns: each assistant turn goes back exactly as returned572 List<BetaMessageParam> messages = [];573 foreach (var userTurn in userTurns)574 {575 messages.Add(new() { Role = Role.User, Content = userTurn });576 var response = await client.Beta.Messages.Create(577 new()578 {579 Model = "claude-fable-5-1",580 MaxTokens = 16000,581 Thinking = new BetaThinkingConfigAdaptive582 {583 BlockBinding = new()584 {585 PrefixMismatchBehavior = BetaThinkingPrefixMismatchBehavior.DropBlock,586 },587 },588 Messages = messages,589 Betas = [AnthropicBeta.ThinkingBindingControls2026_08_01],590 }591 );592 messages.Add(new()593 {594 Role = Role.Assistant,595 Content = response.Content.Select(block => new BetaContentBlockParam(block.Json)).ToList(),596 });597 var thinkingBlocks = response.Content.Count(block => block.TryPickThinking(out _));598 var dropped = response.InputTransformations?.Count ?? 0;599 Console.WriteLine($"thinking blocks: {thinkingBlocks}, dropped: {dropped}");600 }601 ```602603 ```go Go604 client := anthropic.NewClient()605606 userTurns := []string{607 "How many positive integers below 500 have exactly 6 positive divisors?",608 "How many of those are odd?",609 }610611 // messages grows across turns: each assistant turn goes back exactly as returned612 messages := []anthropic.BetaMessageParam{}613 for _, userTurn := range userTurns {614 messages = append(messages, anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(userTurn)))615 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{616 Model: "claude-fable-5-1",617 MaxTokens: 16000,618 Thinking: anthropic.BetaThinkingConfigParamUnion{619 OfAdaptive: &anthropic.BetaThinkingConfigAdaptiveParam{620 BlockBinding: anthropic.BetaThinkingBlockBindingParam{621 PrefixMismatchBehavior: anthropic.BetaThinkingPrefixMismatchBehaviorDropBlock,622 },623 },624 },625 Messages: messages,626 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaThinkingBindingControls2026_08_01},627 })628 if err != nil {629 log.Fatal(err)630 }631 messages = append(messages, response.ToParam())632 thinkingBlocks := 0633 for _, block := range response.Content {634 if block.Type == "thinking" {635 thinkingBlocks++636 }637 }638 fmt.Printf("thinking blocks: %d, dropped: %d\n", thinkingBlocks, len(response.InputTransformations))639 }640 ```641642 ```java Java643 import com.anthropic.models.beta.AnthropicBeta;644 import com.anthropic.models.beta.messages.BetaContentBlock;645 import com.anthropic.models.beta.messages.BetaMessage;646 import com.anthropic.models.beta.messages.BetaThinkingBlockBinding;647 import com.anthropic.models.beta.messages.BetaThinkingConfigAdaptive;648 import com.anthropic.models.beta.messages.BetaThinkingPrefixMismatchBehavior;649 import com.anthropic.models.beta.messages.MessageCreateParams;650651 void main() {652 AnthropicClient client = AnthropicOkHttpClient.fromEnv();653654 List<String> userTurns = List.of(655 "How many positive integers below 500 have exactly 6 positive divisors?",656 "How many of those are odd?");657658 // The builder's message list grows across turns: each assistant turn goes back exactly as returned659 MessageCreateParams.Builder conversation = MessageCreateParams.builder()660 .model("claude-fable-5-1")661 .maxTokens(16000L)662 .thinking(BetaThinkingConfigAdaptive.builder()663 .blockBinding(BetaThinkingBlockBinding.builder()664 .prefixMismatchBehavior(BetaThinkingPrefixMismatchBehavior.DROP_BLOCK)665 .build())666 .build())667 .addBeta(AnthropicBeta.THINKING_BINDING_CONTROLS_2026_08_01);668669 for (String userTurn : userTurns) {670 conversation.addUserMessage(userTurn);671 BetaMessage response = client.beta().messages().create(conversation.build());672 conversation.addMessage(response);673 long thinkingBlocks = response.content().stream()674 .filter(BetaContentBlock::isThinking)675 .count();676 int dropped = response.inputTransformations().map(List::size).orElse(0);677 IO.println("thinking blocks: " + thinkingBlocks + ", dropped: " + dropped);678 }679 }680 ```681682 ```php PHP683 use Anthropic\Beta\AnthropicBeta;684 use Anthropic\Beta\Messages\BetaThinkingBlockBinding;685 use Anthropic\Beta\Messages\BetaThinkingConfigAdaptive;686 use Anthropic\Beta\Messages\BetaThinkingPrefixMismatchBehavior;687 use Anthropic\Client;688689 $client = new Client();690691 $userTurns = [692 'How many positive integers below 500 have exactly 6 positive divisors?',693 'How many of those are odd?',694 ];695696 // $messages grows across turns: each assistant turn goes back exactly as returned697 $messages = [];698 foreach ($userTurns as $userTurn) {699 $messages[] = ['role' => 'user', 'content' => $userTurn];700 $response = $client->beta->messages->create(701 model: 'claude-fable-5-1',702 maxTokens: 16000,703 thinking: BetaThinkingConfigAdaptive::with(704 blockBinding: BetaThinkingBlockBinding::with(705 prefixMismatchBehavior: BetaThinkingPrefixMismatchBehavior::DROP_BLOCK,706 ),707 ),708 messages: $messages,709 betas: [AnthropicBeta::THINKING_BINDING_CONTROLS_2026_08_01],710 );711 $messages[] = ['role' => 'assistant', 'content' => $response->content];712 $thinkingBlocks = array_filter($response->content, fn ($block) => $block->type === 'thinking');713 $dropped = $response->inputTransformations ?? [];714 echo 'thinking blocks: ', count($thinkingBlocks), ', dropped: ', count($dropped), PHP_EOL;715 }716 ```717718 ```ruby Ruby719 client = Anthropic::Client.new720721 user_turns = [722 "How many positive integers below 500 have exactly 6 positive divisors?",723 "How many of those are odd?"724 ]725726 # messages grows across turns: each assistant turn goes back exactly as returned727 messages = []728 user_turns.each do |user_turn|729 messages << {role: "user", content: user_turn}730 response = client.beta.messages.create(731 model: "claude-fable-5-1",732 max_tokens: 16_000,733 thinking: {734 type: "adaptive",735 block_binding: {prefix_mismatch_behavior: "drop_block"}736 },737 messages: messages,738 betas: [Anthropic::AnthropicBeta::THINKING_BINDING_CONTROLS_2026_08_01]739 )740 messages << {role: "assistant", content: response.content}741 thinking_blocks = response.content.count { |block| block.type == :thinking }742 dropped = (response.input_transformations || []).length743 puts "thinking blocks: #{thinking_blocks}, dropped: #{dropped}"744 end745 ```746</CodeGroup>747748```text Output wrap749thinking blocks: 1, dropped: 0750thinking blocks: 1, dropped: 0751```752753Neither turn drops a block because nothing earlier changed. Check that the first response contains a `thinking` block. With adaptive thinking, some responses have none. If no response in the session has one, there is nothing to check and the dropped count is 0 whatever you change, so run the example again.754755Log `input_transformations` on every turn of your own integration. When the API drops a block, the entry looks like the following:756757```json758{759 "input_transformations": [760 {761 "type": "thinking_dropped",762 "path": "messages.1.content.0",763 "reason": "prefix_binding_mismatch"764 }765 ]766}767```768769* **Empty on every turn of a session that contains `thinking` blocks:** your integration keeps the prefix intact.770* **`reason: "prefix_binding_mismatch"`:** something before the block at `path` changed since the previous request. Diff `system`, `tools`, and `messages` up to that turn to find it, or resend the request with `"error"`: the 400 usually ends with a sentence naming what changed. Then find the matching replacement in [Make changes without editing the prefix](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#replace-prefix-edits).771* **`reason: "model_binding_mismatch"`:** the conversation moved to a model that can't read the earlier model's blocks. This isn't a prefix edit. See [Switching models mid-conversation](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#switching-models).772773To see a failure on purpose, send a third turn from the earlier example and add a `system` prompt to that request only, so that it differs from the first two requests, which had none. With `"drop_block"`, the dropped count is no longer 0: the response has one entry for each thinking block in the history, each with `reason: "prefix_binding_mismatch"`. With `"error"`, the request returns the 400 described in [What the API does with an invalid block](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#mismatch-behavior), and its last sentence names the `system` prompt. In the cURL and CLI tabs, remove the `jq` filter to see the error body. If the count is still 0, there was nothing to check: confirm that the model is claude-fable-5-1, that the request sets `block_binding`, that the history you sent contains `thinking` blocks, and that the first two requests had no `system` prompt.774775Two plain turns rarely show the problem. Run a session through each of the following, with `"error"` set so that a regression fails your CI:776777* The first client-side compaction or trim778* A tool, plugin, or MCP server that connects after the first turn779* A mode or instruction change780* A long tool loop, if you add reminders or shorten old tool results781* A switch to another model and back782* A save, a restart, and a resume on a later date783784## Make changes without editing the prefix785786Each common prefix edit has a replacement that gives the model the same information and leaves earlier bytes unchanged, so later thinking stays valid. Find the edit your code makes today in the first column:787788| Instead of | Use | Beta header |789| --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |790| Rebuilding the top-level `system` prompt | A [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions) | None |791| Re-rendering the context in your first user message (environment, date, memory, project instructions) on each request | Render it once and resend it unchanged. When something changes, [put the new version in the newest turn](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#changing-context) | None |792| Clearing or shortening old `tool_result` content, or re-encoding old images, in place | Shorten a tool result or downscale an image before the first time you send it, not after. To clear old results later, [trim context on the server](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming) with `clear_tool_uses_20250919` | `context-management-2025-06-27` |793| Injecting a reminder and deleting it on the next request | A [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) (`clear_at: "next_user_message"`) | `mid-conversation-system-clear-at-2026-08-21` |794| Adding or removing entries in `tools` | [`tool_addition` and `tool_removal` blocks](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#tool-changes) | `mid-conversation-tool-changes-2026-07-01` |795| Changing top-level `output_config.effort` (restarts the cache, doesn't affect thinking) | A [per-message `output_config`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#effort-changes) | `mid-conversation-output-config-2026-07-01` |796| Dropping or summarizing old turns on the client | [On-demand compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming) to keep the recent turns with their thinking, other server-side [compaction or context editing](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming), or [client-side compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client) that keeps no stale thinking | `compact-2026-09-04` (not on Amazon Bedrock or Google Cloud) |797| An image or document URL whose bytes change between requests | A [`file_id` from the Files API](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#files-by-id), or base64 | None |798799All of these assume you [send assistant turns back exactly as returned](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#append-assistant-turns-exactly-as-returned). Mid-conversation system messages, turn-scoped system messages, and tool changes aren't available on every model: [Mid-conversation system messages and tool changes](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) lists the models that accept them. If your code serves several models, keep editing the top-level `system` prompt for the models that don't accept them.800801To use several betas in one request, combine the values in one `anthropic-beta` header. Beta names are the same on Amazon Bedrock and Google Cloud wherever the beta is available there (see [Beta headers](https://platform.claude.com/docs/en/api/beta-headers)):802803```text wrap804anthropic-beta: thinking-binding-controls-2026-08-01,mid-conversation-system-clear-at-2026-08-21,mid-conversation-tool-changes-2026-07-01805```806807### Send assistant turns back exactly as returned808809Store the `content` array from each response and send it back unchanged as the assistant turn: every block type, in the order received, including `thinking` blocks whose `thinking` field is empty. A serializer that drops unknown block types, drops empty fields, or reorders blocks edits the prefix for every later turn.810811On Claude Fable 5.1, the `thinking` field is empty by default and the `signature` carries the reasoning, so a serializer that skips empty blocks removes thinking. If it removes all of them, nothing fails and the model loses its earlier reasoning on every turn. If you parse the stream yourself, keep the block even when no thinking text arrives: it opens, receives its `signature` in a `signature_delta` event, and closes. A block sent back with an empty `signature` fails.812813### Add instructions with a mid-conversation system message814815Some harnesses rebuild the top-level `system` prompt on each request to carry the current time, a token budget, a mode flag, or newly discovered project context. That invalidates every thinking block in the conversation. Instead, freeze `system` at session start. When something changes, append a [`role: "system"` message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) at the point in `messages` where the change becomes true:816817```json818{819 "role": "system",820 "content": "The user switched the workspace to read-only mode. Do not write files until told otherwise."821}822```823824The model treats this message with system-prompt authority, and everything before it stays unchanged. In a tool loop, place the message after the `tool_result` user message, never between an assistant `tool_use` and its `tool_result` (see [Limitations](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#limitations)). Once sent, the message is part of the prefix for later thinking: leave it in place on later requests.825826### Put changing context in the newest turn827828Some harnesses put an environment block in the first user message (working directory, branch, date, memory, project instructions) and render it again on every request. When any value changes, `messages[0]` changes, and every thinking block in the conversation is invalid. Render that block once and resend it as it was. When a value changes, say so in the newest turn: add a text block to the user message you are about to send, or append a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions) if the change comes from you as the operator.829830```json831{832 "role": "user",833 "content": [834 {835 "type": "text",836 "text": "Environment update: the current branch is now release-2."837 },838 { "type": "text", "text": "Run the tests again." }839 ]840}841```842843Once sent, that text block is part of the prefix for later thinking: leave it in place on later requests.844845### Send per-turn reminders as turn-scoped system messages846847A common prefix edit is the per-turn nudge: a line such as "request independent reads together" or "you haven't updated the user in a while" that your code appends after each batch of tool results. To keep reminders from piling up, send each nudge as a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) with `clear_at: "next_user_message"`, placed after the `tool_result` user message. `clear_at` requires the beta header `mid-conversation-system-clear-at-2026-08-21`. The following `messages` array is the request after two tool calls and their results. `messages[3]` is the previous request's nudge, left in place, and `messages[6]` is this request's copy:848849```json850[851 { "role": "user", "content": "Fix the failing test." },852 {853 "role": "assistant",854 "content": [855 { "type": "thinking", "thinking": "", "signature": "..." },856 {857 "type": "tool_use",858 "id": "toolu_01",859 "name": "read_file",860 "input": { "path": "tests/test_auth.py" }861 }862 ]863 },864 {865 "role": "user",866 "content": [{ "type": "tool_result", "tool_use_id": "toolu_01", "content": "..." }]867 },868 {869 "role": "system",870 "clear_at": "next_user_message",871 "content": "Request every independent read in one turn."872 },873 {874 "role": "assistant",875 "content": [876 { "type": "thinking", "thinking": "", "signature": "..." },877 {878 "type": "tool_use",879 "id": "toolu_02",880 "name": "read_file",881 "input": { "path": "src/auth.py" }882 }883 ]884 },885 {886 "role": "user",887 "content": [{ "type": "tool_result", "tool_use_id": "toolu_02", "content": "..." }]888 },889 {890 "role": "system",891 "clear_at": "next_user_message",892 "content": "Request every independent read in one turn."893 }894]895```896897A user message that contains only `tool_result` blocks counts as the "next user message", so `messages[3]` is already cleared. It adds nothing to what the model sees and costs no input tokens, but because it's still in the array, the thinking in `messages[4]` stays valid. `messages[6]` is the copy the model sees this turn. On later requests, keep both where they are and append a fresh copy after the next `tool_result` message.898899### Add or remove tools with `tool_addition` and `tool_removal`900901Editing the `tools` array mid-session invalidates preserved thinking blocks. Instead, declare every tool the session might need in `tools` on the first request and never change the array. To change which tools the model can use from some point on, append a `role: "system"` message that carries a `tool_removal` or `tool_addition` block. These are [mid-conversation tool changes](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes) and need the beta header `mid-conversation-tool-changes-2026-07-01`. For example, to withdraw a dangerous tool after a mode switch:902903```json904{905 "role": "system",906 "content": [907 { "type": "tool_removal", "tool": { "type": "tool_reference", "name": "delete_branch" } },908 { "type": "text", "text": "Branch deletion is disabled for the rest of this session." }909 ]910}911```912913To offer a tool later instead, declare it in `tools` with `defer_loading: true` so the model doesn't see it at first. When it becomes available, append a `tool_addition` block:914915```json916{917 "role": "system",918 "content": [919 { "type": "tool_addition", "tool": { "type": "tool_reference", "name": "deploy" } },920 { "type": "text", "text": "Authentication succeeded. Deployment is now available." }921 ]922}923```924925Sometimes you can't declare a tool up front because you don't know its schema yet. An MCP server discovered at runtime is the common case. Append that tool to `tools` with `defer_loading: true`, then offer it with a `tool_addition` block. Adding a deferred tool is safe: the prefix check ignores a deferred tool until a `tool_addition` block references it, so earlier thinking stays valid. Adding a tool without `defer_loading: true` changes the prefix and invalidates earlier thinking.926927The `role: "system"` messages that carry these blocks join the prefix for later thinking. Leave them in place on later requests.928929### Change effort with a per-message `output_config`930931Changing top-level `output_config.effort` between requests doesn't invalidate thinking, because effort isn't part of the prefix. Changing top-level effort does restart the prompt cache. On Claude Fable 5.1, use [per-message effort](https://platform.claude.com/docs/en/build-with-claude/effort#change-effort-mid-conversation-beta) instead: append a `role: "system"` message with empty `content` and the new level. It needs the beta header `mid-conversation-output-config-2026-07-01`.932933```json934{ "role": "system", "content": [], "output_config": { "effort": "low" } }935```936937The new level takes effect from the next `user` turn. Once sent, the message is part of `messages` and therefore part of the prefix for later thinking: leave it in place on later requests, and append another one to change effort again.938939### Trim context on the server940941Another common prefix edit is client-side trimming: dropping or summarizing the oldest turns and keeping the recent ones verbatim. The kept turns' thinking blocks were produced while the removed history was still in place, so they fail the check. The server-side equivalents don't count as edits, because the check compares the conversation as you sent it:942943* [Compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) summarizes older turns into a compaction block when the context approaches a threshold you set, and the checked prefix restarts from that block. Its [`instructions` parameter](https://platform.claude.com/docs/en/build-with-claude/compaction#custom-summarization-instructions) takes your own summarization prompt, such as "preserve every ticker, position size, and stated assumption". [On-demand compaction](https://platform.claude.com/docs/en/build-with-claude/compaction#compact-on-demand-with-the-compaction-parameter) (beta) returns the summary from a separate request, which can [run in the background](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#background-compaction). Send `"compaction": {"type": "summarize"}` in the request body, and the response carries a single `compaction` block, holding the summary and a signature, instead of a reply. On-demand compaction is available on the Claude API but not on Amazon Bedrock or Google Cloud, and it needs the `compact-2026-09-04` beta header on the summary request and on every later request that carries the block. You send the block in place of the messages it summarizes. The check accepts that swap, so the turns you keep can stay valid with their thinking, under the conditions in [Keep-tail compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#keep-tail-compaction).944* [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) clears old tool results or old thinking blocks by rule, oldest first. The strategies are `clear_tool_uses_20250919` and `clear_thinking_20251015`.945946### Compact on the client947948You can still compact on the client. If you write the summary yourself, don't send back a thinking block that was produced before the rewrite. If the API writes it with on-demand compaction, [Keep-tail compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#keep-tail-compaction) lists when kept thinking stays valid.949950#### Simple compaction (recommended)951952When the conversation grows too long, summarize the whole session into one user message and send only that message plus the next instruction. Nothing earlier is replayed, so there's no thinking left to fail the check, and the model reasons afresh from the summary.953954955956```json957[958 {959 "role": "user",960 "content": "<summary of the session so far>\n\n<the next instruction>"961 }962]963```964965Claude models are trained on long-horizon tasks with this scheme and for most workloads it performs well.966967#### Keep-tail compaction968969Keep-tail compaction summarizes the older turns and keeps the most recent turns verbatim, so the model still sees the last few exchanges word for word. If you write the summary yourself, it breaks the rule: the kept assistant turns still carry thinking blocks that were produced when the original turns, not the summary, came before them. Those blocks fail.970971To keep that thinking, have the API write the summary with [on-demand compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming). Send only the older turns in a request with the `compaction` parameter and the `compact-2026-09-04` beta header. Then send the signed block it returns in place of those turns, followed by the kept turns exactly as returned. The kept thinking stays valid while all of these hold:972973* The compaction request runs on a model with preserved thinking. The conversation's own model is the simple choice.974* The kept turns directly follow the summarized messages, and the first kept message isn't one the API would merge into the last summarized one: a message with the same role, or a `role: "system"` message.975* `system` and your non-deferred `tools` match the compaction request.976977The simplest way to meet the second is to compact exactly the `messages` of a request you already made. Mid-conversation system messages inside the summarized turns are summarized too, so their instructions and tool changes stop applying after the swap. To keep one in force, state it again in a `role: "system"` message directly after the first new `user` turn that follows the kept turns. A system message placed between the block and the kept turns breaks their thinking.978979The rest of this section covers a summary you write yourself.980981982983Fix: keep the turns exactly as they are and send `prefix_mismatch_behavior: "drop_block"`. The API drops the stale thinking blocks, the model reads the kept turns' `text` and `tool_use` blocks, and the request succeeds.984985Pass the compacted history as `messages` and set `block_binding` on the `thinking` configuration. In the following example, `compacted_messages` is the array your compaction step produced: the summary message followed by the kept turns exactly as the API returned them, `thinking` blocks included:986987<CodeGroup>988 ```bash cURL989 curl https://api.anthropic.com/v1/messages \990 -H "content-type: application/json" \991 -H "x-api-key: $ANTHROPIC_API_KEY" \992 -H "anthropic-version: 2023-06-01" \993 -H "anthropic-beta: thinking-binding-controls-2026-08-01" \994 -d "{995 \"model\": \"claude-fable-5-1\",996 \"max_tokens\": 16000,997 \"thinking\": {998 \"type\": \"adaptive\",999 \"block_binding\": { \"prefix_mismatch_behavior\": \"drop_block\" }1000 },1001 \"messages\": $COMPACTED_MESSAGES1002 }"1003 ```10041005 ```bash CLI1006 ant beta:messages create --beta thinking-binding-controls-2026-08-01 <<YAML1007 model: claude-fable-5-11008 max_tokens: 160001009 thinking:1010 type: adaptive1011 block_binding:1012 prefix_mismatch_behavior: drop_block1013 messages: $COMPACTED_MESSAGES1014 YAML1015 ```10161017 ```python Python1018 client = anthropic.Anthropic()10191020 # compacted_messages: the summary message, then the kept turns as returned1021 response = client.beta.messages.create(1022 model="claude-fable-5-1",1023 max_tokens=16000,1024 thinking={1025 "type": "adaptive",1026 "block_binding": {"prefix_mismatch_behavior": "drop_block"},1027 },1028 messages=compacted_messages,1029 betas=["thinking-binding-controls-2026-08-01"],1030 )10311032 print(response.input_transformations)1033 ```10341035 ```typescript TypeScript1036 const client = new Anthropic();10371038 // compactedMessages: the summary message, then the kept turns as returned1039 const response = await client.beta.messages.create({1040 model: "claude-fable-5-1",1041 max_tokens: 16000,1042 thinking: {1043 type: "adaptive",1044 block_binding: { prefix_mismatch_behavior: "drop_block" }1045 },1046 messages: compactedMessages,1047 betas: ["thinking-binding-controls-2026-08-01"]1048 });10491050 console.log(response.input_transformations);1051 ```10521053 ```csharp C#1054 AnthropicClient client = new();10551056 // compactedMessages: the summary message, then the kept turns as returned1057 var response = await client.Beta.Messages.Create(1058 new()1059 {1060 Model = "claude-fable-5-1",1061 MaxTokens = 16000,1062 Thinking = new BetaThinkingConfigAdaptive1063 {1064 BlockBinding = new()1065 {1066 PrefixMismatchBehavior = BetaThinkingPrefixMismatchBehavior.DropBlock,1067 },1068 },1069 Messages = compactedMessages,1070 Betas = [AnthropicBeta.ThinkingBindingControls2026_08_01],1071 }1072 );10731074 Console.WriteLine(response.InputTransformations?.Count ?? 0);1075 ```10761077 ```go Go1078 client := anthropic.NewClient()10791080 // compactedMessages: the summary message, then the kept turns as returned1081 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1082 Model: "claude-fable-5-1",1083 MaxTokens: 16000,1084 Thinking: anthropic.BetaThinkingConfigParamUnion{1085 OfAdaptive: &anthropic.BetaThinkingConfigAdaptiveParam{1086 BlockBinding: anthropic.BetaThinkingBlockBindingParam{1087 PrefixMismatchBehavior: anthropic.BetaThinkingPrefixMismatchBehaviorDropBlock,1088 },1089 },1090 },1091 Messages: compactedMessages,1092 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaThinkingBindingControls2026_08_01},1093 })1094 if err != nil {1095 log.Fatal(err)1096 }10971098 fmt.Println(len(response.InputTransformations))1099 ```11001101 ```java Java1102 import com.anthropic.models.beta.AnthropicBeta;1103 import com.anthropic.models.beta.messages.BetaMessage;1104 import com.anthropic.models.beta.messages.BetaThinkingBlockBinding;1105 import com.anthropic.models.beta.messages.BetaThinkingConfigAdaptive;1106 import com.anthropic.models.beta.messages.BetaThinkingPrefixMismatchBehavior;1107 import com.anthropic.models.beta.messages.MessageCreateParams;11081109 void main() {1110 AnthropicClient client = AnthropicOkHttpClient.fromEnv();11111112 // compactedMessages: the summary message, then the kept turns as returned1113 MessageCreateParams params = MessageCreateParams.builder()1114 .model("claude-fable-5-1")1115 .maxTokens(16000L)1116 .thinking(BetaThinkingConfigAdaptive.builder()1117 .blockBinding(BetaThinkingBlockBinding.builder()1118 .prefixMismatchBehavior(BetaThinkingPrefixMismatchBehavior.DROP_BLOCK)1119 .build())1120 .build())1121 .messages(compactedMessages)1122 .addBeta(AnthropicBeta.THINKING_BINDING_CONTROLS_2026_08_01)1123 .build();11241125 BetaMessage response = client.beta().messages().create(params);11261127 IO.println(response.inputTransformations());1128 }1129 ```11301131 ```php PHP1132 use Anthropic\Beta\AnthropicBeta;1133 use Anthropic\Beta\Messages\BetaThinkingBlockBinding;1134 use Anthropic\Beta\Messages\BetaThinkingConfigAdaptive;1135 use Anthropic\Beta\Messages\BetaThinkingPrefixMismatchBehavior;1136 use Anthropic\Client;11371138 $client = new Client();11391140 // $compactedMessages: the summary message, then the kept turns as returned1141 $response = $client->beta->messages->create(1142 model: 'claude-fable-5-1',1143 maxTokens: 16000,1144 thinking: BetaThinkingConfigAdaptive::with(1145 blockBinding: BetaThinkingBlockBinding::with(1146 prefixMismatchBehavior: BetaThinkingPrefixMismatchBehavior::DROP_BLOCK,1147 ),1148 ),1149 messages: $compactedMessages,1150 betas: [AnthropicBeta::THINKING_BINDING_CONTROLS_2026_08_01],1151 );11521153 var_dump($response->inputTransformations);1154 ```11551156 ```ruby Ruby1157 client = Anthropic::Client.new11581159 # compacted_messages: the summary message, then the kept turns as returned1160 response = client.beta.messages.create(1161 model: "claude-fable-5-1",1162 max_tokens: 16_000,1163 thinking: {1164 type: "adaptive",1165 block_binding: {prefix_mismatch_behavior: "drop_block"}1166 },1167 messages: compacted_messages,1168 betas: [Anthropic::AnthropicBeta::THINKING_BINDING_CONTROLS_2026_08_01]1169 )11701171 puts response.input_transformations1172 ```1173</CodeGroup>11741175The response carries the new assistant turn as usual, plus one `input_transformations` entry per dropped block. For the history in the diagram, that's the thinking on assistant turns 3 and 4:11761177```json1178{1179 "input_transformations": [1180 {1181 "type": "thinking_dropped",1182 "path": "messages.2.content.0",1183 "reason": "prefix_binding_mismatch"1184 },1185 {1186 "type": "thinking_dropped",1187 "path": "messages.4.content.0",1188 "reason": "prefix_binding_mismatch"1189 }1190 ]1191}1192```11931194Keep sending `"drop_block"` on later requests for as long as those two turns stay in the history. Thinking the model produces from this request onward follows the summary and stays valid. If you'd rather not depend on the beta header, the alternative is to strip the `thinking` and `redacted_thinking` blocks from the kept assistant turns yourself when you build the compacted history.11951196#### Background (async) compaction11971198Background compaction builds the summary off the critical path while the conversation continues, then swaps it in a few requests later. Have the API write the summary with [on-demand compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming):119912001. Send the conversation so far in a separate request with the `compaction` parameter and the `compact-2026-09-04` beta header.12012. Keep working on the full history while that request runs.12023. On the first request after the block arrives, send it in place of the messages the compaction request held, followed by every turn appended since.12031204The thinking produced while the summary was being built stays valid under the same conditions as in [Keep-tail compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#keep-tail-compaction).12051206A summary you build yourself breaks the rule the same way keep-tail does, with a delay: every assistant turn produced while the summary was being built carries thinking that predates the swap, and it all fails the moment the summary lands. If you use one, treat the swap like keep-tail and send `"drop_block"` from the swap onward, or compact synchronously.12071208#### Patterns that don't work with preserved thinking12091210* **Cutting turns out of the middle.** Removing individual turns invalidates every thinking block after them, and no compaction scheme avoids that. If you were cutting a turn to change an instruction, append a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions) instead. To remove old tool results or old thinking selectively, use server-side [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing).1211* **Compacting in the middle of a tool round.** Don't compact between an assistant turn's `tool_use` and the `tool_result` that answers it. Send that assistant turn back with its thinking intact so the model finishes the round with its reasoning. See [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks).12121213### Reference files by ID, not by a URL whose content changes12141215For an `image` or `document` block with a `url` source, the check covers the fetched bytes, not the URL string. A URL whose content changes invalidates later thinking: a "latest screenshot" endpoint, or a document someone edits between turns. A rotating signed URL for the same file doesn't. For content you reference across turns, upload it once with the [Files API](https://platform.claude.com/docs/en/build-with-claude/files) and use the `file_id`, or send base64.12161217### Libraries, proxies, and gateways12181219A library, proxy, or gateway sits between someone else's history and the API, so its own rewrites count as edits, and its users can't see or fix them.12201221* **Pass through what you don't recognize.** Forward the caller's `anthropic-beta` values and `thinking.block_binding` unchanged, and return `input_transformations` to them. An options schema that rejects unknown keys stops your users from choosing `"drop_block"`.1222* **Leave a `role: "system"` message where the caller put it.** Moving it into the top-level `system` field changes `system` on that request and invalidates every thinking block in the conversation.1223* **To turn tool use off for a request, send `tool_choice: {"type": "none"}`.** Don't remove `tools`.1224* **Don't hide the 400.** If your code catches it, strips thinking, and retries on the caller's behalf, log that it did: their history is still edited, and the model loses its earlier reasoning on every later request.12251226## FAQ12271228<AccordionGroup>1229 <Accordion title="Do I need a new account to test preserved thinking?">1230 No. Send the `thinking-binding-controls-2026-08-01` beta header and set `thinking.block_binding.prefix_mismatch_behavior`. Setting the field opts that request into enforcement regardless of account age. `"error"` rejects an edited history with the same 400 a new account gets, and `"drop_block"` lets the request through and lists what was dropped in `input_transformations`. See [Check whether your code edits the prefix](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#how-to-tell-whether-your-integration-is-impacted).1231 </Accordion>12321233 <Accordion title="If anything before a thinking block changes, even one tool description, is the conversation unusable?">1234 No. What fails is the thinking already in the history after the point you changed, and you choose what happens to it. With `prefix_mismatch_behavior: "drop_block"`, the API drops those blocks and the request succeeds: the model answers that turn without that reasoning, and the prompt cache restarts at the edit. With the default `"error"`, the API rejects the request with a 400 until you undo the edit or resend with `"drop_block"`. See [What the API does with an invalid block](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#mismatch-behavior). [What counts as an edit](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#what-counts-as-an-edit) lists which changes matter.1235 </Accordion>12361237 <Accordion title="Does changing effort or other thinking settings between requests invalidate earlier thinking?">1238 No. `output_config.effort`, `max_tokens`, and the `thinking` configuration aren't part of the checked prefix, which covers only `system`, `tools`, and `messages`. A top-level effort change invalidates most of the prompt cache. On Claude Fable 5.1, a [per-message effort](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#effort-changes) change keeps the prompt cache and is used as the new effort level until changed again.1239 </Accordion>12401241 <Accordion title="My tool list changes mid-session. How do I avoid invalidating the conversation?">1242 Don't edit `tools`. Declare the full set at session start, mark tools that aren't available yet with `defer_loading: true`, and offer or withdraw them with `tool_addition` and `tool_removal` blocks. If you learn a tool's schema only mid-session, such as from an MCP server discovered at runtime, you can still append it to `tools` with `defer_loading: true` and offer it the same way. That's safe because an unreferenced deferred tool isn't part of the prefix. The `role: "system"` messages that carry these blocks join the prefix for later thinking, so don't move, reword, or delete them afterward. See [Add or remove tools with `tool_addition` and `tool_removal`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#tool-changes).1243 </Accordion>12441245 <Accordion title="I compact by summarizing older turns and keeping recent turns verbatim. Does that still work?">1246 Yes, if the API writes the summary. [On-demand compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#server-side-trimming) (beta header `compact-2026-09-04`) summarizes the older turns into a signed block that you send in place of them. The recent turns keep their thinking under the conditions in [Keep-tail compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#keep-tail-compaction).12471248 If you write the summary yourself, the kept turns' thinking fails the check, because those blocks were produced against the history you replaced. Strip `thinking` and `redacted_thinking` blocks from the turns you carry across and keep their `text` and `tool_use` blocks, or send `prefix_mismatch_behavior: "drop_block"` and let the API drop them. Simple compaction leaves no thinking behind to fail and is the recommended approach: one summary message plus the next user turn, with no earlier turns replayed. Server-side [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) and [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) don't count as edits. See [Compact on the client](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client).1249 </Accordion>12501251 <Accordion title="How do I handle instruction files such as AGENTS.md or CLAUDE.md that change mid-session?">1252 Load them once at session start and keep the top-level `system` prompt and `tools` fixed. When a file changes, append the new version at that point in `messages` instead of editing the original. Use a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) for instructions that come from you as the operator. For file text you treat as untrusted, which shouldn't carry system-prompt authority, put the content in the next `user` turn instead. See [Add instructions with a mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions) and [Limitations](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#limitations).1253 </Accordion>12541255 <Accordion title="Can I resume a saved session later, after a restart or the next day?">1256 Yes. A resumed session is an ordinary follow-up request: `system`, `tools`, and the earlier `messages` must have the same content as what you last sent. JSON formatting and key order don't matter; the values do. Persist exactly what you sent and received, and replay that: the rendered system prompt, the tool definitions, and each assistant turn as returned. Don't re-render from inputs that might have changed since, such as the date, an updated instruction file, or a new tool version. Anything new goes in an appended message. See [Send assistant turns back exactly as returned](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#append-assistant-turns-exactly-as-returned).1257 </Accordion>12581259 <Accordion title="A saved session now fails on every request. How do I get it working again?">1260 The stored history has an edit in it, so replaying it can't succeed. Send that session with `prefix_mismatch_behavior: "drop_block"` from now on, or remove its `thinking` and `redacted_thinking` blocks once and continue. Thinking the model produces from that point on stays valid as long as nothing before it changes again. Then find the edit so that new sessions don't hit it. See [Handle the error in code](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#handle-the-error-in-code).1261 </Accordion>12621263 <Accordion title="My harness can route a turn to a non-Claude model. Do those turns invalidate Claude's earlier thinking?">1264 No, provided they're appended after the existing history and nothing earlier changes: an assistant message without thinking blocks is an appended message like any other. Send the other model's output as `text` and `tool_use` content.1265 </Accordion>12661267 <Accordion title="Can I carry a conversation's reasoning into a new conversation?">1268 Not into a different conversation. A thinking block is usable only when it follows the exact `system`, `tools`, and `messages` it was produced from. A branch that replays that history unchanged up to the fork point keeps its thinking. A conversation that starts from anything else can't use it, so start that conversation from a summary of the task state, as in [simple compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client): the goal, decisions made, files and results so far, and the next step.1269 </Accordion>1270</AccordionGroup>12711272## Next steps12731274<CardGroup cols={2}>1275 <Card title="Troubleshooting thinking" icon="hammer" href="https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting">1276 Diagnose and fix the most common thinking failures: configuration 400 errors, empty or missing thinking blocks, max\_tokens stops, and cache misses.1277 </Card>12781279 <Card title="Mid-conversation system messages and tool changes" icon="messages" href="https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages">1280 Change system instructions or tool availability partway through a conversation without invalidating the cached prefix that came before them.1281 </Card>12821283 <Card title="Compaction" icon="stack" href="https://platform.claude.com/docs/en/build-with-claude/compaction">1284 Server-side context compaction for managing long conversations that approach context window limits.1285 </Card>12861287 <Card title="Prompt caching" icon="database" href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">1288 Cache prompt prefixes with `cache_control` to cut costs and latency, using automatic caching or explicit breakpoints with 5-minute or 1-hour TTLs.1289 </Card>1290</CardGroup>1291