Repository Public
1---2title: Thinking3url: https://platform.claude.com/docs/en/build-with-claude/thinking4description: "Understand how Claude's thinking works: turn it on, read thinking output, steer thinking depth with effort, and use thinking with tools, caching, and streaming."5---67<Note>8 To learn how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).9</Note>1011A model that answers in a single pass has to get everything right on the first try: no scratch work, no checking, no changing course halfway through. For a proof, a tricky bug, or a long agentic task, the first approach is often not the best one.1213Thinking removes that constraint. When thinking is active, Claude works through the problem in its own words before answering: it restates what is being asked, tries approaches, checks intermediate results, and abandons paths that do not hold up. That reasoning arrives in `thinking` content blocks ahead of the response, and Claude draws on it to produce the final answer. This is why thinking improves performance on complex tasks like math, coding, analysis, and long-running agentic work, where the quality of the answer depends on intermediate work that would otherwise be compressed into the response itself or skipped.1415Thinking has a cost: the tokens Claude spends reasoning are billed as output tokens, even when the thinking text isn't returned to you, and they count toward `max_tokens` alongside the response text. This page covers how thinking behaves across the API surface: turning it on, reading its output, and managing its interactions with tools, streaming, caching, and the context window.1617## How thinking works18192021Whether Claude thinks on a given request, and how deeply, depends on your thinking configuration and the complexity of the request.2223Here is what thinking looks like in a response: one or more `thinking` content blocks arrive before the `text` blocks. The thinking block is still generated content, like the `text` block that follows it, but it is separated from the canonical response. Each thinking block also carries a `signature` field, an encrypted copy of the full reasoning that you pass back unchanged in multi-turn and tool-use conversations (see [Thinking encryption](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-encryption)):2425```json26{27 "content": [28 {29 "type": "thinking",30 "thinking": "Let me break this down. The question has two parts, so I'll start with the simpler one and use its result to constrain the second...",31 "signature": "WaUjzkypQ2mUEVM36O2Txu...."32 },33 {34 "type": "text",35 "text": "Based on my analysis..."36 }37 ]38}39```4041You don't always see this text, and what you see is never the raw chain of thought: the text in a thinking block is a [summary of Claude's reasoning](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking). The `display` field on the thinking configuration controls whether that summary is returned at all: `"summarized"` returns it, while `"omitted"`, the default on many models, returns thinking blocks with an empty `thinking` field. Either way the block is billed the same and passed back the same in multi-turn conversations. See [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) for per-model defaults and details.4243If Claude uses tools, thinking can also appear between tool calls. See [Thinking with tool use](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use). For the full response format, see the [Messages API reference](https://platform.claude.com/docs/en/api/messages/create).4445## Configuring thinking4647On most models, thinking is on by default or one parameter away. Which configuration each model accepts, and what it defaults to, is listed in the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#supported-models) on the Troubleshooting page.4849On Claude Opus 5, Claude Sonnet 5, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, and Claude Mythos Preview, thinking is already on and needs no configuration. `display` defaults to `"omitted"` on these models, so the thinking text is hidden until you opt in. Opt in with `thinking: {"type": "adaptive", "display": "summarized"}`, which is exactly the following request with the [model string](https://platform.claude.com/docs/en/models/overview) swapped.5051On Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, and Claude Sonnet 4.6, thinking is off until you set `thinking: {type: "adaptive"}`, which lets Claude decide when and how deeply to think based on the request. The following examples do that, set `display: "summarized"` so the thinking text is visible, and use a roomy `max_tokens`:5253<CodeGroup>54 ```bash cURL55 curl https://api.anthropic.com/v1/messages \56 -H "x-api-key: $ANTHROPIC_API_KEY" \57 -H "anthropic-version: 2023-06-01" \58 -H "content-type: application/json" \59 -d '{60 "model": "claude-opus-4-8",61 "max_tokens": 16000,62 "thinking": {63 "type": "adaptive",64 "display": "summarized"65 },66 "messages": [67 {68 "role": "user",69 "content": "What is the greatest common divisor of 1071 and 462?"70 }71 ]72 }'73 ```7475 ```bash CLI76 ant messages create \77 --model claude-opus-4-8 \78 --max-tokens 16000 \79 --thinking '{type: adaptive, display: summarized}' \80 --message '{role: user, content: "What is the greatest common divisor of 1071 and 462?"}' \81 --transform content \82 --format yaml83 ```8485 ```python Python86 client = anthropic.Anthropic()8788 response = client.messages.create(89 model="claude-opus-4-8",90 max_tokens=16000,91 thinking={"type": "adaptive", "display": "summarized"},92 messages=[93 {94 "role": "user",95 "content": "What is the greatest common divisor of 1071 and 462?",96 }97 ],98 )99100 for block in response.content:101 match block.type:102 case "thinking":103 print(f"\nThinking: {block.thinking}")104 case "text":105 print(f"\nResponse: {block.text}")106 ```107108 ```typescript TypeScript109 const client = new Anthropic();110111 const response = await client.messages.create({112 model: "claude-opus-4-8",113 max_tokens: 16000,114 thinking: {115 type: "adaptive",116 display: "summarized"117 },118 messages: [119 {120 role: "user",121 content: "What is the greatest common divisor of 1071 and 462?"122 }123 ]124 });125126 for (const block of response.content) {127 switch (block.type) {128 case "thinking":129 console.log(`\nThinking: ${block.thinking}`);130 break;131 case "text":132 console.log(`\nResponse: ${block.text}`);133 break;134 }135 }136 ```137138 ```csharp C#139 AnthropicClient client = new();140141 var parameters = new MessageCreateParams142 {143 Model = Model.ClaudeOpus4_8,144 MaxTokens = 16000,145 Thinking = new ThinkingConfigAdaptive { Display = Display.Summarized },146 Messages = [147 new() {148 Role = Role.User,149 Content = "What is the greatest common divisor of 1071 and 462?"150 }151 ]152 };153154 var message = await client.Messages.Create(parameters);155156 foreach (var block in message.Content)157 {158 if (block.TryPickThinking(out ThinkingBlock? thinking))159 {160 Console.WriteLine($"\nThinking: {thinking.Thinking}");161 }162 else if (block.TryPickText(out TextBlock? text))163 {164 Console.WriteLine($"\nResponse: {text.Text}");165 }166 }167 ```168169 ```go Go170 client := anthropic.NewClient()171172 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{173 Model: anthropic.ModelClaudeOpus4_8,174 MaxTokens: 16000,175 Thinking: anthropic.ThinkingConfigParamUnion{176 OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{177 Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized,178 },179 },180 Messages: []anthropic.MessageParam{181 anthropic.NewUserMessage(anthropic.NewTextBlock("What is the greatest common divisor of 1071 and 462?")),182 },183 })184 if err != nil {185 log.Fatal(err)186 }187188 for _, block := range response.Content {189 switch v := block.AsAny().(type) {190 case anthropic.ThinkingBlock:191 fmt.Printf("\nThinking: %s", v.Thinking)192 case anthropic.TextBlock:193 fmt.Printf("\nResponse: %s", v.Text)194 }195 }196 ```197198 ```java Java199 import com.anthropic.models.messages.ThinkingConfigAdaptive;200201 void main() {202 AnthropicClient client = AnthropicOkHttpClient.fromEnv();203204 MessageCreateParams params = MessageCreateParams.builder()205 .model(Model.CLAUDE_OPUS_4_8)206 .maxTokens(16000L)207 .thinking(ThinkingConfigAdaptive.builder()208 .display(ThinkingConfigAdaptive.Display.SUMMARIZED)209 .build())210 .addUserMessage("What is the greatest common divisor of 1071 and 462?")211 .build();212213 Message response = client.messages().create(params);214215 response.content().forEach(block -> {216 block.thinking().ifPresent(thinkingBlock ->217 IO.println("\nThinking: " + thinkingBlock.thinking())218 );219 block.text().ifPresent(textBlock ->220 IO.println("\nResponse: " + textBlock.text())221 );222 });223 }224 ```225226 ```php PHP227 use Anthropic\Messages\TextBlock;228 use Anthropic\Messages\ThinkingBlock;229230 $client = new Client();231232 $message = $client->messages->create(233 maxTokens: 16000,234 messages: [235 [236 'role' => 'user',237 'content' => 'What is the greatest common divisor of 1071 and 462?'238 ]239 ],240 model: 'claude-opus-4-8',241 thinking: ['type' => 'adaptive', 'display' => 'summarized'],242 );243244 foreach ($message->content as $block) {245 switch (true) {246 case $block instanceof ThinkingBlock:247 echo "\nThinking: " . $block->thinking;248 break;249 case $block instanceof TextBlock:250 echo "\nResponse: " . $block->text;251 break;252 }253 }254 ```255256 ```ruby Ruby257 client = Anthropic::Client.new258259 message = client.messages.create(260 model: "claude-opus-4-8",261 max_tokens: 16000,262 thinking: {263 type: "adaptive",264 display: "summarized"265 },266 messages: [267 {268 role: "user",269 content: "What is the greatest common divisor of 1071 and 462?"270 }271 ]272 )273274 message.content.each do |block|275 case block276 when Anthropic::Models::ThinkingBlock277 puts "\nThinking: #{block.thinking}"278 when Anthropic::Models::TextBlock279 puts "\nResponse: #{block.text}"280 end281 end282 ```283</CodeGroup>284285Running the example prints the summarized thinking, then the answer:286287```text Output wrap288Thinking: Use Euclidean algorithm.2891071 = 2*462 + 147290462 = 3*147 + 21291147 = 7*21 + 0292GCD = 21293294Response: ## Finding GCD of 1071 and 462295296I'll use the **Euclidean algorithm**, repeatedly dividing and taking remainders...297```298299Thinking tokens count toward `max_tokens`, so set it high enough to leave room for both the thinking and the response text. See [Cost control](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#cost-control) on the steering page and [Thinking and the context window](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-the-context-window).300301### Turning thinking off302303On Claude Sonnet 5, where thinking is on by default, you can turn it off:304305<CodeGroup>306 ```bash cURL307 curl https://api.anthropic.com/v1/messages \308 -H "x-api-key: $ANTHROPIC_API_KEY" \309 -H "anthropic-version: 2023-06-01" \310 -H "content-type: application/json" \311 -d '{312 "model": "claude-sonnet-5",313 "max_tokens": 4096,314 "thinking": {"type": "disabled"},315 "messages": [316 {317 "role": "user",318 "content": "Summarize this article in one sentence."319 }320 ]321 }'322 ```323324 ```bash CLI325 ant messages create \326 --model claude-sonnet-5 \327 --max-tokens 4096 \328 --thinking '{type: disabled}' \329 --message '{role: user, content: "Summarize this article in one sentence."}'330 ```331332 ```python Python333 client = anthropic.Anthropic()334335 response = client.messages.create(336 model="claude-sonnet-5",337 max_tokens=4096,338 thinking={"type": "disabled"},339 messages=[{"role": "user", "content": "Summarize this article in one sentence."}],340 )341 ```342343 ```typescript TypeScript344 const client = new Anthropic();345346 const response = await client.messages.create({347 model: "claude-sonnet-5",348 max_tokens: 4096,349 thinking: { type: "disabled" },350 messages: [{ role: "user", content: "Summarize this article in one sentence." }]351 });352 ```353354 ```csharp C#355 AnthropicClient client = new();356357 var parameters = new MessageCreateParams358 {359 Model = Model.ClaudeSonnet5,360 MaxTokens = 4096,361 Thinking = new ThinkingConfigDisabled(),362 Messages = [363 new() {364 Role = Role.User,365 Content = "Summarize this article in one sentence."366 }367 ]368 };369370 var message = await client.Messages.Create(parameters);371 ```372373 ```go Go374 client := anthropic.NewClient()375376 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{377 Model: anthropic.ModelClaudeSonnet5,378 MaxTokens: 4096,379 Thinking: anthropic.ThinkingConfigParamUnion{380 OfDisabled: &anthropic.ThinkingConfigDisabledParam{},381 },382 Messages: []anthropic.MessageParam{383 anthropic.NewUserMessage(anthropic.NewTextBlock("Summarize this article in one sentence.")),384 },385 })386 if err != nil {387 log.Fatal(err)388 }389 ```390391 ```java Java392 import com.anthropic.models.messages.ThinkingConfigDisabled;393394 void main() {395 AnthropicClient client = AnthropicOkHttpClient.fromEnv();396397 MessageCreateParams params = MessageCreateParams.builder()398 .model(Model.CLAUDE_SONNET_5)399 .maxTokens(4096L)400 .thinking(ThinkingConfigDisabled.builder().build())401 .addUserMessage("Summarize this article in one sentence.")402 .build();403404 Message response = client.messages().create(params);405 }406 ```407408 ```php PHP409 $client = new Client();410411 $message = $client->messages->create(412 maxTokens: 4096,413 messages: [414 [415 'role' => 'user',416 'content' => 'Summarize this article in one sentence.'417 ]418 ],419 model: 'claude-sonnet-5',420 thinking: ['type' => 'disabled'],421 );422 ```423424 ```ruby Ruby425 client = Anthropic::Client.new426427 message = client.messages.create(428 model: "claude-sonnet-5",429 max_tokens: 4096,430 thinking: { type: "disabled" },431 messages: [432 {433 role: "user",434 content: "Summarize this article in one sentence."435 }436 ]437 )438 ```439</CodeGroup>440441Claude Opus 5 also has thinking on by default and accepts `thinking: {type: "disabled"}` at [effort](https://platform.claude.com/docs/en/build-with-claude/effort) `high` or below. At `xhigh` or `max` effort, thinking cannot be turned off: requests that combine `thinking: {type: "disabled"}` with those effort levels return a 400 error. This restriction applies to Claude Opus 5 and later models and is enforced on each request. With thinking disabled, Claude Opus 5 can occasionally emit tool calls as plain text or include internal XML tags in its visible output. See [Running with thinking disabled](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#running-with-thinking-disabled) for prompting mitigations.442443Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, and Claude Mythos Preview reject `thinking: {type: "disabled"}`. Thinking can't be turned off on these models.444445If your model supports only extended thinking (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#supported-models)), configure it with `type: "enabled"` and a `budget_tokens` value instead. The [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) page covers that configuration. And if any thinking configuration comes back with a 400 error, [Troubleshooting thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting) matches each error message to its fix.446447## Reading thinking output448449### Controlling thinking display450451The `display` field on the thinking configuration controls how thinking content is returned in API responses. `display` works in both modes: set it alongside `type: "adaptive"` or `type: "enabled"`. It accepts these values:452453* `"summarized"`: thinking blocks contain [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) text, a readable summary of Claude's reasoning. This is the default on Claude Opus 4.6, Claude Sonnet 4.6, and earlier models.454* `"omitted"`: thinking blocks are returned with an empty `thinking` field. The `signature` field still carries the encrypted full thinking for multi-turn continuity (see [Thinking encryption](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-encryption)). This is the default on Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, Claude Opus 5, Claude Sonnet 5, Claude Opus 4.8, Claude Opus 4.7, and [Claude Mythos Preview](https://anthropic.com/glasswing).455* `"updates"` (beta): reasoning blocks are returned with an empty `thinking` field, as with `"omitted"`, and the short [progress updates](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates) some models write between tool calls come back as readable text. Requires the beta header `thinking-display-updates-2026-08-18`.456457Set `display: "omitted"` when your application doesn't surface thinking content to users. The primary benefit is faster time-to-first-text-token when streaming: the server skips streaming thinking tokens entirely and delivers only the signature, so the final text response begins streaming sooner.458459With `display: "omitted"`, the response contains `thinking` blocks with an empty `thinking` field:460461```json Output462{463 "content": [464 {465 "type": "thinking",466 "thinking": "",467 "signature": "EosnCkYICxIMMb3LzNrMu..."468 },469 {470 "type": "text",471 "text": "The answer is 12,231."472 }473 ]474}475```476477Keep the following in mind when working with omitted thinking:478479* You're still charged for the full thinking tokens. Omitting reduces latency, not cost.480* If you pass thinking blocks back in multi-turn conversations, pass them unchanged. The server decrypts the `signature` to reconstruct the original thinking for prompt construction (see [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks)). Any text you place in the `thinking` field of a round-tripped omitted block is ignored.481* `display` is invalid with `thinking.type: "disabled"` (there is nothing to display).482* When using `thinking.type: "adaptive"` and the model skips thinking for a simple request, no thinking block is produced regardless of `display`.483* When streaming with `display: "omitted"`, no thinking text is streamed. Each thinking block streams a `thinking_delta` with an empty `thinking` string, then its `signature_delta`. With `display: "updates"`, only [progress-update blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates) stream `thinking_delta` events that carry text. See [Streaming thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#streaming-thinking) for the event sequence.484485<Note>486 The `signature` field is identical whichever `display` value you set. Switching `display` values between turns in a conversation is supported.487</Note>488489In the Ruby SDK, plain hashes take `display:` as the examples show. The typed `ThinkingConfigAdaptive` class names the parameter `display_` (trailing underscore, to avoid shadowing Ruby's `Kernel#display`). Either way, the wire field is still `display`.490491### Summarized thinking492493When `display` is `"summarized"`, the thinking text you receive is a summary of Claude's full thinking process rather than the raw chain of thought. Summarized thinking provides the full intelligence benefits of thinking while preventing misuse. No `display` setting returns the raw chain of thought.494495Keep the following in mind when working with summarized thinking:496497* You're charged for the full thinking tokens generated by the original request, not the summary tokens. The billed output token count does not match the count of tokens you see in the response.498* On Claude Opus 4.6, Claude Sonnet 4.6, and earlier models, the first few lines of thinking output are more verbose, providing detailed reasoning that's particularly helpful for prompt engineering purposes. [Claude Mythos Preview](https://anthropic.com/glasswing) summarizes from the first token, so its thinking blocks do not show this verbose preamble.499* Summarization preserves the key ideas of Claude's thinking process with minimal added latency, so summaries can stream as they arrive.500* Summarization is processed by a different model from the one you target in your requests. The thinking model does not see the summarized output.501* As Anthropic seeks to improve the thinking feature, summarization behavior is subject to change.502503<Note>504 In rare cases where you need access to full thinking output, [contact Anthropic sales](mailto:sales@anthropic.com).505</Note>506507To see the model's reasoning, read the `thinking` blocks rather than prompting for reasoning in the response text. On Claude Fable 5.1 and Claude Fable 5, a request that attempts to elicit the model's internal reasoning as part of the response text can be refused with `stop_details.category: "reasoning_extraction"`. See [Refusal categories](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response) for the field reference and handling guidance.508509### Streaming thinking510511Thinking works with [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming). Thinking blocks stream as `thinking_delta` events inside `content_block_delta` events, followed by a single `signature_delta` event just before the block's `content_block_stop`. Text blocks stream afterward as usual.512513514515The following examples stream a response with adaptive thinking, printing thinking and text deltas as they arrive:516517<CodeGroup>518 ```bash cURL519 curl https://api.anthropic.com/v1/messages \520 -H "x-api-key: $ANTHROPIC_API_KEY" \521 -H "anthropic-version: 2023-06-01" \522 -H "content-type: application/json" \523 -d '{524 "model": "claude-opus-4-8",525 "max_tokens": 16000,526 "stream": true,527 "thinking": {528 "type": "adaptive",529 "display": "summarized"530 },531 "messages": [532 {533 "role": "user",534 "content": "What is the greatest common divisor of 1071 and 462?"535 }536 ]537 }'538 ```539540 ```bash CLI541 ant messages create \542 --model claude-opus-4-8 \543 --max-tokens 16000 \544 --thinking '{type: adaptive, display: summarized}' \545 --message '{role: user, content: "What is the greatest common divisor of 1071 and 462?"}' \546 --stream \547 --format jsonl548 ```549550 ```python Python551 client = anthropic.Anthropic()552553 with client.messages.stream(554 model="claude-opus-4-8",555 max_tokens=16000,556 thinking={"type": "adaptive", "display": "summarized"},557 messages=[558 {559 "role": "user",560 "content": "What is the greatest common divisor of 1071 and 462?",561 }562 ],563 ) as stream:564 for event in stream:565 match event.type:566 case "content_block_start":567 print(f"\nStarting {event.content_block.type} block...")568 case "content_block_delta":569 delta = event.delta570 match delta.type:571 case "thinking_delta":572 print(delta.thinking, end="", flush=True)573 case "text_delta":574 print(delta.text, end="", flush=True)575 ```576577 ```typescript TypeScript578 const client = new Anthropic();579580 const stream = client.messages.stream({581 model: "claude-opus-4-8",582 max_tokens: 16000,583 thinking: { type: "adaptive", display: "summarized" },584 messages: [{ role: "user", content: "What is the greatest common divisor of 1071 and 462?" }]585 });586587 for await (const event of stream) {588 switch (event.type) {589 case "content_block_start":590 console.log(`\nStarting ${event.content_block.type} block...`);591 break;592 case "content_block_delta":593 switch (event.delta.type) {594 case "thinking_delta":595 process.stdout.write(event.delta.thinking);596 break;597 case "text_delta":598 process.stdout.write(event.delta.text);599 break;600 }601 break;602 }603 }604 ```605606 ```csharp C#607 AnthropicClient client = new();608609 var parameters = new MessageCreateParams610 {611 Model = Model.ClaudeOpus4_8,612 MaxTokens = 16000,613 Thinking = new ThinkingConfigAdaptive { Display = Display.Summarized },614 Messages = [new() { Role = Role.User, Content = "What is the greatest common divisor of 1071 and 462?" }]615 };616617 await foreach (var rawEvent in client.Messages.CreateStreaming(parameters))618 {619 if (rawEvent.TryPickContentBlockStart(out var start))620 {621 Console.WriteLine($"\nStarting {start.ContentBlock.Type} block...");622 }623 else if (rawEvent.TryPickContentBlockDelta(out var delta))624 {625 if (delta.Delta.TryPickThinking(out var thinkingDelta))626 {627 Console.Write(thinkingDelta.Thinking);628 }629 else if (delta.Delta.TryPickText(out var textDelta))630 {631 Console.Write(textDelta.Text);632 }633 }634 }635 ```636637 ```go Go638 client := anthropic.NewClient()639640 stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{641 Model: anthropic.ModelClaudeOpus4_8,642 MaxTokens: 16000,643 Thinking: anthropic.ThinkingConfigParamUnion{644 OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{645 Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized,646 },647 },648 Messages: []anthropic.MessageParam{649 anthropic.NewUserMessage(anthropic.NewTextBlock("What is the greatest common divisor of 1071 and 462?")),650 },651 })652653 for stream.Next() {654 event := stream.Current()655 switch eventVariant := event.AsAny().(type) {656 case anthropic.ContentBlockStartEvent:657 fmt.Printf("\nStarting %s block...\n", eventVariant.ContentBlock.Type)658 case anthropic.ContentBlockDeltaEvent:659 switch deltaVariant := eventVariant.Delta.AsAny().(type) {660 case anthropic.ThinkingDelta:661 fmt.Print(deltaVariant.Thinking)662 case anthropic.TextDelta:663 fmt.Print(deltaVariant.Text)664 }665 }666 }667 if err := stream.Err(); err != nil {668 log.Fatal(err)669 }670 ```671672 ```java Java673 import com.anthropic.models.messages.ThinkingConfigAdaptive;674675 void main() {676 AnthropicClient client = AnthropicOkHttpClient.fromEnv();677678 MessageCreateParams params = MessageCreateParams.builder()679 .model(Model.CLAUDE_OPUS_4_8)680 .maxTokens(16000L)681 .thinking(ThinkingConfigAdaptive.builder()682 .display(ThinkingConfigAdaptive.Display.SUMMARIZED)683 .build())684 .addUserMessage("What is the greatest common divisor of 1071 and 462?")685 .build();686687 try (var streamResponse = client.messages().createStreaming(params)) {688 streamResponse.stream().forEach(event -> {689 switch (event.type().value()) {690 case CONTENT_BLOCK_START -> {691 var startEvent = event.asContentBlockStart();692 var block = startEvent.contentBlock();693 switch (block.type().value()) {694 case THINKING -> IO.println("\nStarting thinking block...");695 case TEXT -> IO.println("\nStarting text block...");696 }697 }698 case CONTENT_BLOCK_DELTA -> {699 var deltaEvent = event.asContentBlockDelta();700 deltaEvent.delta().thinking().ifPresent(td ->701 IO.print(td.thinking())702 );703 deltaEvent.delta().text().ifPresent(td ->704 IO.print(td.text())705 );706 }707 }708 });709 }710 }711 ```712713 ```php PHP714 use Anthropic\Messages\RawContentBlockDeltaEvent;715 use Anthropic\Messages\RawContentBlockStartEvent;716 use Anthropic\Messages\TextDelta;717 use Anthropic\Messages\ThinkingDelta;718719 $client = new Client();720721 $stream = $client->messages->createStream(722 maxTokens: 16000,723 messages: [724 ['role' => 'user', 'content' => 'What is the greatest common divisor of 1071 and 462?']725 ],726 model: 'claude-opus-4-8',727 thinking: ['type' => 'adaptive', 'display' => 'summarized'],728 );729730 foreach ($stream as $event) {731 switch (true) {732 case $event instanceof RawContentBlockStartEvent:733 echo "\nStarting {$event->contentBlock->type} block...\n";734 break;735 case $event instanceof RawContentBlockDeltaEvent:736 switch (true) {737 case $event->delta instanceof ThinkingDelta:738 echo $event->delta->thinking;739 break;740 case $event->delta instanceof TextDelta:741 echo $event->delta->text;742 break;743 }744 break;745 }746 }747 ```748749 ```ruby Ruby750 client = Anthropic::Client.new751752 stream = client.messages.stream(753 model: "claude-opus-4-8",754 max_tokens: 16000,755 thinking: { type: "adaptive", display: "summarized" },756 messages: [757 { role: "user", content: "What is the greatest common divisor of 1071 and 462?" }758 ]759 )760761 stream.each do |event|762 case event763 when Anthropic::Streaming::ThinkingEvent764 print event.thinking765 when Anthropic::Streaming::TextEvent766 print event.text767 end768 end769 ```770</CodeGroup>771772To reassemble complete thinking blocks with their signatures after streaming, use your SDK's message-accumulation helper where one exists (for example, `stream.get_final_message()` in Python or `stream.finalMessage()` in TypeScript) instead of concatenating deltas yourself.773774<Accordion title="Full streaming event trace">775 ```sse Output776 event: message_start777 data: {"type": "message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-8", "stop_reason": null, "stop_sequence": null}}778779 event: content_block_start780 data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}781782 event: content_block_delta783 data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 × 462 + 147"}}784785 event: content_block_delta786 data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n462 = 3 × 147 + 21\n147 = 7 × 21 + 0\n\nSo GCD(1071, 462) = 21"}}787788 // Additional thinking deltas...789790 event: content_block_delta791 data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b..."}}792793 event: content_block_stop794 data: {"type": "content_block_stop", "index": 0}795796 event: content_block_start797 data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}798799 event: content_block_delta800 data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "The greatest common divisor of 1071 and 462 is **21**."}}801802 // Additional text deltas...803804 event: content_block_stop805 data: {"type": "content_block_stop", "index": 1}806807 event: message_delta808 data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}809810 event: message_stop811 data: {"type": "message_stop"}812 ```813</Accordion>814815When `display: "omitted"` is set, the thinking block opens, a `thinking_delta` with an empty `thinking` string arrives, a single `signature_delta` follows, and the block closes. Text streaming begins immediately after:816817```sse Output818event: content_block_start819data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}820821event: content_block_delta822data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":""}}823824event: content_block_delta825data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"EosnCkYICxIMMb3LzNrMu..."}}826827event: content_block_stop828data: {"type":"content_block_stop","index":0}829830event: content_block_start831data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}832```833834With `display: "updates"` (beta), reasoning blocks stream as they do under `"omitted"`. Each [progress-update block](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates) streams its text as `thinking_delta` events before the `tool_use` block it introduces. A pause of several seconds before the progress-update block opens is normal:835836```sse Output837event: content_block_start838data: {"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":"","signature":""}}839840event: content_block_delta841data: {"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"Confirmed the retry path never refreshes the expired token. Editing auth.py to add the refresh call."}}842843event: content_block_delta844data: {"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":"Es8CCkYICxIM..."}}845846event: content_block_stop847data: {"type":"content_block_stop","index":1}848849event: content_block_start850data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_01D7FLrfh4GYq7yT1ULFeyMV","name":"edit_file","input":{}}}851```852853Under `"updates"`, treat a block as a progress update as soon as one of its `thinking_delta` events carries non-empty text.854855<Note>856 When using streaming with thinking enabled, you might notice that text sometimes arrives in larger chunks alternating with smaller, token-by-token delivery. This is expected behavior, especially for thinking content.857858 The streaming system processes content in batches, which can delay and group streaming events into this "chunky" delivery pattern.859</Note>860861For general streaming mechanics, see [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming).862863## Thinking and effort864865The `thinking` parameter controls whether Claude thinks in [thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking) before answering; the `effort` parameter controls how much work Claude puts into the whole response, which in adaptive mode includes how often and how deeply it thinks. Don't pass `adaptive` as an `effort` value: `adaptive` is a thinking mode, not an effort level.866867To learn what each effort level does to thinking behavior, see the [per-level thinking behavior table](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#effort-levels) on the [Steering thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost) page. The [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) page documents the parameter itself, including which levels each model supports. On Claude Opus 4.5, the only extended-thinking-only model that supports effort, effort composes with `budget_tokens`. See [Budget rules and tuning](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#budget-rules-and-tuning).868869With the two controls separated this way, pick the one that matches your goal:870871* **Lower cost or latency on a thinking-enabled workload:** lower `effort` first. It scales the whole response down, thinking included.872* **Claude is thinking too rarely or too shallowly:** raise `effort`, or see [Steering how often Claude thinks](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#tuning-thinking-behavior) on the steering page.873* **You need thinking fully off:** use `thinking: {type: "disabled"}` on models that allow it (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#supported-models)).874* **You need a hard ceiling on spend:** use `max_tokens`. Effort is soft guidance. `max_tokens` is a strict limit.875876## Thinking with tool use877878Thinking works alongside [tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview), letting Claude reason through tool selection and process tool results. Two constraints apply:8798801. **Tool choice limitation (manual mode):** tool use with manual extended thinking (`thinking: {type: "enabled"}`) only supports `tool_choice: {"type": "auto"}` (the default) or `tool_choice: {"type": "none"}`. Using `tool_choice: {"type": "any"}` or `tool_choice: {"type": "tool", "name": "..."}` results in an error because these options force tool use, which is incompatible with manual extended thinking. Adaptive thinking, including on models where thinking is on by default, supports forced tool use, except on Claude Fable 5.1 and Claude Mythos 5.1 (see [Response prefill and forced tool use](https://platform.claude.com/docs/en/build-with-claude/thinking#limits-and-feature-compatibility)).8812. **Preserving thinking blocks:** when you return tool results, you must pass the thinking blocks from the assistant message back to the API, complete and unmodified. See [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks).882883**A tool-use loop is one assistant turn.** From the model's perspective, an assistant turn doesn't complete until Claude finishes its full response, which may include multiple tool calls and results. This whole sequence is a single assistant turn:884885```text wrap886User: "What's the weather in Paris?"887Assistant: [thinking] + [tool_use: get_weather]888User: [tool_result: "20°C, sunny"]889Assistant: [text: "The weather in Paris is 20°C and sunny"]890```891892The entire turn runs in a single thinking mode: you can't toggle thinking in the middle of a turn, including during the tool-use loop. In extended (manual) mode, the API additionally enforces that the final assistant turn of a thinking-enabled request begins with a thinking block. Adaptive mode relaxes this: no assistant turn needs to start with one.893894**Mid-turn conflicts degrade gracefully.** If you toggle thinking mid-turn (for example, between sending a tool call and returning its result), the API doesn't error. Instead, it silently disables thinking for that request. To preserve model quality, the API may strip thinking blocks that would create an invalid turn structure, or disable thinking when the conversation history is incompatible with thinking being enabled. To confirm whether thinking was active, check for the presence of `thinking` blocks in the response.895896**Toggle between turns, not within them.** Plan your thinking strategy at the start of each turn. Complete the assistant turn, then change the thinking configuration for the next one:897898```text wrap899User: "What's the weather?"900Assistant: [tool_use] (thinking disabled)901User: [tool_result]902Assistant: [text: "It's sunny"]903User: "What about tomorrow?"904Assistant: [thinking] + [text: "..."] (thinking enabled - new turn)905```906907Toggling thinking modes also invalidates prompt caching. See [Thinking and prompt caching](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching).908909### Preserving thinking blocks910911When Claude invokes a tool, it pauses construction of its response to await external information. When you return the tool result, Claude continues building that same response, so its earlier reasoning must still be present. Pass every `thinking` block back to the API complete and unmodified, alongside the `tool_use` block it accompanied. This matters for two reasons:9129131. **Reasoning continuity:** the thinking blocks capture the step-by-step reasoning that led to the tool requests. Including them lets Claude continue reasoning from where it left off.9142. **Context maintenance:** tool results appear as user messages in the API structure, but they're part of one continuous reasoning flow. Preserving thinking blocks maintains that flow across API calls.915916In short:917918* **Required:** within a tool-use turn, pass thinking blocks back.919* **Recommended:** across turns, pass everything back.920* **Allowed:** outside tool use, omit prior turns' thinking.921922You don't need to prune old thinking yourself. Pass all thinking blocks back in multi-turn conversations, and the API automatically filters them, keeps the blocks needed to preserve the model's reasoning, and bills input tokens only for the blocks actually shown to Claude. Which prior-turn blocks are kept is per-model. See [Thinking block preservation by model](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model). To override the default, use the [`clear_thinking_20251015` context-editing strategy](https://platform.claude.com/docs/en/build-with-claude/context-editing#thinking-block-clearing).923924Within the latest assistant message, the sequence of consecutive `thinking` blocks must match what the model generated in the original request: you can't rearrange, edit, or partially drop them. This includes [`redacted_thinking` blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#redacted-thinking-blocks).925926<Note>927 Modified thinking blocks are rejected with a 400 error. See [A 400 error says thinking blocks cannot be modified](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#error-thinking-blocks-modified) for the exact message, the common causes, and the fix. The one exception: text placed in the empty `thinking` field of an [omitted](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) block is ignored rather than rejected.928</Note>929930For a complete two-turn walkthrough with code in every SDK, see [Thinking in tool and multi-turn workflows](https://platform.claude.com/docs/en/build-with-claude/thinking-tool-workflows#two-turn-tool-use-round-trip). It defines a tool, receives a thinking-plus-tool-use response, and echoes the assistant turn back with the tool result.931932### Interleaved thinking933934Interleaved thinking lets Claude think between tool calls, reasoning about each tool result before acting on it. With interleaved thinking, Claude can:935936* Reason about the results of a tool call before deciding what to do next937* Chain multiple tool calls with reasoning steps in between938* Make more nuanced decisions based on intermediate results939940<Note>941 Consecutive tool calls do not require interleaved thinking. Claude can chain tool calls with or without interleaved thinking. Interleaving changes where thinking blocks appear between tool calls, not whether tool calls can chain.942</Note>943944With adaptive thinking, interleaved thinking is automatic on every model that supports adaptive thinking. No beta header is needed. 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, and Claude Opus 4.7, reasoning between tool calls always appears in thinking blocks. Claude Haiku 4.5 does not support interleaved thinking. On models using manual extended thinking, interleaving requires a beta header and changes how the thinking budget is counted. [Interleaved thinking in manual mode](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) covers the per-model rules and platform-specific header behavior.945946With interleaved thinking, the thinking allocation can span the entire assistant turn rather than a single response. Interleaved thinking is only supported for [tools used through the Messages API](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).947948For a worked comparison showing what interleaved thinking changes in a two-tool workflow, see [How interleaved thinking changes the flow](https://platform.claude.com/docs/en/build-with-claude/thinking-tool-workflows#how-interleaved-thinking-changes-the-flow).949950### Progress updates between tool calls951952On Claude Fable 5.1, Claude Mythos 5.1, and Claude Fable 5, the model can write a progress update between tool calls. A progress update is a sentence or two on what the model just found and what it's about to do next, written for the person watching the agent rather than as reasoning. Each one comes back as its own `thinking` block with its own `signature`, separate from any reasoning block at the same point. It sits immediately before the `tool_use` or `server_tool_use` block it introduces. At most one progress update precedes each tool call, and the model can skip any of them. Progress updates aren't [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking): they appear whether or not reasoning blocks appear between tool calls, and a response can contain both.953954What a progress-update block contains depends on [`display`](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display):955956| `display` | Reasoning blocks | Progress-update blocks |957| ----------------------------------------- | ---------------------- | -------------------------------------------------------- |958| `"omitted"` (the default on these models) | Empty `thinking` field | Empty `thinking` field |959| `"updates"` (beta) | Empty `thinking` field | Summary text |960| `"summarized"` | Summary text | Summary text, not distinguishable from a reasoning block |961962Use `display: "updates"` for an agent interface that keeps reasoning hidden and shows the user a status line at each step. Under it, any `thinking` block with non-empty text is a progress update, so render those and nothing else. It's in beta and requires the beta header `thinking-display-updates-2026-08-18` (on Amazon Bedrock, Google Cloud, and Microsoft Foundry, pass the beta value as described in [Beta headers](https://platform.claude.com/docs/en/api/beta-headers)). Without it, the value is rejected with the same 400 `invalid_request_error` as an unknown `display` value.963964```json965{966 "model": "claude-fable-5-1",967 "max_tokens": 16000,968 "thinking": { "type": "adaptive", "display": "updates" },969 "tools": [970 {971 "name": "edit_file",972 "description": "Replace the contents of a file in the repository.",973 "input_schema": {974 "type": "object",975 "properties": {976 "path": { "type": "string" },977 "content": { "type": "string" }978 },979 "required": ["path", "content"]980 }981 }982 ],983 "messages": [984 {985 "role": "user",986 "content": "The login test fails after an hour of uptime. Find out why and fix it."987 }988 ]989}990```991992Under `"updates"`, the start of the response that follows a `tool_result` looks like this. The first block is reasoning and stays empty, as it would under `"omitted"`. The second carries text, so it's a progress update. Under `"summarized"` both blocks carry text, and under `"omitted"` both are empty.993994```json Output995{996 "content": [997 {998 "type": "thinking",999 "thinking": "",1000 "signature": "EqMBCkYICxIM..."1001 },1002 {1003 "type": "thinking",1004 "thinking": "Confirmed the retry path never refreshes the expired token. Editing auth.py to add the refresh call.",1005 "signature": "Es8CCkYICxIM..."1006 },1007 {1008 "type": "tool_use",1009 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",1010 "name": "edit_file",1011 "input": { "path": "auth.py", "content": "..." }1012 }1013 ]1014}1015```10161017Keep the following in mind when working with progress updates:10181019* Pass progress-update blocks back unchanged with the rest of the assistant turn, like any other `thinking` block.1020* The text you receive is a summary of the progress update, normally a sentence or two. Don't rely on its length. The progress update counts toward `usage.output_tokens` at its full length, not the summary's.1021* A progress-update block can come back with an empty `thinking` field under any `display` value. Render nothing for an empty block. Under `"updates"` it looks the same as an empty reasoning block and needs no separate handling.1022* When a response stops on `max_tokens`, `model_context_window_exceeded`, or `stop_sequence` soon after a tool call or tool result, its last block can be a progress-update block standing in for the work the model hadn't finished. Under `"updates"` and `"summarized"` its text is exactly `This part of the response was interrupted before it finished.` and you can show it like any other update. Under `"omitted"` it's empty. To continue, pass the assistant turn back unchanged and append a new `user` message (with a `tool_result` for each `tool_use` block in that turn).1023* When [streaming](https://platform.claude.com/docs/en/build-with-claude/thinking#streaming-thinking), expect a pause of several seconds before a progress-update block opens. See the `"updates"` trace in [Streaming thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#streaming-thinking).1024* These models write fewer progress updates at higher [effort](https://platform.claude.com/docs/en/build-with-claude/effort) and in long tool chains. If your interface depends on them, see [Ask for user-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#ask-for-user-facing-progress-updates).10251026### Thinking block preservation by model10271028Whether thinking blocks from previous assistant turns stay in context by default depends on the model:10291030* **Keep all prior turns:** Claude Opus 4.5 and later Opus models, Claude Sonnet 4.6 and later Sonnet models, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, and Claude Mythos Preview.1031* **Keep the last turn only:** earlier Opus and Sonnet models, and all Haiku models through Claude Haiku 4.5. When you pass older thinking blocks back, the API strips them automatically. You don't need to remove them yourself.10321033Preservation brings two benefits:10341035* **Cache optimization:** preserved thinking blocks enable cache hits during tool use, as they are passed back with tool results and cached incrementally across the assistant turn, resulting in token savings in multistep workflows.1036* **No intelligence impact:** preserving thinking blocks has no negative effect on model performance.10371038The tradeoff is context usage: long conversations consume more context space on keep-all models, because retained thinking blocks count as input like any other conversation history (see [Thinking and the context window](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-the-context-window)). The behavior is automatic in both regimes. No code changes or beta headers are required, and you should keep passing complete, unmodified thinking blocks back as described in [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks). To override the default in either direction, use [thinking block clearing](https://platform.claude.com/docs/en/build-with-claude/context-editing#thinking-block-clearing).10391040**Switching models mid-conversation.** Keep passing thinking blocks back unchanged when you switch models, for example after a [classifier refusal fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback). A thinking block is readable only by the model that produced it or a newer one, and the API ignores or drops the blocks the target model can't read. On Claude Fable 5.1 and Claude Mythos 5.1 the direction matters: they read every earlier model's thinking blocks and no earlier model reads theirs, so switching up to them keeps the conversation's reasoning and switching down drops it (see [how dropped blocks are billed and reported](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#switching-models)). Strip prior `thinking` and `redacted_thinking` blocks yourself only to save input tokens on models that ignore rather than drop them, and never when redeeming a [fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit), which requires the body unchanged.10411042## Preserved thinking10431044[Preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking) decides whether the model can use a thinking block that you send back from an earlier turn. Starting with Claude Fable 5.1, the API checks the `signature` of every `thinking` or `redacted_thinking` block in a request for two things:10451046* **The model that produced it.** A model reads its own thinking blocks and those of earlier models, never those of a newer model. Claude Fable 5.1 reads blocks from Claude Opus 5, but Claude Opus 5 can't read blocks from Claude Fable 5.1. The API drops a block the current model can't read, without an error and without billing it. See [Switching models mid-conversation](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#switching-models).1047* **Everything sent before it.** A block stays valid only while the top-level `system` prompt, the `tools`, and the messages before it are unchanged. If any of them changes, 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).10481049The 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 check only on requests that set `thinking.block_binding.prefix_mismatch_behavior`. Later models will enforce it for all accounts, so make your integration append-only now.10501051To keep thinking valid, send every assistant turn back exactly as you received it and add new messages only at the end of `messages`. If your code builds the `messages` array itself, the Preserved thinking page covers:10521053* [What counts as an edit](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#what-counts-as-an-edit), and [how to check whether your code makes one](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#how-to-tell-whether-your-integration-is-impacted).1054* [The API feature that replaces each common edit](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#replace-prefix-edits): mid-conversation system messages for new instructions and per-turn reminders, `tool_addition` and `tool_removal` blocks for tool changes, per-message `output_config` for effort changes, and server-side compaction and context editing for trimming.1055* [Client-side compaction](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client): which patterns keep thinking valid and which don't.1056* [The `thinking-binding-controls-2026-08-01` beta header](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#preserved-thinking-controls). It adds an `input_transformations` array to every response that lists the blocks the API dropped, and a `block_binding.prefix_mismatch_behavior` field on the thinking configuration that accepts `"error"` or `"drop_block"`.10571058## Thinking and prompt caching10591060[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) interacts with thinking in a few specific ways. The following rules apply in both thinking modes.10611062**Configuration changes invalidate caching.** The thinking configuration and the resolved [`effort`](https://platform.claude.com/docs/en/build-with-claude/effort) level are rendered into the prompt itself, so changing any of them starts a new cache prefix. Switching between `adaptive`, `enabled`, and `disabled`, changing `budget_tokens`, and changing the effort value all invalidate cache breakpoints: message-level breakpoints always miss, and tool and system-prompt breakpoints can miss too, depending on where the model renders the configuration. Treat any thinking or top-level effort change as starting the cache over. On models that support [per-message effort](https://platform.claude.com/docs/en/build-with-claude/effort#change-effort-mid-conversation-beta), an effort change carried in a `role: "system"` message inside `messages` leaves the cached prefix intact. Consecutive requests that keep the same configuration preserve the cache, and setting a parameter explicitly to its default value is equivalent to omitting it. A thinking block the API drops under either [preserved-thinking condition](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking) changes the cached prefix from that block's position onward. Blocks passed back unchanged keep the cache intact. A worked demonstration with usage output is on the [Steering thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#prompt-caching) page.10631064**Thinking blocks are cached with tool results.** During a tool-use loop, caching occurs when you make a follow-up request that includes tool results. At that point the previous conversation history, including its thinking blocks, can be cached, and those cached thinking blocks count as input tokens in your usage metrics when read from the cache. This occurs automatically, even without explicit `cache_control` markers, and behaves the same for regular and interleaved thinking. The tradeoff: thinking blocks you never see again in responses still contribute to input token usage when read from cache.10651066**Whether prior blocks are in context at all is per-model.** The [preservation default](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model) governs this. On keep-all models, previous turns' thinking blocks stay cached and in context. On last-turn-only models, once you send a user message that isn't a tool result, all previous thinking blocks are stripped from context. On those models, a conversation like this:10671068```text wrap1069User: ["What's the weather in Paris?"],1070Assistant: [thinking_block_1] + [tool_use block 1],1071User: [tool_result_1, cache=True],1072Assistant: [thinking_block_2] + [text block 2],1073User: [Text response, cache=True]1074```10751076is processed as if the thinking blocks were never there:10771078```text wrap1079User: ["What's the weather in Paris?"],1080Assistant: [tool_use block 1],1081User: [tool_result_1, cache=True],1082Assistant: [text block 2],1083User: [Text response, cache=True]1084```10851086On keep-all models, the same request keeps `thinking_block_1` and `thinking_block_2` in context and in the cache.10871088**Degradation strips thinking from the cacheable history.** If thinking becomes disabled mid-turn and you pass thinking content in the current tool-use turn, the thinking content is stripped and thinking remains disabled for that request (see [graceful degradation](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use)). [Interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking) amplifies cache invalidation effects, because thinking blocks can occur between multiple tool calls.10891090<Tip>1091 Thinking-heavy tasks often take longer than the default 5-minute cache lifetime to complete. Consider the [1-hour cache duration](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) to maintain cache hits across longer thinking sessions and multistep workflows.1092</Tip>10931094## Thinking and the context window10951096`max_tokens`, which includes all thinking Claude generates in the current turn, is enforced as a strict limit. On Claude 4.5 models and newer, if input tokens plus `max_tokens` exceeds the context window size, the API accepts the request. If generation then reaches the context window limit, it stops with `stop_reason: "model_context_window_exceeded"` instead of returning an error. On earlier models, the API returns a validation error instead. See [Handling stop reasons](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons).10971098How thinking counts against the window depends on when it was generated:10991100* **Current-turn thinking** always counts toward `max_tokens`, is billed as output tokens, and occupies context window space for the turn that generated it.1101* **Prior-turn thinking** depends on the [preservation default](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model). On [models that keep all prior turns](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model), previous thinking blocks remain in context, count toward the window, and are billed as input tokens like the rest of the conversation history. On models that keep only the last turn, the API strips older thinking blocks automatically when you pass them back, so they don't consume window space or input tokens.11021103In practice:11041105* On keep-all models, budget your context window as if thinking were ordinary conversation history, because it is. Long agentic sessions accumulate thinking in context. Use [thinking block clearing](https://platform.claude.com/docs/en/build-with-claude/context-editing#thinking-block-clearing) if you need to reclaim space.1106* On last-turn-only models, thinking is a per-turn cost only: each turn's thinking counts against that turn's `max_tokens` and then drops out of the window.11071108The following diagrams illustrate the last-turn-only (stripping) regime. The first shows a multi-turn conversation: each turn's thinking block is generated in the output but not carried into later turns' input.1109111011111112The second shows the same regime with tool use: thinking stays in context alongside its tool result for the duration of the assistant turn, then drops out on the next user turn.1113111411151116Use the [token counting API](https://platform.claude.com/docs/en/build-with-claude/token-counting) to get accurate counts for your specific use case, especially for multi-turn conversations that include thinking.11171118## Thinking encryption11191120Full thinking content is encrypted and returned in the `signature` field on each thinking block. The API uses the signature to verify that thinking blocks were generated by Claude when you pass them back.11211122Keep the following in mind when working with signatures:11231124* It is only strictly necessary to send back thinking blocks when [using tools with thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use). Otherwise you can omit thinking blocks from previous turns. If you do pass them back, whether the API keeps or strips them depends on the model (see [Thinking block preservation by model](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model)). Use [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) to configure this.1125* When sending back thinking blocks, pass everything back exactly as you received it, for consistency and to avoid potential issues.1126* When [streaming responses](https://platform.claude.com/docs/en/build-with-claude/thinking#streaming-thinking), the signature arrives as a `signature_delta` inside a `content_block_delta` event just before the `content_block_stop` event.1127* `signature` values are significantly longer in Claude 4 and later models than in previous models.1128* The `signature` field is opaque: don't interpret or parse it.1129* `signature` values are compatible across platforms (the Claude API, [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock), and [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)). Values generated on one platform work on another.11301131## Redacted thinking blocks11321133In addition to regular `thinking` blocks, the API may return `redacted_thinking` blocks when portions of Claude's reasoning are safety-redacted. A `redacted_thinking` block contains encrypted thinking content in a `data` field, with no readable text:11341135```json1136{1137 "type": "redacted_thinking",1138 "data": "..."1139}1140```11411142The `data` field is opaque and encrypted. Like the `signature` field on regular thinking blocks, pass `redacted_thinking` blocks back to the API unchanged when continuing a multi-turn conversation with [tools](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use).11431144<Tip>1145 If your code filters content blocks by type (for example, `block.type == "thinking"`) when round-tripping responses with tool use, also include `redacted_thinking` blocks. Filtering on `block.type == "thinking"` alone silently drops `redacted_thinking` blocks and breaks the multi-turn protocol described in [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks).1146</Tip>11471148<Note>1149 `redacted_thinking` blocks are a distinct content block type returned when thinking is safety-redacted. This is separate from the [`display: "omitted"`](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) option, which returns regular `thinking` blocks with an empty `thinking` field.1150</Note>11511152## Limits and feature compatibility11531154### Sampling parameters11551156On 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, and Claude Sonnet 5, non-default `temperature`, `top_p`, or `top_k` values return a 400 error on every request, regardless of whether thinking is used. On older models, the restriction applies only while thinking is on: `temperature` and `top_k` are incompatible with thinking, and `top_p` is allowed at values between 0.95 and 1.11571158### Response prefill and forced tool use11591160You can't prefill the assistant response while thinking is on. Forced tool use (`tool_choice: {"type": "any"}` or `{"type": "tool", ...}`) is incompatible with manual extended thinking but works with adaptive thinking. The exceptions are Claude Fable 5.1 and Claude Mythos 5.1, which reject forced tool use on every request with a 400 error. On those models, use `tool_choice: {"type": "auto"}` with [strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use) or [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) instead. See [Thinking with tool use](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use).11611162### Output limits11631164Each model accepts `max_tokens` up to the ceiling listed here. On the [Message Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing#extended-output-beta), the `output-300k-2026-03-24` [beta header](https://platform.claude.com/docs/en/api/beta-headers) raises that ceiling for the models with a batches ceiling listed.11651166| Model | Max output tokens | Batches beta ceiling |1167| :-------------------- | :---------------- | :------------------- |1168| Claude Fable 5.1 | 128K | — |1169| Claude Mythos 5.1 | 128K | — |1170| Claude Fable 5 | 128K | — |1171| Claude Mythos 5 | 128K | — |1172| Claude Mythos Preview | 128K | Not available |1173| Claude Opus 5 | 128K | 300K |1174| Claude Opus 4.8 | 128K | 300K |1175| Claude Opus 4.7 | 128K | 300K |1176| Claude Opus 4.6 | 128K | 300K |1177| Claude Opus 4.5 | 64K | Not available |1178| Claude Sonnet 5 | 128K | 300K |1179| Claude Sonnet 4.6 | 128K | 300K |1180| Claude Sonnet 4.5 | 64K | Not available |1181| Claude Haiku 4.5 | 64K | Not available |11821183See the [models overview](https://platform.claude.com/docs/en/models/overview) for limits on legacy models.11841185### Long requests11861187The SDKs require streaming when `max_tokens` is greater than 21,333, to avoid HTTP timeouts on long-running requests. This is a client-side validation, not an API restriction. If you don't need to process events incrementally, use `.stream()` with `.get_final_message()` (Python) or `.finalMessage()` (TypeScript) to get the complete `Message` object without handling individual events. See [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming#get-the-final-message-without-handling-events). Expect longer response times when thinking is active, because generating thinking blocks adds processing time. For workloads that push thinking above roughly 32k tokens per request, use [batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) to avoid networking issues: such requests can run long enough to hit system timeouts and open connection limits.11881189## Next steps11901191<CardGroup cols={2}>1192 <Card title="Steering thinking" icon="compass" href="https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost">1193 Steer how often and how deeply Claude thinks with effort levels, system prompt guidance, and per-message steering, and understand thinking's cost and pricing.1194 </Card>11951196 <Card title="Thinking in tool and multi-turn workflows" icon="wrench" href="https://platform.claude.com/docs/en/build-with-claude/thinking-tool-workflows">1197 Walk through a complete two-turn tool-use round trip that preserves thinking blocks correctly, and see how interleaved thinking changes the flow.1198 </Card>11991200 <Card title="Preserved thinking" icon="stack" href="https://platform.claude.com/docs/en/build-with-claude/preserved-thinking">1201 Find out whether your Messages API integration edits conversation history, and replace each edit with the API feature that keeps earlier thinking blocks valid.1202 </Card>12031204 <Card title="Troubleshooting thinking" icon="hammer" href="https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting">1205 Diagnose and fix the most common thinking failures: configuration 400 errors, empty or missing thinking blocks, max\_tokens stops, and cache misses.1206 </Card>12071208 <Card title="Effort" icon="sliders" href="https://platform.claude.com/docs/en/build-with-claude/effort">1209 Control how many tokens Claude uses when responding with the effort parameter, trading off between response thoroughness and token efficiency.1210 </Card>1211</CardGroup>1212