SPB Git

Repository Public

extended-thinking.md 21.6 KB 410 lines markdown

1---2title: Extended thinking3url: https://platform.claude.com/docs/en/build-with-claude/extended-thinking4description: Configure manual extended thinking with a fixed budget_tokens budget on Claude models that support it, and migrate to adaptive thinking.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>1011<Warning>12  Extended thinking (`thinking.type: "enabled"` with `budget_tokens`) is deprecated on the Claude 4.6 models (requests using it still succeed). Claude 4.7 and later models do not support it and reject requests that use it, returning a 400 error. On Claude 4.5 and earlier models that support thinking, extended thinking is the only available thinking mode. Claude Mythos Preview supports both modes. Where both modes are available, use [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) instead.1314  See [Migrating to adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#migrating-to-adaptive-thinking) to move to adaptive thinking. If your model supports only extended thinking, this page describes the supported configuration; no change is needed until you move to a newer model.15</Warning>1617<Note>18  If a request fails with a 400 error whose message starts with `"thinking.type.enabled" is not supported`, your model uses adaptive thinking instead. See [Troubleshooting thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#error-thinking-type-enabled), or jump to [Migrating to adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#migrating-to-adaptive-thinking).19</Note>2021Extended thinking in manual mode gives you direct control over how much Claude thinks. You set a thinking token budget on each request with `thinking: {type: "enabled", budget_tokens: N}`, and Claude thinks against that budget before it starts its final answer. Manual mode remains useful when your workload requires predictable latency or precise control over thinking costs. This page covers how to set and tune the budget, how manual mode interacts with interleaved thinking and prompt caching, and how to migrate to adaptive thinking.2223To learn how thinking itself works, including thinking blocks and the response shape, the `display` parameter, streaming, thinking with tool use, and encryption, see the [thinking overview](https://platform.claude.com/docs/en/build-with-claude/thinking).2425## Supported models2627Extended thinking availability per model, including the models where extended thinking is the only mode, is listed in the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#supported-models).2829## How to use extended thinking3031Here is an example of using extended thinking in the Messages API:3233<CodeGroup>34  ```bash cURL35  curl https://api.anthropic.com/v1/messages \36    -H "x-api-key: $ANTHROPIC_API_KEY" \37    -H "anthropic-version: 2023-06-01" \38    -H "content-type: application/json" \39    -d '{40      "model": "claude-sonnet-4-6",41      "max_tokens": 16000,42      "thinking": {43        "type": "enabled",44        "budget_tokens": 1000045      },46      "messages": [47        {48          "role": "user",49          "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?"50        }51      ]52    }'53  ```5455  ```bash CLI56  ant messages create \57    --format yaml <<'YAML'58  model: claude-sonnet-4-659  max_tokens: 1600060  thinking:61    type: enabled62    budget_tokens: 1000063  messages:64    - role: user65      content: Are there an infinite number of prime numbers such that n mod 4 == 3?66  YAML67  ```6869  ```python Python70  client = anthropic.Anthropic()7172  response = client.messages.create(73      model="claude-sonnet-4-6",74      max_tokens=16000,75      thinking={"type": "enabled", "budget_tokens": 10000},76      messages=[77          {78              "role": "user",79              "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",80          }81      ],82  )8384  # The response contains summarized thinking blocks and text blocks85  for block in response.content:86      match block.type:87          case "thinking":88              print(f"\nThinking summary: {block.thinking}")89          case "text":90              print(f"\nResponse: {block.text}")91  ```9293  ```typescript TypeScript94  const client = new Anthropic();9596  const response = await client.messages.create({97    model: "claude-sonnet-4-6",98    max_tokens: 16000,99    thinking: {100      type: "enabled",101      budget_tokens: 10000,102    },103    messages: [104      {105        role: "user",106        content: "Are there an infinite number of prime numbers such that n mod 4 == 3?",107      },108    ],109  });110111  // The response contains summarized thinking blocks and text blocks112  for (const block of response.content) {113    switch (block.type) {114      case "thinking":115        console.log(`\nThinking summary: ${block.thinking}`);116        break;117      case "text":118        console.log(`\nResponse: ${block.text}`);119        break;120    }121  }122  ```123124  ```csharp C#125  AnthropicClient client = new();126127  var response = await client.Messages.Create(new()128  {129      Model = Model.ClaudeSonnet4_6,130      MaxTokens = 16000,131      Thinking = new ThinkingConfigEnabled(budgetTokens: 10000),132      Messages =133      [134          new()135          {136              Role = Role.User,137              Content = "Are there an infinite number of prime numbers such that n mod 4 == 3?",138          },139      ],140  });141142  // The response contains summarized thinking blocks and text blocks143  foreach (var block in response.Content)144  {145      if (block.TryPickThinking(out var thinking))146      {147          Console.WriteLine($"\nThinking summary: {thinking.Thinking}");148      }149      else if (block.TryPickText(out var text))150      {151          Console.WriteLine($"\nResponse: {text.Text}");152      }153  }154  ```155156  ```go Go157  client := anthropic.NewClient()158159  response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{160  	Model:     anthropic.ModelClaudeSonnet4_6,161  	MaxTokens: 16000,162  	Thinking:  anthropic.ThinkingConfigParamOfEnabled(10000),163  	Messages: []anthropic.MessageParam{164  		anthropic.NewUserMessage(anthropic.NewTextBlock("Are there an infinite number of prime numbers such that n mod 4 == 3?")),165  	},166  })167  if err != nil {168  	log.Fatal(err)169  }170171  // The response contains summarized thinking blocks and text blocks172  for _, block := range response.Content {173  	switch block := block.AsAny().(type) {174  	case anthropic.ThinkingBlock:175  		fmt.Printf("\nThinking summary: %s", block.Thinking)176  	case anthropic.TextBlock:177  		fmt.Printf("\nResponse: %s", block.Text)178  	}179  }180  ```181182  ```java Java183  import com.anthropic.client.okhttp.AnthropicOkHttpClient;184  import com.anthropic.models.messages.MessageCreateParams;185  import com.anthropic.models.messages.Model;186187  void main() {188      var client = AnthropicOkHttpClient.fromEnv();189190      var params = MessageCreateParams.builder()191          .model(Model.CLAUDE_SONNET_4_6)192          .maxTokens(16_000)193          .enabledThinking(10_000)194          .addUserMessage("Are there an infinite number of prime numbers such that n mod 4 == 3?")195          .build();196197      var response = client.messages().create(params);198199      // The response contains summarized thinking blocks and text blocks200      for (var block : response.content()) {201          block.thinking().ifPresent(thinkingBlock ->202              IO.println("\nThinking summary: " + thinkingBlock.thinking())203          );204          block.text().ifPresent(textBlock ->205              IO.println("\nResponse: " + textBlock.text())206          );207      }208  }209  ```210211  ```php PHP212  $client = new Client();213214  $response = $client->messages->create(215      model: 'claude-sonnet-4-6',216      maxTokens: 16000,217      thinking: ['type' => 'enabled', 'budget_tokens' => 10000],218      messages: [219          [220              'role' => 'user',221              'content' => 'Are there an infinite number of prime numbers such that n mod 4 == 3?',222          ],223      ],224  );225226  // The response contains summarized thinking blocks and text blocks227  foreach ($response->content as $block) {228      echo match (true) {229          $block instanceof \Anthropic\Messages\ThinkingBlock => "\nThinking summary: {$block->thinking}",230          $block instanceof \Anthropic\Messages\TextBlock => "\nResponse: {$block->text}",231          default => '',232      };233  }234  ```235236  ```ruby Ruby237  client = Anthropic::Client.new238239  response = client.messages.create(240    model: "claude-sonnet-4-6",241    max_tokens: 16_000,242    thinking: {243      type: :enabled,244      budget_tokens: 10_000245    },246    messages: [247      {248        role: :user,249        content: "Are there an infinite number of prime numbers such that n mod 4 == 3?"250      }251    ]252  )253254  # The response contains summarized thinking blocks and text blocks255  response.content.each do |block|256    case block257    when Anthropic::Models::ThinkingBlock258      puts "\nThinking summary: #{block.thinking}"259    when Anthropic::Models::TextBlock260      puts "\nResponse: #{block.text}"261    end262  end263  ```264</CodeGroup>265266To turn on manual extended thinking, add a `thinking` object with `type` set to `enabled` and a `budget_tokens` value.267268The `budget_tokens` parameter sets a target for how many tokens Claude can use for its internal reasoning process. Larger budgets can improve response quality by enabling more thorough analysis for complex problems.269270## Budget rules and tuning271272`budget_tokens` must satisfy these constraints:273274* **Minimum of 1,024 tokens.** The API rejects smaller values.275* **Less than `max_tokens`.** Thinking tokens count toward the `max_tokens` limit for the turn, so the budget must leave room for the final response. The one exception is [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking), where `budget_tokens` can exceed `max_tokens` because the budget spans all thinking blocks within one assistant turn.276* **No cache pre-warming.** Because `budget_tokens` must be less than `max_tokens`, extended thinking cannot be combined with `max_tokens: 0` ([cache pre-warming](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)).277278The budget is a target rather than a strict cap. Actual token usage varies with the task, and Claude may stop reasoning well before the budget is exhausted; `max_tokens` remains the hard ceiling on total output.279280On Claude Opus 4.5, the only extended-thinking-only model that supports [effort](https://platform.claude.com/docs/en/build-with-claude/effort), effort shapes the overall response while `budget_tokens` sets thinking depth; set both.281282To tune the budget:283284* Match the starting point to the task. For simple tasks, start near the 1,024-token minimum and increase incrementally to find the optimal range for your use case. For complex tasks, start with a larger budget of 16,000 tokens or more and adjust to your latency and quality needs. Higher budgets enable more comprehensive reasoning, with diminishing returns that depend on the task, and at the cost of increased latency. For critical tasks, test different settings to find the right balance.285* For thinking budgets above 32k, use [batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) to avoid networking issues. Pushing the model to think beyond 32k tokens produces long-running requests that can hit system timeouts and open-connection limits.286287To track what a budget actually costs you, monitor the `usage.output_tokens_details.thinking_tokens` field in the response, which reports how many of the billed output tokens were internal reasoning. When streaming, this breakdown appears only on the final `message_delta` event.288289When you are ready to move off manual budgets, see [Migrating to adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#migrating-to-adaptive-thinking).290291## Interleaved thinking in manual mode292293Interleaved thinking lets Claude think between tool calls within a single assistant turn, reasoning about each tool result before deciding what to do next. For the concept, the turn structure, and how it behaves on adaptive-thinking models, see [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking) in the thinking overview. This section covers how to enable it when you use manual `type: "enabled"` thinking.294295On Claude Opus 4.5, Claude Sonnet 4.5, and earlier Claude 4 models, add the `interleaved-thinking-2025-05-14` [beta header](https://platform.claude.com/docs/en/api/beta-headers) to your API request.296297The 4.6 generation splits in manual mode:298299* **Claude Sonnet 4.6**: the beta header with manual `type: "enabled"` is still functional but deprecated. Prefer [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking), which interleaves automatically with no header.300* **Claude Opus 4.6**: manual mode has no interleaved thinking at all. Only its adaptive mode interleaves, so switch to `thinking: {type: "adaptive"}` if you need reasoning between tool calls on this model.301302Claude Haiku 4.5 does not support interleaved thinking. On the Claude API, the beta header is accepted but ignored.303304Two more considerations for interleaved thinking in manual mode:305306* `budget_tokens` can exceed `max_tokens` here; the [budget rules](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#budget-rules-and-tuning) explain this exception.307* Interleaved thinking is only supported for [tools used through the Messages API](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).308309How platforms treat the beta header differs. The Claude API and [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws) accept `interleaved-thinking-2025-05-14` on any model and ignore it where unsupported. Acceptance is not the same as effect: on models that reject `type: "enabled"` (4.7 and later) or lack manual-mode interleaving (Claude Opus 4.6), the header has no manual-mode effect; adaptive thinking interleaves automatically there.310311Partner-operated platforms ([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)) likewise accept the header on any model without returning an error, and ignore it on models that don't support interleaved thinking.312313## Turn structure in manual mode314315The general turn-structure rules, including the single-turn tool-use loop, mid-turn conflict handling, and toggling thinking between turns, are on [Thinking with tool use](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use).316317Manual mode adds one requirement: the final assistant turn of a thinking-enabled request must begin with a thinking block ([adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) drops that requirement). Changing the thinking configuration between turns also invalidates prompt caching; see the following section.318319## Prompt caching in manual mode320321Manual mode adds one rule on top of the mode-neutral caching behavior described in [thinking and prompt caching](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching): changing `budget_tokens` between requests invalidates cache breakpoints, just as switching thinking modes does, because the budget value is rendered into the prompt. Message-level breakpoints always miss after a budget change; whether tool and system-prompt breakpoints miss too depends on where the model renders the configuration.322323In practice, pick a budget and hold it stable for the life of a cached conversation. Running a multi-turn conversation with message-level caching on Claude Sonnet 4.6 and changing the budget on the third request from 4,000 to 8,000 tokens shows the invalidation directly:324325```text Output wrap326First request - establishing cache327First response usage: { cache_creation_input_tokens: 1370, cache_read_input_tokens: 0, input_tokens: 17, output_tokens: 700 }328329Second request - same thinking parameters (cache hit expected)330Second response usage: { cache_creation_input_tokens: 0, cache_read_input_tokens: 1370, input_tokens: 303, output_tokens: 874 }331332Third request - different thinking budget (cache miss expected)333Third response usage: { cache_creation_input_tokens: 1370, cache_read_input_tokens: 0, input_tokens: 747, output_tokens: 619 }334```335336The third request re-creates the cache (`cache_creation_input_tokens=1370`, `cache_read_input_tokens=0`) because the budget changed between requests. For a runnable version of the same experiment in adaptive mode, where the effort level plays the cache role that `budget_tokens` plays here, see [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#prompt-caching) on the steering page.337338## Shared mechanics339340Most thinking behavior is mode neutral and documented once on the [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) page. Everything there applies in manual mode too:341342* [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display)343* [Streaming thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#streaming-thinking)344* [Thinking with tool use](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-with-tool-use), including [preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks)345* [Thinking and prompt caching](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching)346* [Thinking and the context window](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-the-context-window)347* [Thinking encryption](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-encryption)348* [Pricing](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#pricing) (on the [Steering thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost) page)349350## Migrating to adaptive thinking351352If your model supports only extended thinking (Claude Sonnet 4.5, Claude Opus 4.5, Claude Haiku 4.5, and earlier Claude 4 models), no action is needed now: adaptive thinking is not available there, and `type: "adaptive"` [returns a 400 error](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#error-thinking-type-adaptive). Keep `budget_tokens` until you move to a model that supports adaptive thinking, then apply the mapping that follows.353354You need to migrate off `type: "enabled"` if:355356* You use Claude Opus 4.6 or Claude Sonnet 4.6, where `budget_tokens` is deprecated.357* You are moving to Claude Opus 4.7, Claude Opus 4.8, Claude Opus 5, Claude Sonnet 5, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, or Claude Mythos 5, where `type: "enabled"` returns a 400 error.358359The mapping is small: remove `budget_tokens`, set `thinking: {type: "adaptive"}`, and control reasoning depth with `output_config: {effort: ...}` instead of a token budget.360361```json362{363  "model": "claude-sonnet-4-6",364  "max_tokens": 16000,365  "thinking": {366    "type": "enabled",367    "budget_tokens": 10000368  }369}370```371372becomes:373374```json375{376  "model": "claude-sonnet-4-6",377  "max_tokens": 16000,378  "thinking": {379    "type": "adaptive"380  },381  "output_config": {382    "effort": "high"383  }384}385```386387`effort: "high"` matches the API default; it appears here only to show where the depth control now lives, and omitting it produces identical behavior.388389Expect a behavioral difference, not just a syntax change. With a fixed budget, Claude thinks on every request. With adaptive thinking, Claude decides whether and how much to think on each request, and at lower [effort](https://platform.claude.com/docs/en/build-with-claude/effort) settings it may skip thinking entirely on easy inputs. You can also remove the `interleaved-thinking-2025-05-14` beta header after migrating: adaptive thinking interleaves automatically, and the Claude API ignores the header on these models. Thinking block preservation changes too: Claude Opus 4.5 and models numbered 4.6 and higher keep prior turns' thinking blocks in context and bill them as input, where Claude Sonnet 4.5, Claude Haiku 4.5, and earlier models stripped them; see [thinking block preservation by model](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model).390391Switching modes is a thinking-configuration change, so the first request after the switch invalidates cache breakpoints, as described in [Prompt caching in manual mode](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#extended-thinking-with-prompt-caching).392393For full guidance, see [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking), [effort](https://platform.claude.com/docs/en/build-with-claude/effort), and the [model migration guide](https://platform.claude.com/docs/en/about-claude/models/migration-guide).394395## Next steps396397<CardGroup cols={3}>398  <Card title="Thinking" icon="brain" href="https://platform.claude.com/docs/en/build-with-claude/thinking">399    Learn how thinking works: blocks, display, streaming, and tool use.400  </Card>401402  <Card title="Steering thinking" icon="compass" href="https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost">403    Let Claude decide when and how much to think on each request.404  </Card>405406  <Card title="Thinking in tool and multi-turn workflows" icon="wrench" href="https://platform.claude.com/docs/en/build-with-claude/thinking-tool-workflows">407    Preserve thinking blocks and manage thinking across tool calls and turns.408  </Card>409</CardGroup>410
Files main
Menu

Theme