Follow Discord
Sweep 22 Oct 2026 · 04:32Z Build v2.1.308 527 read Stable v2.1.308 Latest v2.1.308 Next v2.1.308 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · api

One read of Claude Developer Platformapi-20261021T193714Z

242 pages moved out of 808 read.

Pages moved 242 significant first
Pages read 808 in this capture
Captured 19:37 UTC
Corpus hash 851c97e9b6f0 corpus-hash

What this read moved

76-100 of 242, page 4 of 10

This capture is too large to show at once. Changes 76-100 of 242 are below, significant first; the rest are on the following screens.

build-with-claude/mid-conversation-system-messages Changed · +15 / -15 lines

from line 1006
10061006 
10071007A few rules follow from where the definition renders:
10081008 
1009* **Declare what you know up front.** A tool you know about at the first request belongs in `tools`, with `defer_loading: true` and a later `tool_addition` reference if the model shouldn't see it yet. Define by value only what is unknown at the first request or changes later.
1009* **Declare what you know up front.** A tool you know about at the first request belongs in `tools`, with `defer_loading: true` and a later `tool_addition` reference if it shouldn't be offered to the model yet. Define by value only what is unknown at the first request or changes later.
10101010* **Keep at least one non-deferred tool in `tools`.** A conversation whose `tools` array has no non-deferred tool is accepted, but the first tool it defines by value changes the start of the rendered prompt, which costs one full cache miss on that request. A [tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) counts as non-deferred.
10111011* **Dated tool types keep their own beta headers.** If a server tool you define by value requires its own beta header, send that header on every later request in the conversation.
10121012* **`cache_control` goes on the block or in the definition, not both,** and counts toward the request's breakpoint limit. A deferred definition can't carry `cache_control`.
from line 1015
10151015 
10161016* More than 10,000 deferred tools are available after any message.
10171017* More than 10,000 tools defined after the first user message are available after any message.
1018* The tool definitions sent after the first user message that are still available after any message total more than 4 MB (4,194,304 bytes).
1019* The rendered tool text is larger than 4 MB (4,194,304 bytes).
1018* The tool definitions sent after the first user message that are still available after any message total more than 4 MB (4,194,304 bytes).
1019* The rendered tool text is larger than 4 MB (4,194,304 bytes).
10201020 
10211021### Add an MCP server mid-conversation (beta)
10221022 
from line 1621
16211621 
16221622* **Mid-session policy or persona changes.** A long agentic session needs a new constraint ("from now on, write all SQL as parameterized queries") after dozens of cached turns. Adding it to the top-level `system` field would re-process the entire history.
16231623* **Per-turn context that must be authoritative.** You want to inject a freshness note, a session deadline, or a tool-availability change with system-level weight, and it changes too often to live in the cached prefix.
1624* **Per-turn reminders that shouldn't pile up.** A harness nudges the model after each batch of tool results ("request independent reads together", "the user hasn't heard from you in a while") and wants the model to see only the newest copy. A [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) renders for one turn and then costs nothing, without deleting anything from the history.
1625* **State changes your application observes.** Your application notices something Claude should treat as an operator-level fact: files changed on disk, the user toggled an auto-approve setting, available tools changed, or the remaining token budget dropped below a threshold.
1626* **User input that should not interrupt an agentic loop.** A user types a follow-up while Claude is still executing tools for the previous request. Relaying it as a system message after the next tool result lets Claude fold the new input into the work it is already doing, instead of treating it as a fresh request to switch to. On Claude Sonnet 5.5 and Claude Haiku 5.5, append the user's words as a `text` block after the last `tool_result` in the same `user` message instead. See [Placement after tool results](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#placement-after-tool-results).
1624* **Per-turn reminders that shouldn't pile up.** A harness nudges the model after each batch of tool results ("request independent reads together," "the user hasn't heard from you in a while") and needs the model to receive only the newest copy. A [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) renders for one turn and then costs nothing, without deleting anything from the history.
1625* **State changes your application observes.** Your application detects something Claude should treat as an operator-level fact: files changed on disk, the user toggled an auto-approve setting, available tools changed, or the remaining token budget dropped below a threshold.
1626* **User input that should not interrupt an agentic loop.** A user types a follow-up while Claude is still running tools for the previous request. Relaying it as a system message after the next tool result lets Claude fold the new input into the work it is already doing, instead of treating it as a fresh request to switch to. On Claude Sonnet 5.5 and Claude Haiku 5.5, append the user's words as a `text` block after the last `tool_result` in the same `user` message instead. See [Placement after tool results](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#placement-after-tool-results).
16271627* **Mode switches that grant standing permissions.** A session-level mode can use a mid-conversation system message to grant standing consent to an expensive capability, such as automatically launching multiagent workflows, with a short refresher every several turns and an exit notice when the mode is turned off. For a worked example, see [Build an orchestration mode](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-effort-example).
16281628 
1629In all of these cases you could put the instruction in a regular `user` message, and Claude does follow instructions that arrive in user turns. The difference is priority: a `user` message is treated as coming from the end user, while a `system` message is treated as coming from you, the application operator. When the two conflict, system instructions take precedence, so use the `system` role for operator-level facts and constraints that should hold even if the end user asks for something different. A mid-conversation system message keeps that operator-level priority without paying the cache-miss cost of editing the top-level `system` field.
1629In all of these cases you could put the instruction in a regular `user` message, and Claude does follow instructions that arrive in user turns. The difference is priority: a `user` message is treated as coming from the end user, whereas a `system` message is treated as coming from you, the application operator. When the two conflict, system instructions take precedence, so use the `system` role for operator-level facts and constraints that should hold even if the end user asks for something different. A mid-conversation system message keeps that operator-level priority without paying the cache-miss cost of editing the top-level `system` field.
16301630 
16311631## How it works
16321632 
from line 1902
19021902 client = Anthropic::Client.new
19031903 
19041904 response = client.messages.create(
1905 model: "claude-opus-5-5",
1905 model: Anthropic::Model::CLAUDE_OPUS_5_5,
19061906 max_tokens: 1024,
19071907 # Automatic prompt caching: each request caches the conversation so far,
19081908 # and the next request reads the unchanged prefix from cache.
from line 1954
19541954]
19551955```
19561956 
1957Phrase the system content as context rather than as a command that overrides the user. State the fact ("new input arrived from the user: X", "the remaining token budget is now Y") and let Claude act on it. Claude is trained to resist instructions that appear to work against the user, and that protection still applies to the system role, so language such as "ignore what the user said" is less effective than stating what changed.
1957Phrase the system content as context rather than as a command that overrides the user. State the fact ("new input arrived from the user: X," "the remaining token budget is now Y") and let Claude act on it. Claude is trained to resist instructions that appear to work against the user, and that protection still applies to the system role, so language such as "ignore what the user said" is less effective than stating what changed.
19581958 
19591959This pattern is for relaying input from the conversation's own end user. Do not use it to pass tool output, retrieved documents, or other third-party content; keep that content in `tool_result` blocks (see [Limitations](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#limitations)).
19601960 
from line 1998
19981998 
19991999The main use is a per-turn reminder in a tool loop. Append the reminder after the `tool_result` message each time you want the model to see it, and leave every earlier copy where it is. The model sees only the copies that come after the last user message, so the reminder never piles up. Nothing earlier in `messages` changes, so the [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) keeps matching. On Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5 this also keeps later [thinking blocks valid](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation): deleting an earlier reminder would change the conversation before those blocks and fail the conversation check, while a cleared message stays in the array and leaves that conversation unchanged.
20002000 
2001The following request is a later step of an agent loop. `messages[3]` rendered on the earlier request, when it was the last message in the array. Once `messages[5]` (a later user message) exists, `messages[3]` is cleared: the cleared message stays in the array, so the conversation before the thinking block in `messages[4]` is unchanged, but the model no longer sees its text. `messages[6]` and `messages[7]` both render, in order.
2001The following request is a later step of an agent loop. `messages[3]` rendered on the earlier request, when it was the last message in the array. Once `messages[5]` (a later user message) exists, `messages[3]` is cleared: the cleared message stays in the array, so the conversation before the thinking block in `messages[4]` is unchanged, but the model no longer receives its text. `messages[6]` and `messages[7]` both render, in order.
20022002 
20032003```json
20042004{
from line 2073
20732073 
20742074Rules for turn-scoped messages:
20752075 
2076* **Re-send cleared messages verbatim.** A cleared message is still part of the conversation history. Rebuilding it from current state (a fresh token count, a timestamp), dropping it as redundant, or changing its `clear_at` value is an edit to an earlier message. The prompt cache misses from that point, and on Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5 every thinking block produced after it fails the [conversation check](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation).
2076* **Re-send cleared messages verbatim.** A cleared message is still part of the conversation history. Rebuilding it from current state (a fresh token count, a timestamp), dropping it as redundant, or changing its `clear_at` value is an edit to an earlier message. On Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5, every thinking block produced after it fails the [conversation check](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation).
20772077* **Text only.** `content` is one or more `text` blocks (or a string). `tool_addition` and `tool_removal` blocks return a 400 error on a turn-scoped message, and so does `output_config`. Use a separate `role: "system"` message without `clear_at` for those.
20782078* **No `cache_control` on its blocks.** A cleared message is never part of a cache key, so a breakpoint on it could never match. Put the breakpoint on the last block of the preceding user turn instead, as the example does. The top-level [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) field skips turn-scoped messages when it picks a breakpoint. On the request that clears a message, the reusable cached prefix ends at the user turn before it, so only the one assistant turn between that message and the new user message is reprocessed.
20792079* **Placement rules still apply**, cleared or not. A turn-scoped message must follow a `user` turn (or an `assistant` turn ending in a server tool result) and precede an `assistant` turn or end the array, like any mid-conversation system message. One that ends the array always renders. One followed directly by another `user` message is a 400 error, not a cleared message: put all of a tool round's results in one user message and the reminders after it.
20802080* **Assistant turns don't clear it.** A prefilled or [paused](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#pause-turn) assistant turn after the message, or a server-side tool loop, adds no user message, so the message still renders on that continuation. To keep a reminder in view through a client-side tool loop, append it again after each `tool_result` message.
20812081* **Token counting follows what renders.** A cleared message adds nothing to `usage.input_tokens` or to a [token count](https://platform.claude.com/docs/en/build-with-claude/token-counting).
2082* **Imported history.** In a transcript you construct in one step (few-shot examples, a migrated conversation), a turn-scoped message that already has an assistant turn and a user message after it is cleared from the first request and never renders. That is the right state for a per-turn reminder you are carrying over. Leave `clear_at` unset only on a message the model should see on every request.
2082* **Imported history.** In a transcript you construct in one step (few-shot examples, a migrated conversation), a turn-scoped message that already has an assistant turn and a user message after it is cleared from the first request and never renders. That is the right state for a per-turn reminder you are carrying over. Leave `clear_at` unset only on a message that should render on every request.
20832083 
20842084The validation errors are:
20852085 
from line 2304
23042304 client = Anthropic::Client.new
23052305 
23062306 response = client.beta.messages.create(
2307 model: "claude-fable-5-1",
2307 model: Anthropic::Model::CLAUDE_FABLE_5_1,
23082308 max_tokens: 4096,
23092309 messages: [
23102310 {role: "user", content: "Draft a short status update on the database migration for the team channel."},
from line 2324
23242324 
23252325Mid-conversation system messages and [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) are designed to be used together:
23262326 
2327* **Enable caching explicitly.** Caching only happens when the request includes `cache_control`, either the top-level [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) field or an [explicit breakpoint](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints) on a content block. A mid-conversation system message does not create a cache entry on its own, and without caching enabled there are no savings to preserve.
2327* **Enable caching explicitly.** Caching only occurs when the request includes `cache_control`, either the top-level [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) field or an [explicit breakpoint](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints) on a content block. A mid-conversation system message does not create a cache entry on its own, and without caching enabled there are no savings to preserve.
23282328* **Cache the stable prefix as usual.** Place `cache_control` on the last block that stays the same across requests, whether that is the end of the top-level `system` field, the end of your tool definitions, or a stable point in the message history.
23292329* **Append the system message after the breakpoint.** Because it comes after the cached prefix, it does not change the prefix hash and the cache still hits.
23302330* **A mid-conversation system message is itself cacheable.** Once it is in the conversation, it becomes part of the stable history. On the next turn you can move your cache breakpoint past it (or rely on [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) to do so) and the system message is read from cache like any other turn.
from line 2346
23462346 </Card>
23472347 
23482348 <Card title="Cache diagnostics" icon="magnifying-glass" href="https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics">
2349 Find out exactly where two requests diverged when a cache hit you expected does not happen.
2349 Find out exactly where two requests diverged when a cache hit you expected does not occur.
23502350 </Card>
23512351 
23522352 <Card title="Using the Messages API" icon="message" href="https://platform.claude.com/docs/en/build-with-claude/working-with-messages">

build-with-claude/overview Changed · +18 / -18 lines

from line 8
88 
99* **Model capabilities:** Control how Claude reasons and formats responses.
1010* **Tools:** Let Claude take actions on the web or in your environment.
11* **Tool infrastructure:** Handles discovery and orchestration at scale.
12* **Context management:** Keeps long-running sessions efficient.
11* **Tool infrastructure:** Handle discovery and orchestration at scale.
12* **Context management:** Keep long-running sessions efficient.
1313* **Files and assets:** Manage the documents and data you provide to Claude.
1414 
1515If you're new, start with [model capabilities](https://platform.claude.com/docs/en/build-with-claude/overview#model-capabilities) and [tools](https://platform.claude.com/docs/en/build-with-claude/overview#tools). Return to the other sections when you're ready to optimize cost, latency, or scale.
from line 41
4141| Feature | Description | Zero Data Retention (ZDR) | Availability |
4242| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
4343| [Context windows](https://platform.claude.com/docs/en/build-with-claude/context-windows) | Up to 1M tokens for processing large documents, extensive code bases, and long conversations. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
44| [Adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) | Let Claude dynamically determine when and how much to think. The only thinking mode on Claude 4.7 and later models. Use the effort parameter to control thinking depth. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
44| [Adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) | Let Claude dynamically determine when and how much to think. The only thinking mode on Claude 4.7 and later models. Use the `effort` parameter to control thinking depth. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
4545| [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) | Process large volumes of requests asynchronously for cost savings. Send batches with a large number of queries per batch. Batch API calls cost 50% less than standard API calls. | Not ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws /> |
4646| [Citations](https://platform.claude.com/docs/en/build-with-claude/citations) | Ground Claude's responses in source documents. With Citations, Claude can provide detailed references to the exact sentences and passages it uses to generate responses, leading to more verifiable, trustworthy outputs. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
4747| [Data residency](https://platform.claude.com/docs/en/manage-claude/data-residency) | Control where model inference runs using geographic controls. Specify `"global"` or `"us"` routing per request through the `inference_geo` parameter. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws /> |
48| [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) | Control how many tokens Claude uses when responding with the effort parameter, trading off between response thoroughness and token efficiency. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
49| [Fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit) | Avoid paying the prompt-cache cost twice when you retry a refused request on another model. The refusal carries a credit token, and echoing it on the retry bills the retry as though the conversation had been on the new model all along. Message Batches results do not include fallback credit tokens. | Not ZDR eligible\* | <PlatformAvailability claudeApiBeta claudePlatformAwsBeta bedrockBeta vertexAiBeta azureAiBeta /> |
48| [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) | Control how many tokens Claude uses when responding with the `effort` parameter, trading off between response thoroughness and token efficiency. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
49| [Fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit) | Avoid paying the prompt-cache cost twice when you retry a refused request on another model. The refusal carries a credit token, and echoing it on the retry bills the retry as though the conversation had been on the new model from the start. Message Batches results do not include fallback credit tokens. | Not ZDR eligible\* | <PlatformAvailability claudeApiBeta claudePlatformAwsBeta bedrockBeta vertexAiBeta azureAiBeta /> |
5050| [PDF support](https://platform.claude.com/docs/en/build-with-claude/pdf-support) | Process and analyze text and visual content from PDF documents. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
51| [Search results](https://platform.claude.com/docs/en/build-with-claude/search-results) | Enable natural citations for RAG applications by providing search results with proper source attribution. Achieve web search-quality citations for custom knowledge bases and tools. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
51| [Search results](https://platform.claude.com/docs/en/build-with-claude/search-results) | Get natural citations for RAG applications by providing search results with proper source attribution. Achieve web search-quality citations for custom knowledge bases and tools. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
5252| [Server-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback) | Retry a refused request inside a single API call. Use the `"default"` mode to apply Anthropic's recommended fallback models, or name up to three models of your own; when the requested model declines, the API runs the next model in the chain on the same request. The `fallbacks` parameter is not available in the Message Batches API. | Not ZDR eligible\* | <PlatformAvailability claudeApiBeta /> |
5353| [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) | Guarantee schema conformance with two approaches: JSON outputs for structured data responses, and strict tool use for validated tool inputs. | [ZDR eligible (qualified)](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#data-retention)\* | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
5454| [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) | Enhanced reasoning capabilities for complex tasks, with an optional summary of Claude's reasoning before its final answer. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
from line 55
5555 
5656## Tools
5757 
58Built-in tools that Claude invokes through `tool_use`. Server-side tools are run by the platform; client-side tools are implemented and executed by you.
58Built-in tools that Claude calls through `tool_use`. Server-side tools are run by the platform; client-side tools are implemented and run by you.
5959 
6060### Server-side tools
6161 
from line 63
6363| --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------- |
6464| [Advisor tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool) | Pair a faster executor model with a higher-intelligence advisor model that provides strategic guidance mid-generation for long-horizon agentic workloads. | ZDR eligible | <PlatformAvailability claudeApiBeta claudePlatformAwsBeta /> |
6565| [Code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) | Run code in a sandboxed environment for advanced data analysis, calculations, and file processing. Free when used with web search or web fetch. | Not ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws azureAi />† |
66| [Web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool) | Retrieve full content from specified web pages and PDF documents for in-depth analysis. | ZDR eligible\* | <PlatformAvailability claudeApi claudePlatformAws azureAi /> |
66| [Web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool) | Retrieve full content from specified webpages and PDF documents for in-depth analysis. | ZDR eligible\* | <PlatformAvailability claudeApi claudePlatformAws azureAi /> |
6767| [Web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) | Augment Claude's comprehensive knowledge with current, real-world data from across the web. | ZDR eligible\* | <PlatformAvailability claudeApi claudePlatformAws vertexAi azureAi /> |
6868 
6969### Client-side tools
7070 
71| Feature | Description | ZDR | Availability |
72| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------ | ----------------------------------------------------------------------------------------- |
73| [Bash](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) | Execute bash commands and scripts to interact with the system shell and perform command-line operations. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
74| [Browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) | Navigate, read, and interact with webpages in your own browser environment. | ZDR eligible | <PlatformAvailability claudeApi vertexAi /> |
75| [Computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) | Control computer interfaces by taking screenshots and issuing mouse and keyboard commands. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAwsBeta bedrockBeta vertexAi azureAiBeta /> |
76| [Memory](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool) | Enable Claude to store and retrieve information across conversations. Build knowledge bases over time, maintain project context, and learn from past interactions. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
77| [Text editor](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool) | Create and edit text files with a built-in text editor interface for file manipulation tasks. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
71| Feature | Description | ZDR | Availability |
72| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------------------------------------------------------- |
73| [Bash](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) | Run bash commands and scripts to interact with the system shell and perform command-line operations. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
74| [Browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) | Navigate, read, and interact with webpages in your own browser environment. | ZDR eligible | <PlatformAvailability claudeApi vertexAi /> |
75| [Computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) | Control computer interfaces by taking screenshots and issuing mouse and keyboard commands. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAwsBeta bedrockBeta vertexAi azureAiBeta /> |
76| [Memory](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool) | Allow Claude to store and retrieve information across conversations. Build knowledge bases over time, maintain project context, and learn from past interactions. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
77| [Text editor](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool) | Create and edit text files with a built-in text editor interface for file manipulation tasks. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
7878 
7979## Tool infrastructure
8080 
from line 86
8686| [Fine-grained tool streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) | Stream tool use parameters without buffering/JSON validation, reducing latency for receiving large parameters. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
8787| [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) | Connect to remote [MCP](https://modelcontextprotocol.io/) servers directly from the Messages API without a separate MCP client. | Not ZDR eligible | <PlatformAvailability claudeApiBeta claudePlatformAwsBeta azureAiBeta /> |
8888| [Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) | Enable Claude to call your tools programmatically from within code execution containers, reducing latency and token consumption for multi-tool workflows. | Not ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws azureAi />† |
89| [Tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) | Scale to thousands of tools by dynamically discovering and loading tools on-demand using regex- and BM25-based search, optimizing context usage and improving tool selection accuracy. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
89| [Tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) | Scale to thousands of tools by dynamically discovering and loading tools on demand using regex- and BM25-based search, optimizing context usage and improving tool selection accuracy. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
9090 
9191## Context management
9292 
from line 98
9898| [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) | Automatically manage conversation context with configurable strategies. Supports clearing tool results when approaching token limits and managing thinking blocks in extended thinking conversations. | ZDR eligible | <PlatformAvailability claudeApiBeta claudePlatformAwsBeta bedrockBeta vertexAiBeta azureAiBeta /> |
9999| [Automatic prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) | Simplify prompt caching to a single API parameter. The system automatically caches the last cacheable block in your request, moving the cache point forward as conversations grow. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
100100| [Prompt caching (5m)](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) | Provide Claude with more background knowledge and example outputs to reduce costs and latency. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
101| [Prompt caching (1hr)](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) | Extended 1-hour cache duration for less frequently accessed but important context, complementing the standard 5-minute cache. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
102| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | Token counting enables you to determine the number of tokens in a message before sending it to Claude, helping you make informed decisions about your prompts and usage. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
101| [Prompt caching (1h)](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) | Extended 1-hour cache duration for less frequently accessed but important context, complementing the standard 5-minute cache. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
102| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | Token counting allows you to determine the number of tokens in a message before sending it to Claude, helping you make informed decisions about your prompts and usage. | ZDR eligible | <PlatformAvailability claudeApi claudePlatformAws bedrock vertexAi azureAi /> |
103103 
104104## Files and assets
105105 

build-with-claude/pdf-support Changed · +22 / -22 lines

## Before you start ## Before you begin

from line 19
1919 
2020* Analyzing financial reports and understanding charts/tables
2121* Extracting key information from legal documents
22* Assisting with document translation
22* Helping with document translation
2323* Converting document information into structured formats
2424 
25## Before you begin
25## Before you start
2626 
2727### Check PDF requirements
2828 
2929Claude works with any standard PDF. Ensure your request size meets these requirements:
3030 
31| Requirement | Limit |
32| ------------------------- | -------------------------------------------------------------------------------------------------- |
33| Maximum request size | 32 MB ([varies by platform](https://platform.claude.com/docs/en/api/overview#request-size-limits)) |
34| Maximum pages per request | 600 (100 when the request's context window is under 1M tokens) |
35| Format | Standard PDF (no passwords/encryption) |
31| Requirement | Limit |
32| ------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
33| Maximum request size | 32 MB (varies by platform; see [request size limits](https://platform.claude.com/docs/en/api/overview#request-size-limits)) |
34| Maximum pages per request | 600 (100 when the request's context window is under 1M tokens) |
35| Format | Standard PDF (no passwords/encryption) |
3636 
3737Both limits are on the entire request payload, including any other content sent alongside PDFs. For large PDFs, consider uploading with the [Files API](https://platform.claude.com/docs/en/build-with-claude/files) and referencing by `file_id` to keep request payloads small.
3838 
from line 116
116116 "model": "claude-opus-5-5",
117117 "max_tokens": 1024,
118118 "messages": [{
119 "role": "user",
120 "content": [{
121 "type": "document",
122 "source": {
123 "type": "url",
124 "url": "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
125 }
126 },
127 {
128 "type": "text",
129 "text": "What are the key findings in this document?"
130 }]
119 "role": "user",
120 "content": [{
121 "type": "document",
122 "source": {
123 "type": "url",
124 "url": "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
125 }
126 },
127 {
128 "type": "text",
129 "text": "What are the key findings in this document?"
130 }]
131131 }]
132 }'
132 }'
133133 ```
134134 
135135 ```bash CLI
from line 1024
10241024 Claude can reference both textual and visual content when it responds. You can further improve performance by integrating PDF support with:
10251025 
10261026 * [Use prompt caching](https://platform.claude.com/docs/en/build-with-claude/pdf-support#use-prompt-caching): To improve performance for repeated analysis.
1027 * [Process document batches](https://platform.claude.com/docs/en/build-with-claude/pdf-support#process-document-batches): For high-volume document processing.
1027 * [Process document batches](https://platform.claude.com/docs/en/build-with-claude/pdf-support#process-document-batches): To process documents at high volume.
10281028 * [Tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview): To extract specific information from documents for use as tool inputs.
10291029 </Step>
10301030</Steps>
from line 1953
19531953 
19541954<CardGroup cols={2}>
19551955 <Card title="Vision" icon="image" href="https://platform.claude.com/docs/en/build-with-claude/vision">
1956 Claude's vision capabilities allow it to understand and analyze images, opening up exciting possibilities for multimodal interaction.
1956 Claude's vision capabilities allow it to process and analyze images, opening up exciting possibilities for multimodal interaction.
19571957 </Card>
19581958 
19591959 <Card title="Try PDF examples" icon="file" href="https://platform.claude.com/cookbook/multimodal-getting-started-with-vision">

build-with-claude/preserved-thinking Changed · +43 / -44 lines

from line 25
2525* [Summarizes or drops old turns on the client](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client) and keeps recent turns with their thinking
2626* [Adds, removes, or edits entries in `tools`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#tool-changes)
2727* [Adds a reminder to a user turn](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) and removes or rewrites it later
28* [Drops some `thinking` blocks and keeps later ones](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#append-assistant-turns-exactly-as-returned), or removes them and [later puts them back](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#prefix-check)
28* [Drops some `thinking` blocks and keeps later ones](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#append-assistant-turns-exactly-as-returned), or removes them and [later restores those blocks](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#prefix-check)
2929* [Rebuilds a saved session from templates](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#faq) instead of replaying what it sent
3030 
3131On an older account, none of these produces an error unless the request sets `prefix_mismatch_behavior`, so a run with no errors on your own key doesn't show whether your code is affected. If people run your tool with their own API keys, those on newer accounts get the 400 error before you do. To see what they see without changing how your requests behave, send the `thinking-binding-controls-2026-08-01` beta header. On an older account, each response then flags blocks that fail the check, and the model still reads them (see [Set the mismatch behavior and read `input_transformations`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#preserved-thinking-controls)).
from line 45
4545* **A conversation that moves to Claude Fable 5.1 from an earlier model, or from Claude Opus 5.5 on the Claude API, keeps its reasoning.** The earlier model's thinking blocks stay readable, so the model thinks as usual from the first turn after the switch.
4646* **A conversation that moves from Claude Fable 5.1 to any model other than Claude Mythos 5.1 loses Claude Fable 5.1's reasoning for that request.** This occurs when a router sends a turn to a cheaper model, after a [classifier refusal fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback), or during a [server-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#server-side-fallback). The API removes the unreadable blocks before the prompt reaches the model. They aren't billed and don't count toward `input_tokens`.
4747 
48Keep sending the full history on every request, thinking blocks included, and let the API drop what the current model can't read. The API never edits your `messages` array, so the dropped blocks stay in your history. When the same history goes back to Claude Fable 5.1, its blocks are readable again, along with the earlier model's thinking. The reasoning is lost for good only if your client removes the blocks itself, for example a harness that strips thinking on a model switch or rebuilds the history from what each model used.
48Keep sending the full history on every request, thinking blocks included, and let the API drop what the current model can't read. The API never edits your `messages` array, so the dropped blocks stay in your history. When the same history goes back to Claude Fable 5.1, its blocks are readable again, along with the earlier model's thinking. The reasoning is permanently lost only if your client removes the blocks itself, for example a harness that strips thinking on a model switch or rebuilds the history from what each model used.
4949 
5050<Frame>
5151 ![Animation: switching to Claude Opus skips Claude Fable 5.1's thinking for that turn; switching back, everything is read again](https://platform.claude.com/docs/images/preserved-thinking-model-switch.svg)
from line 87
8787 
8888Earlier thinking blocks aren't in the prefix, but each thinking block records which thinking block came before it, across turns. You can remove thinking blocks from the start of the history (oldest first), from the end, or all of them. What fails is a gap: the thinking blocks you keep must be an unbroken run of the original sequence, so removing one from the middle invalidates the thinking blocks after it. Once you remove a block, leave it out. Putting it back invalidates the thinking blocks produced while it was gone.
8989 
90Keep `system` and `tools` fixed for the session and treat `messages` as append-only. The same discipline keeps the prefix stable for [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): the edits that invalidate thinking are the edits that restart the cache.
90Keep `system` and `tools` fixed for the session and treat `messages` as append-only. The same discipline keeps the prefix stable for [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): most edits that invalidate thinking also restart the cache.
9191 
9292### What the API does with an invalid block
9393 
from line 97
9797* **`"drop_block"`:** the API drops each failing block and every thinking block after it, and the request succeeds. Dropped blocks aren't billed. The model answers that turn without using reasoning from dropped blocks, and the prompt cache restarts at the edit. The response lists each dropped block in `input_transformations` (on the `message_start` event when streaming) with `reason: "prefix_binding_mismatch"`.
9898 
9999<Warning>
100 `"drop_block"` keeps requests succeeding, but it doesn't fix the edit that caused the mismatch, and it has a cost. Dropping blocks can significantly increase the output tokens generated, especially at higher effort levels or when blocks are dropped on every turn. For more information, see [Output-token cost of `"drop_block"`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#drop-block-cost). Dropped blocks aren't billed, but Claude re-creates the reasoning it can no longer read, so it generates more output tokens. Output quality might also change on tasks where later turns build on earlier reasoning. Use `"drop_block"` as a stopgap while you fix the edit, but not as a long-term setting.
100 `"drop_block"` keeps requests succeeding, but it doesn't fix the edit that caused the mismatch, and it has a cost. Dropping blocks can significantly increase the output tokens generated, especially when blocks are dropped on every turn. For more information, see [Output-token cost of `"drop_block"`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#drop-block-cost). Dropped blocks aren't billed, but Claude re-creates the reasoning it can no longer read, so it generates more output tokens. Output quality might also change on tasks where later turns build on earlier reasoning. Use `"drop_block"` as a stopgap while you fix the edit, but not as a long-term setting.
101101</Warning>
102102 
103103Count the responses in each session whose `input_transformations` has a `prefix_binding_mismatch` entry, alert on them, and replace each edit with the matching pattern in [Make changes without editing the prefix](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#replace-prefix-edits). In the Message Batches API, an item that leaves the field unset doesn't fail. Where the API enforces the check by default, it drops the failing blocks instead. Set `"error"` explicitly there if you want batch items to fail.
from line 104
104104 
105105Both the field and the `input_transformations` array require the `thinking-binding-controls-2026-08-01` [beta header](https://platform.claude.com/docs/en/api/beta-headers). [Set the mismatch behavior and read `input_transformations`](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#preserved-thinking-controls) shows the request in each SDK.
106106 
107The 400 message begins:
107The 400 message starts:
108108 
109109```text wrap
110110messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to "drop_block".
from line 122
122122 
123123#### Output-token cost of `"drop_block"`
124124 
125In Anthropic's testing on a multi-turn coding benchmark, dropping thinking blocks once per session increased output tokens by 2.5% at low effort, 3.9% at medium, 4.5% at high, and 20.1% at max. Dropping them on every turn after the first increased output tokens by 4.6% at low effort, 9.7% at medium, 10.3% at high, and 67.1% at max. These figures are estimates with wide error bars, and the impact on your workload depends on your harness.
126 
127125When Claude can no longer read reasoning from earlier turns, it re-creates that reasoning, so requests that drop thinking blocks generate more output tokens and can take longer to respond. A drop on every turn costs more than an occasional drop, and how much more depends on your harness: how often it edits the prefix and how much each turn builds on earlier reasoning.
128126 
129127Before you rely on `"drop_block"`, run evals on your own workload to measure the increase. If it's small, `"drop_block"` can keep requests succeeding while you fix the edit. Either way, fixing the edit with a pattern from [Make changes without editing the prefix](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#replace-prefix-edits) is a better long-term solution.
from line 368
370368 client = Anthropic::Client.new
371369 
372370 response = client.beta.messages.create(
373 model: "claude-fable-5-1",
371 model: Anthropic::Model::CLAUDE_FABLE_5_1,
374372 max_tokens: 16_000,
375373 thinking: {
376374 type: "adaptive",
from line 415
417415 
418416Each row compares two consecutive requests:
419417 
420| Change between requests | Later thinking blocks |
421| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
422| Append messages at the end | Valid |
423| Add a tool with `defer_loading: true` that nothing has referenced yet | Valid |
424| Remove `thinking` blocks from the start of the history, from the end, or all of them | Valid (the model loses that reasoning) |
425| Change any request parameter outside `system`, `tools`, and `messages` (`effort`, `max_tokens`, `output_config`, `tool_choice`, `metadata`, `thinking.display`, and so on) | Valid |
426| Add, move, or remove `cache_control` markers | Valid |
427| A rotating signed URL that returns the same bytes | Valid |
428| Server-side compaction or context editing removes or replaces content | Valid (the check compares what you sent, not the server's edited copy) |
429| A cleared [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) left in place | Valid |
430| Edit, reorder, or delete any earlier `user`, `assistant`, or `system` message | Invalid, except when the signed block from [on-demand compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand) replaces the messages it summarizes, under the [conditions for kept thinking](https://platform.claude.com/docs/en/build-with-claude/compaction-thinking-blocks#conditions-for-kept-thinking-to-stay-valid) |
431| Re-render the context you put in the first user message with a changed value | Invalid for every thinking block |
432| Clear or shorten an earlier `tool_result`, re-encode an earlier image, or change an earlier `tool_use` input | Invalid for every later thinking block |
433| Add a text block to an earlier user turn, or remove one you added last time | Invalid |
434| Change the top-level `system` string or blocks | Invalid |
435| Add, remove, rename, or edit a tool in `tools` | Invalid |
436| Remove a `thinking` block from the middle of the history and keep later ones | Invalid for every later thinking block |
437| Put back a `thinking` block you removed on an earlier request | Invalid for thinking blocks produced while it was gone |
438| An image or document URL that returns different bytes on the next request | Invalid |
439| The same turn-scoped message deleted or reworded on a later request | Invalid |
418| Change between requests | Later thinking blocks |
419| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
420| Append messages at the end | Valid |
421| Add a tool with `defer_loading: true` that nothing has referenced yet | Valid |
422| Remove `thinking` blocks from the start of the history, from the end, or all of them | Valid (the model loses that reasoning) |
423| Change any request parameter outside `model`, `system`, `tools`, and `messages` (`effort`, `max_tokens`, `output_config`, `tool_choice`, `metadata`, `thinking.display`, and so on) | Valid |
424| Change `model` | Valid for blocks that the new model can read; the API drops the others without an error (see [Switching models mid-conversation](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#switching-models)) |
425| Add, move, or remove `cache_control` markers | Valid |
426| A rotating signed URL that returns the same bytes | Valid |
427| Server-side compaction or context editing removes or replaces content | Valid (the check compares what you sent, not the server's edited copy) |
428| A cleared [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) left in place | Valid |
429| Edit, reorder, or delete any earlier `user`, `assistant`, or `system` message | Invalid, except when the signed block from [on-demand compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand) replaces the messages it summarizes, under the [conditions for kept thinking](https://platform.claude.com/docs/en/build-with-claude/compaction-thinking-blocks#conditions-for-kept-thinking-to-stay-valid) |
430| Re-render the context you put in the first user message with a changed value | Invalid for every thinking block |
431| Clear or shorten an earlier `tool_result`, re-encode an earlier image, or change an earlier `tool_use` input | Invalid for every later thinking block |
432| Add a text block to an earlier user turn, or remove one you added last time | Invalid |
433| Change the top-level `system` string or blocks | Invalid |
434| Add, remove, rename, or edit a tool in `tools` | Invalid |
435| Remove a `thinking` block from the middle of the history and keep later ones | Invalid for every later thinking block |
436| Put back a `thinking` block you removed on an earlier request | Invalid for thinking blocks produced while it was gone |
437| An image or document URL that returns different bytes on the next request | Invalid |
438| The same turn-scoped message deleted or reworded on a later request | Invalid |
440439 
441440### Check whether your code edits the prefix
442441 
from line 690
691690 user_turns.each do |user_turn|
692691 messages << {role: "user", content: user_turn}
693692 response = client.beta.messages.create(
694 model: "claude-fable-5-1",
693 model: Anthropic::Model::CLAUDE_FABLE_5_1,
695694 max_tokens: 16_000,
696695 thinking: {
697696 type: "adaptive",
from line 1015
10161015 # Only the last request adds a system prompt, which changes the prefix on purpose
10171016 system_param = (turn_index == user_turns.length - 1) ? {system_: "Answer briefly."} : {}
10181017 response = client.beta.messages.create(
1019 model: "claude-fable-5-1",
1018 model: Anthropic::Model::CLAUDE_FABLE_5_1,
10201019 max_tokens: 16_000,
10211020 thinking: {type: "adaptive"},
10221021 messages: messages,
from line 1038
10391038thinking blocks: 1, flagged: 2
10401039```
10411040 
1042The third response flags every thinking block from the earlier turns, one per turn in this run, because the new system prompt comes before all of them. The model still read them.
1041The third response flags every thinking block from the earlier turns, one for each turn in this run, because the new system prompt comes before all of them. The model still read them.
10431042 
1044Handle these entries as you would `prefix_binding_mismatch` drops. The edit is before the first block listed: diff `system`, `tools`, and `messages` up to that block's `path` against the previous request to find it, then replace it with the matching pattern in [Make changes without editing the prefix](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#replace-prefix-edits). On a new account, or on any request that sets `prefix_mismatch_behavior`, the API instead rejects the request or drops the failing blocks. The entries are a lower bound on what enforcement would remove: with `"drop_block"`, a failing block also takes the rest of that turn's thinking blocks with it, and removing one block can make the next one fail too. When the API only records the check, it judges each block on its own and lists a block only if that block fails.
1043Handle these entries as you would `prefix_binding_mismatch` drops. The edit is before the first block listed: diff `system`, `tools`, and `messages` up to that block's `path` against the previous request to find it, then replace it with the matching pattern in [Make changes without editing the prefix](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#replace-prefix-edits). On a new account, or on any request that sets `prefix_mismatch_behavior`, the API instead rejects the request or drops the failing blocks. The entries are a lower bound on what enforcement would remove: with `"drop_block"`, a failing block also takes the rest of that turn's thinking blocks with it, and removing one block can make the next one fail too. When the API only records the check, it evaluates each block on its own and lists a block only if that block fails.
10451044 
10461045## Make changes without editing the prefix
10471046 
from line 1157
11581157]
11591158```
11601159 
1161A user message that contains only `tool_result` blocks counts as the "next user message", so `messages[3]` is already cleared. It adds nothing to what the model sees and costs no input tokens, but because it's still in the array, the thinking in `messages[4]` stays valid. `messages[6]` is the copy the model sees this turn. On later requests, keep both where they are and append a fresh copy after the next `tool_result` message.
1160A user message that contains only `tool_result` blocks counts as the "next user message," so `messages[3]` is already cleared. It adds nothing to what the model receives and costs no input tokens, but because it's still in the array, the thinking in `messages[4]` stays valid. `messages[6]` is the copy the model receives this turn. On later requests, keep both where they are and append a fresh copy after the next `tool_result` message.
11621161 
11631162### Add or remove tools with `tool_addition` and `tool_removal`
11641163 
from line 1165
11661165 
11671166You have two ways to use these blocks:
11681167 
1169* **Declare every tool up front.** Put every tool the session might need in `tools` on the first request, with `defer_loading: true` on any the model shouldn't see yet. Then turn tools on and off with `tool_addition` and `tool_removal` blocks that name them.
1170* **Start with a snapshot and add tools as you go.** Put the tools you know about in `tools` on the first request. When a new tool comes along, define it inside a `tool_addition` block instead of editing `tools`.
1168* **Declare every tool up front.** Put every tool the session might need in `tools` on the first request, with `defer_loading: true` on any that shouldn't be offered to the model yet. Then turn tools on and off with `tool_addition` and `tool_removal` blocks that name them.
1169* **Start with a snapshot and add tools as you go.** Put the tools you know about in `tools` on the first request. When you learn about another tool, define it inside a `tool_addition` block instead of editing `tools`.
11711170 
11721171Either way, `tools` never changes, so earlier thinking stays valid and the prompt cache still hits, with the one exception noted later in this section.
11731172 
from line 1242
12431242Another common prefix edit is client-side trimming: dropping or summarizing the oldest turns and keeping the recent ones verbatim. The kept turns' thinking blocks were produced while the removed history was still in place, so they fail the check. The server-side equivalents don't count as edits, because the check compares the conversation as you sent it:
12441243 
12451244* [On-demand compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand) (beta) returns the summary from a separate request, which can [run in the background](https://platform.claude.com/docs/en/build-with-claude/compaction-background), and you send the returned block in place of the messages it summarizes. The check accepts that swap, so the turns you keep can stay valid with their thinking, under the [conditions for kept thinking](https://platform.claude.com/docs/en/build-with-claude/compaction-thinking-blocks#conditions-for-kept-thinking-to-stay-valid). [Request a summary](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand#request-a-summary) shows the request and names the beta header it needs.
1246* [Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold) summarizes older turns into a compaction block when the context approaches a threshold you set, and the checked prefix restarts from that block. Its [`instructions` parameter](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#custom-summarization-instructions) takes your own summarization prompt, such as "preserve every ticker, position size, and stated assumption".
1245* [Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold) summarizes older turns into a compaction block when the context approaches a threshold you set, and the checked prefix restarts from that block. Its [`instructions` parameter](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#custom-summarization-instructions) takes your own summarization prompt, such as "preserve every ticker, position size, and stated assumption."
12471246* [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) clears old tool results or old thinking blocks by rule, oldest first. The strategies are `clear_tool_uses_20250919` and `clear_thinking_20251015`.
12481247 
12491248### Compact on the client
from line 1254
12551254When the conversation grows too long, summarize the whole session into one user message and send only that message plus the next instruction. Nothing earlier is replayed, so there's no thinking left to fail the check, and the model reasons afresh from the summary.
12561255 
12571256<Frame>
1258 ![Simple compaction: request 4 sends the full history with thinking on each assistant turn; request 5 sends one user message holding a summary of turns 1 to 4 plus the next instruction, so no earlier thinking is sent and nothing is checked](https://platform.claude.com/docs/images/preserved-thinking-simple-compaction.svg)
1257 ![Simple compaction: request 4 sends the full history with thinking; request 5 sends one summary message, so nothing is checked](https://platform.claude.com/docs/images/preserved-thinking-simple-compaction.svg)
12591258</Frame>
12601259 
12611260```json
from line 1266
12671266]
12681267```
12691268 
1270Claude models are trained on long-horizon tasks with this scheme and for most workloads it performs well.
1269Claude models are trained on long-horizon tasks with this scheme, and for most workloads it performs well.
12711270 
12721271#### Keep-tail compaction
12731272 
1274Keep-tail compaction summarizes the older turns and keeps the most recent turns verbatim, so the model still sees the last few exchanges word for word. If you write the summary yourself, it breaks the rule: the kept assistant turns still carry thinking blocks that were produced when the original turns, not the summary, came before them. Those blocks fail.
1273Keep-tail compaction summarizes the older turns and keeps the most recent turns verbatim, so the model still receives the last few exchanges word for word. If you write the summary yourself, it breaks the rule: the kept assistant turns still carry thinking blocks that were produced when the original turns, not the summary, came before them. Those blocks fail.
12751274 
12761275To keep that thinking, have the API write the summary with on-demand compaction. [Compaction that keeps recent turns](https://platform.claude.com/docs/en/build-with-claude/compaction-keep-recent-turns) shows how, and [Conditions for kept thinking to stay valid](https://platform.claude.com/docs/en/build-with-claude/compaction-thinking-blocks#conditions-for-kept-thinking-to-stay-valid) lists when the kept thinking stays valid.
12771276 
from line 1277
12781277The rest of this section covers a summary you write yourself.
12791278 
12801279<Frame>
1281 ![Keep-tail compaction: the history is replaced by a summary of turns 1 and 2 followed by turns 3 to 5 verbatim; the thinking on assistant turns 3 and 4 was produced after the original turns, not the summary, so it fails; the same request sent with prefix\_mismatch\_behavior drop\_block succeeds, the API drops those two blocks and lists them in input\_transformations](https://platform.claude.com/docs/images/preserved-thinking-keep-tail-compaction.svg)
1280 ![Keep-tail compaction: thinking on kept turns 3 and 4 fails; with drop\_block, the API drops it and the request succeeds](https://platform.claude.com/docs/images/preserved-thinking-keep-tail-compaction.svg)
12821281</Frame>
12831282 
12841283Fix: keep the turns exactly as they are and send `prefix_mismatch_behavior: "drop_block"`. The API drops the stale thinking blocks, the model reads the kept turns' `text` and `tool_use` blocks, and the request succeeds.
from line 1473
14741473 ```
14751474</CodeGroup>
14761475 
1477The response carries the new assistant turn as usual, plus one `input_transformations` entry per dropped block. For the history in the diagram, that's the thinking on assistant turns 3 and 4:
1476The response carries the new assistant turn as usual, plus one `input_transformations` entry for each dropped block. For the history in the diagram, that's the thinking on assistant turns 3 and 4:
14781477 
14791478```json
14801479{
from line 1503
15041503#### Patterns that don't work with preserved thinking
15051504 
15061505* **Cutting turns out of the middle.** Removing individual turns invalidates every thinking block after them, and no compaction scheme avoids that. If you were cutting a turn to change an instruction, append a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions) instead. To remove old tool results or old thinking selectively, use server-side [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing).
1507* **Compacting in the middle of a tool round.** Don't compact between an assistant turn's `tool_use` and the `tool_result` that answers it. Send that assistant turn back with its thinking intact so the model finishes the round with its reasoning. See [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks).
1506* **Compacting in the middle of a tool round.** Don't compact between an assistant turn's `tool_use` and the `tool_result` that answers it. Send that assistant turn back with its thinking intact so the model completes the round with its reasoning. See [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks).
15081507 
15091508### Reference files by ID, not by a URL whose content changes
15101509 
from line 1568
15691568 
15701569<CardGroup cols={2}>
15711570 <Card title="Troubleshooting thinking" icon="hammer" href="https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting">
1572 Diagnose and fix the most common thinking failures: configuration 400 errors, empty or missing thinking blocks, max\_tokens stops, and cache misses.
1571 Diagnose and fix the most common thinking failures: configuration 400 errors, empty or missing thinking blocks, `max_tokens` stops, and cache misses.
15731572 </Card>
15741573 
15751574 <Card title="Mid-conversation system messages and tool changes" icon="messages" href="https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages">

build-with-claude/prompt-caching Changed · +65 / -65 lines

from line 12
1212 
1313There are two ways to enable prompt caching:
1414 
15* **[Automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching)**: Add a single `cache_control` field at the top level of your request. The system automatically applies the cache breakpoint to the last cacheable block and moves it forward as conversations grow. Best for multi-turn conversations where the growing message history should be cached automatically.
16* **[Explicit cache breakpoints](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints)**: Place `cache_control` directly on individual content blocks for fine-grained control over exactly what gets cached.
15* **[Automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching):** Add a single `cache_control` field at the top level of your request. The system automatically applies the cache breakpoint to the last cacheable block and moves it forward as conversations grow. Best for multi-turn conversations where the growing message history should be cached automatically.
16* **[Explicit cache breakpoints](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints):** Place `cache_control` directly on individual content blocks for fine-grained control over exactly what gets cached.
1717 
1818The simplest way to start is with automatic caching:
1919 
from line 196
196196 
1971971. The system checks if a prompt prefix, up to a specified cache breakpoint, is already cached from a recent query.
1981982. If found, it uses the cached version, reducing processing time and costs.
1993. Otherwise, it processes the full prompt and caches the prefix once the response begins.
1993. Otherwise, it processes the full prompt and caches the prefix once the response starts.
200200 
201201This is especially useful for:
202202 
from line 260
260260<Note>
261261 The previous table reflects the following pricing multipliers for prompt caching:
262262 
263 * 5-minute cache write tokens are 1.25 times the base input tokens price
264 * 1-hour cache write tokens are 2 times the base input tokens price
265 * Cache read tokens are 0.1 times the base input tokens price (see the table footnote for per-model exceptions)
263 * Cache write tokens with a 5-minute TTL are 1.25 times the base input tokens price.
264 * Cache write tokens with a 1-hour TTL are 2 times the base input tokens price.
265 * Cache read tokens are 0.1 times the base input tokens price (see the table footnote for per-model exceptions).
266266 
267 These multipliers stack with other pricing modifiers such as the Batch API discount, [long context pricing](https://platform.claude.com/docs/en/about-claude/pricing#long-context-pricing), and data residency. On a model priced by prompt length, cache reads and cache writes count toward a request's prompt length. See [pricing](https://platform.claude.com/docs/en/about-claude/pricing) for full details.
267 These multipliers stack with other pricing modifiers such as the Batch API discount, [long context pricing](https://platform.claude.com/docs/en/about-claude/pricing#long-context-pricing), and data residency. On a model priced by prompt length, cache reads and cache writes count toward a request's prompt length. See [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing) for full details.
268268</Note>
269269 
270270***
from line 533
533533 
534534#### How automatic prefix checking works
535535 
536You can use just one cache breakpoint at the end of your static content, and the system will automatically find the longest prefix that a prior request already wrote to the cache. Understanding how this works helps you optimize your caching strategy.
536You can use just one cache breakpoint at the end of your static content, and the system automatically finds the longest prefix that a prior request already wrote to the cache. Understanding how this works helps you optimize your caching strategy.
537537 
538538**Three core principles:**
539539 
5401. **Cache writes happen only at your breakpoint.** Marking a block with `cache_control` writes exactly one cache entry: a hash of the prefix ending at that block. The system does not write entries for any earlier position. Because the hash is cumulative, covering everything up to and including the breakpoint, changing any block at or before the breakpoint produces a different hash on the next request.
5401. **Cache writes occur only at your breakpoint.** Marking a block with `cache_control` writes exactly one cache entry: a hash of the prefix ending at that block. The system does not write entries for any earlier position. Because the hash is cumulative, covering everything up to and including the breakpoint, changing any block at or before the breakpoint produces a different hash on the next request.
541541 
5425422. **Cache reads look backward for entries that prior requests wrote.** On each request the system computes the prefix hash at your breakpoint and checks for a matching cache entry. If none exists, it walks backward one block at a time, checking whether the prefix hash at each earlier position matches something already in the cache. It is looking for prior writes, not for stable content.
543543 
5443. **The lookback window is 20 blocks.** The system checks at most 20 positions per breakpoint, counting the breakpoint itself as the first. If the system finds no matching entry in that window, checking stops (or resumes from the next explicit breakpoint, if any). On the Claude API, a run of consecutive `tool_use` blocks counts as one position, and so does a run of consecutive `tool_result` blocks, so a turn with many parallel tool calls doesn't push the previous request's entry out of the window on its own.
5443. **The lookback window is 20 blocks.** The system checks at most 20 positions for each breakpoint, counting the breakpoint itself as the first. If the system finds no matching entry in that window, checking stops (or resumes from the next explicit breakpoint, if any). On the Claude API, a run of consecutive `tool_use` blocks counts as one position, and so does a run of consecutive `tool_result` blocks, so a turn with many parallel tool calls doesn't push the previous request's entry out of the window on its own.
545545 
546546**Example: Lookback in a growing conversation**
547547 
from line 548
548548You append new blocks each turn and set `cache_control` on the final block of each request:
549549 
550550* **Turn 1:** 10 blocks, breakpoint on block 10. No prior cache entries exist. The system writes an entry at block 10.
551* **Turn 2:** 15 blocks, breakpoint on block 15. Block 15 has no entry, so the system walks back to block 10 and finds the turn-1 entry. Cache hit at block 10; the system processes only blocks 11 through 15 fresh and writes a new entry at block 15.
551* **Turn 2:** 15 blocks, breakpoint on block 15. Block 15 has no entry, so the system walks back to block 10 and finds the turn-1 entry. Cache hit at block 10. The system processes only blocks 11 through 15 fresh and writes a new entry at block 15.
552552* **Turn 3:** 35 blocks, breakpoint on block 35. The system checks 20 positions (blocks 35 through 16) and finds nothing. The turn-2 entry at block 15 is one position outside the window, so there is no cache hit. Adding a second breakpoint at block 15 starts a second lookback window there, which finds the turn-2 entry.
553553 
554554**Common mistake: Breakpoint on content that changes every request**
from line 558
558558* **Request 1:** Cache write at block 6. The hash includes the timestamp.
559559* **Request 2:** The timestamp differs, so the prefix hash at block 6 differs. The lookback walks through blocks 5, 4, 3, 2, and 1, but the system never wrote an entry at any of those positions. No cache hit. You pay for a fresh cache write on every request and never get a read.
560560 
561The lookback does not find stable content behind your breakpoint and cache it. It finds entries that prior requests already wrote, and writes happen only at breakpoints. Move `cache_control` to block 5, the last block that stays the same across requests, and every subsequent request reads the cached prefix. [Automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) hits the same trap: it places the breakpoint on the last cacheable block, which in this structure is the one that changes every request, so use an explicit breakpoint on block 5 instead.
561The lookback does not find stable content behind your breakpoint and cache it. It finds entries that prior requests already wrote, and writes occur only at breakpoints. Move `cache_control` to block 5, the last block that stays the same across requests, and every subsequent request reads the cached prefix. [Automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) has the same problem: it places the breakpoint on the last cacheable block, which in this structure is the one that changes every request, so use an explicit breakpoint on block 5 instead.
562562 
563563**Key takeaway:** Place `cache_control` on the last block whose prefix is identical across the requests you want to share a cache. In a growing conversation the final block works as long as each turn adds fewer than 20 blocks: earlier content never changes, so the next request's lookback finds the prior write. For a prompt with a varying suffix (timestamps, per-request context, the incoming message), place the breakpoint at the end of the static prefix, not on the varying block.
564564 
from line 601
601601 
602602These minimums apply on every platform where each model is available.
603603 
604Shorter prompts cannot be cached, even if marked with `cache_control`. Any requests to cache fewer than this number of tokens will be processed without caching, and no error is returned. To verify whether a prompt was cached, check the [response usage fields](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#tracking-cache-performance): if both `cache_creation_input_tokens` and `cache_read_input_tokens` are 0, the prompt was not cached (likely because it did not meet the minimum length requirement).
604Shorter prompts cannot be cached, even if marked with `cache_control`. Any requests to cache fewer than this number of tokens are processed without caching, and no error is returned. To verify whether a prompt was cached, check the [response usage fields](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#tracking-cache-performance): if both `cache_creation_input_tokens` and `cache_read_input_tokens` are 0, the prompt was not cached (likely because it did not meet the minimum length requirement).
605605 
606606If your prompt falls just short of the minimum for your model and platform, expanding the cached content to reach the threshold is often worthwhile. Cache reads cost significantly less than uncached input tokens, so reaching the minimum can reduce costs for frequently reused prompts.
607607 
from line 609
609609 [Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock) is an AWS-operated platform. On Bedrock, see the [Bedrock prompt caching documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html) for the per-model minimums, failure behavior, and usage-field names that apply.
610610</Note>
611611 
612For concurrent requests, note that a cache entry only becomes available after the first response begins. If you need cache hits for parallel requests, wait for the first response before sending subsequent requests.
612For concurrent requests, note that a cache entry only becomes available after the first response starts. If you need cache hits for parallel requests, wait for the first response before sending subsequent requests.
613613 
614614Currently, "ephemeral" is the only supported cache type, which by default has a 5-minute lifetime.
615615 
from line 620
620620* Tools: Tool definitions in the `tools` array
621621* System messages: Content blocks in the `system` array
622622* Text messages: Content blocks in the `messages.content` array, for both user and assistant turns
623* Images & Documents: Content blocks in the `messages.content` array, in user turns
623* Images and documents: Content blocks in the `messages.content` array, in user turns
624624* Tool use and tool results: Content blocks in the `messages.content` array, in both user and assistant turns
625625 
626626Each of these elements can be cached, either automatically or by marking them with `cache_control`.
from line 627
627627 
628628### What cannot be cached
629629 
630While most request blocks can be cached, there are some exceptions:
630Although most request blocks can be cached, there are some exceptions:
631631 
632632* Thinking blocks cannot be cached directly with `cache_control`. However, thinking blocks CAN be cached alongside other content when they appear in previous assistant turns. When cached this way, they DO count as input tokens when read from cache.
633633 
634* Sub-content blocks (like [citations](https://platform.claude.com/docs/en/build-with-claude/citations)) themselves cannot be cached directly. Instead, cache the top-level block.
634* Sub-content blocks (such as [citations](https://platform.claude.com/docs/en/build-with-claude/citations)) themselves cannot be cached directly. Instead, cache the top-level block.
635635 
636 In the case of citations, the top-level document content blocks that serve as the source material for citations can be cached. This allows you to use prompt caching with citations effectively by caching the documents that citations will reference.
636 In the case of citations, the top-level document content blocks that serve as the source material for citations can be cached. This allows you to use prompt caching with citations effectively by caching the documents that citations reference.
637637 
638638* Empty text blocks cannot be cached.
639639 
from line 643
643643 
644644As described in [Structuring your prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#structuring-your-prompt), the cache follows the hierarchy: `tools` → `system` → `messages`. Changes at each level invalidate that level and all subsequent levels.
645645 
646The following table shows which parts of the cache are invalidated by different types of changes. ✘ indicates that the cache is invalidated, while ✓ indicates that the cache remains valid.
646The following table shows which parts of the cache are invalidated by different types of changes. ✘ indicates that the cache is invalidated, whereas ✓ indicates that the cache remains valid.
647647 
648648| What changes | Tools cache | System cache | Messages cache | Impact |
649649| ----------------------------------------------------- | -------------- | -------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
from line 651
651651| **Web search toggle** | ✓ | ✘ | ✘ | Enabling/disabling web search modifies the system prompt |
652652| **Citations toggle** | ✓ | ✘ | ✘ | Enabling/disabling citations modifies the system prompt |
653653| **Speed setting** | ✓ | ✘ | ✘ | Switching between [`speed: "fast"` and standard speed](https://platform.claude.com/docs/en/build-with-claude/fast-mode) invalidates system and message caches |
654| **Tool choice** | ✓ | ✓ | ✘ | Changes to `tool_choice` parameter only affect message blocks |
654| **Tool choice** | ✓ | ✓ | ✘ | Changes to the `tool_choice` parameter only affect message blocks |
655655| **Images** | ✓ | ✓ | ✘ | Adding/removing images anywhere in the prompt affects message blocks |
656656| **Thinking parameters** | Model-specific | Model-specific | ✘ | The thinking configuration (mode, and `budget_tokens` in extended mode) is rendered into the prompt, so changing it always invalidates message blocks; tool and system caches are also invalidated on models that render the configuration ahead of them. See [Thinking and prompt caching](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching). |
657657| **Effort setting** | Model-specific | Model-specific | ✘ | Changing the [`output_config.effort`](https://platform.claude.com/docs/en/build-with-claude/effort) value always invalidates message blocks, with the same model-specific effect on tool and system caches as thinking parameters. Setting effort explicitly to the model's default is equivalent to omitting it and does not invalidate. 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. |
658658| **Non-tool results passed to requests with thinking** | ✓ | ✓ | Model-specific | On Opus 4.5+, Sonnet 4.6+, and Haiku 5.5, thinking blocks are preserved by default, so the cache remains valid (✓). On earlier Opus/Sonnet models and Haiku models through Claude Haiku 4.5, all previously-cached thinking blocks are stripped from context, and any messages that follow those thinking blocks are removed from the cache (✘). For more details, see [Caching with thinking blocks](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#caching-with-thinking-blocks). |
659| **Dropped thinking blocks** | ✓ | ✓ | ✘ | When the API drops a Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, Claude Sonnet 5.5, or Claude Haiku 5.5 thinking block that isn't [preserved](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking) on that request (for example, one you replay to a model that can't read it), the cached prefix changes from that block's position onward on that request. Blocks the receiving model can read, passed back unchanged, keep the cache intact. |
659| **Dropped thinking blocks** | ✓ | ✓ | ✘ | When the API drops a Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, Claude Sonnet 5.5, or Claude Haiku 5.5 thinking block that isn't [preserved](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking) on that request, the cached prefix changes from that block's position onward on that request. Blocks the receiving model can read, passed back unchanged, keep the cache intact. |
660660 
661661On models that support [mid-conversation tool changes](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes), the `inline-tools-2026-09-15` beta header lets you add a tool, or change a tool's definition, partway through a conversation without editing `tools`. Send the definition in a `tool_addition` block in a mid-conversation system message and leave `tools` exactly as you first sent it. The cached prefix still matches, so only the appended message is processed as new input. The one exception is a `tools` array with no non-deferred tool, where the first tool defined this way costs one full cache miss on that request. See [Define tools in a message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#define-tools-in-a-message-beta).
662662 
from line 668
668668 
669669Monitor cache performance using these API response fields, within `usage` in the response (or `message_start` event if [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)):
670670 
671* `cache_creation_input_tokens`: Number of tokens written to the cache when creating a new entry.
672* `cache_read_input_tokens`: Number of tokens retrieved from the cache for this request.
673* `input_tokens`: Number of input tokens which were not read from or used to create a cache (that is, tokens after the last cache breakpoint).
671* `cache_creation_input_tokens`: Number of tokens written to the cache when creating a new entry
672* `cache_read_input_tokens`: Number of tokens retrieved from the cache for this request
673* `input_tokens`: Number of input tokens that were not read from or used to create a cache (that is, tokens after the last cache breakpoint)
674674 
675675<Note>
676676 **Understanding the token breakdown**
from line 703
703703 
704704When using [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) with prompt caching, thinking blocks have special behavior:
705705 
706**Automatic caching alongside other content:** While thinking blocks cannot be explicitly marked with `cache_control`, they get cached as part of the request content when you make subsequent API calls with tool results. This commonly happens during tool use when you pass thinking blocks back to continue the conversation.
706**Automatic caching alongside other content:** Although thinking blocks cannot be explicitly marked with `cache_control`, they get cached as part of the request content when you make subsequent API calls with tool results. This commonly occurs during tool use when you pass thinking blocks back to continue the conversation.
707707 
708708**Input token counting:** When thinking blocks are read from cache, they count as input tokens in your usage metrics. This is important for cost calculation and token budgeting.
709709 
710710**Cache invalidation patterns:**
711711 
712* Cache remains valid when only tool results are provided as user messages
713* On Opus 4.5+, Sonnet 4.6+, and Haiku 5.5, thinking blocks are preserved by default even when non-tool-result user content is added, so the cache remains valid
714* On earlier Opus/Sonnet models and Haiku models through Claude Haiku 4.5, cache gets invalidated when non-tool-result user content is added, causing all previous thinking blocks to be stripped from context
715* This caching behavior occurs even without explicit `cache_control` markers
712* Cache remains valid when only tool results are provided as user messages.
713* On Opus 4.5+, Sonnet 4.6+, and Haiku 5.5, thinking blocks are preserved by default even when non-tool-result user content is added, so the cache remains valid.
714* On earlier Opus/Sonnet models and Haiku models through Claude Haiku 4.5, cache gets invalidated when non-tool-result user content is added, causing all previous thinking blocks to be stripped from context.
715* This caching behavior occurs even without explicit `cache_control` markers.
716716 
717717For more details on cache invalidation, see [What invalidates the cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache).
718718 
from line 751
751751 
752752* **Organization and workspace isolation:** Caches are isolated between organizations. Different organizations never share caches, even if they use identical prompts. Caches are also isolated per workspace within an organization on the Claude API, Claude Platform on AWS, and Microsoft Foundry; Bedrock and Google Cloud use organization-level isolation only.
753753 
754* **Exact matching:** Cache hits require 100% identical prompt segments, including all text and images up to and including the block marked with cache control.
754* **Exact matching:** Cache hits require 100 percent identical prompt segments, including all text and images up to and including the block marked with cache control.
755755 
756756* **Output token generation:** Prompt caching has no effect on output token generation. The response you receive is identical to what you would get if prompt caching were not used.
757757 
from line 761
761761 
762762* Start with [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching) for multi-turn conversations. It handles breakpoint management automatically.
763763* Use [explicit block-level breakpoints](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints) when you need to cache different sections with different change frequencies.
764* Cache stable, reusable content like system instructions, background information, large contexts, or frequent tool definitions.
764* Cache stable, reusable content such as system instructions, background information, large contexts, or frequent tool definitions.
765765* Place cached content at the prompt's beginning for best performance.
766766* Use cache breakpoints strategically to separate different cacheable prefix sections.
767767* Place the breakpoint on the last block that stays identical across requests. For a prompt with a static prefix and a varying suffix (timestamps, per-request context, the incoming message), that is the end of the prefix, not the varying block.
from line 772
772772Tailor your prompt caching strategy to your scenario:
773773 
774774* Conversational agents: Reduce cost and latency for extended conversations, especially those with long instructions or uploaded documents.
775* Coding assistants: Improve autocomplete and code base Q\&A by keeping relevant sections or a summarized version of the code base in the prompt.
775* Coding assistants: Improve auto-complete and code base Q\&A by keeping relevant sections or a summarized version of the code base in the prompt.
776776* Large document processing: Incorporate complete long-form material including images in your prompt without increasing response latency.
777* Detailed instruction sets: Share extensive lists of instructions, procedures, and examples to fine-tune Claude's responses. Developers often include an example or two in the prompt, but with prompt caching you can get even better performance by including 20+ diverse examples of high quality answers.
777* Detailed instruction sets: Share extensive lists of instructions, procedures, and examples to fine-tune Claude's responses. Developers often include an example or two in the prompt, but with prompt caching you can get even better performance by including 20+ diverse examples of high-quality answers.
778778* Agentic tool use: Enhance performance for scenarios involving multiple tool calls and iterative code changes, where each step typically requires a new API call.
779* Talk to books, papers, documentation, podcast transcripts, and other longform content: Bring any knowledge base alive by embedding the entire document(s) into the prompt, and letting users ask it questions.
779* Books, papers, documentation, podcast transcripts, and other long-form content: Make any knowledge base interactive by embedding the entire document(s) into the prompt, and letting users ask it questions.
780780 
781781### Troubleshooting common issues
782782 
from line 786
786786 [Cache diagnostics](https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics) has the API compare consecutive requests and report where the prompt prefix diverged, which automatically handles many of the steps in this list.
787787</Tip>
788788 
789* Ensure cached sections are identical across calls. For explicit breakpoints, verify that `cache_control` markers are in the same locations
790* Check that calls are made within the cache lifetime (5 minutes by default)
791* Verify that `tool_choice`, image usage, the thinking configuration, and `output_config.effort` remain consistent between calls
792* Validate that you are caching at least the minimum number of tokens for your model and platform (see [Cache limitations](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-limitations))
793* Confirm your breakpoint is on a block that stays identical across requests. Cache writes happen only at the breakpoint, and if that block changes (timestamps, per-request context, the incoming message), the prefix hash never matches. The lookback does not find stable content behind the breakpoint; it only finds entries that earlier requests wrote at their own breakpoints
794* Verify that the keys in your `tool_use` content blocks have stable ordering as some languages (for example, Swift, Go) randomize key order during JSON conversion, breaking caches
795* Use [cache diagnostics](https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics) to have the API compare consecutive requests and report which part of the prompt diverged
789* Ensure cached sections are identical across calls. For explicit breakpoints, verify that `cache_control` markers are in the same locations.
790* Check that calls are made within the cache lifetime (5 minutes by default).
791* Verify that `tool_choice`, image usage, the thinking configuration, and `output_config.effort` remain consistent between calls.
792* Validate that you are caching at least the minimum number of tokens for your model and platform (see [Cache limitations](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-limitations)).
793* Confirm your breakpoint is on a block that stays identical across requests. Cache writes occur only at the breakpoint, and if that block changes (timestamps, per-request context, the incoming message), the prefix hash never matches. The lookback does not find stable content behind the breakpoint; it only finds entries that earlier requests wrote at their own breakpoints.
794* Verify that the keys in your `tool_use` content blocks have stable ordering as some languages (for example, Swift, Go) randomize key order during JSON conversion, breaking caches.
795* Use [cache diagnostics](https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics) to have the API compare consecutive requests and report which part of the prompt diverged.
796796 
797797<Note>
798 Changes to `tool_choice` or the presence/absence of images anywhere in the prompt will invalidate the cache, requiring a new cache entry to be created. For more details on cache invalidation, see [What invalidates the cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache).
798 Changes to `tool_choice` or the presence/absence of images anywhere in the prompt invalidate the cache, requiring a new cache entry to be created. For more details on cache invalidation, see [What invalidates the cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache).
799799</Note>
800800 
801801***
from line 837
837837 
838838Note that the current `cache_creation_input_tokens` field equals the sum of the values in the `cache_creation` object.
839839 
840If you see `ephemeral_5m_input_tokens` writes you didn't request while using server tools such as web search, see [Tool use with prompt caching](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching#server-tool-results-are-cached-automatically).
840If you see `ephemeral_5m_input_tokens` writes you didn't request while using server tools such as web search, see [Server tool results are cached automatically](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching#server-tool-results-are-cached-automatically).
841841 
842842### When to use the 1-hour cache
843843 
from line 845
845845 
846846The 1-hour cache is best used in the following scenarios:
847847 
848* When you have prompts that are likely used less frequently than 5 minutes, but more frequently than every hour. For example, when an agentic side-agent will take longer than 5 minutes, or when storing a long chat conversation with a user and you generally expect that user may not respond in the next 5 minutes.
849* When latency is important and your follow-up prompts may be sent beyond 5 minutes.
848* When you have prompts that are likely used less frequently than every 5 minutes, but more frequently than every hour. For example, when an agentic side-agent will take longer than 5 minutes, or when storing a long chat conversation with a user and you generally expect that user might not respond in the next 5 minutes.
849* When latency is important and your follow-up prompts might be sent beyond 5 minutes.
850850* When you want to improve your rate limit utilization, because cache hits are not deducted against your rate limit.
851851 
852852<Note>
853 The 5-minute and 1-hour cache behave the same with respect to latency. You will generally see improved time-to-first-token for long documents.
853 The 5-minute and 1-hour cache behave the same with respect to latency. You generally see improved time-to-first-token for long documents.
854854</Note>
855855 
856856### Mixing different TTLs
from line 867
867867 If `B` or `C` is larger than `A`, it is necessarily a cache miss, because `A` is the highest cache hit.
868868</Note>
869869 
870You'll be charged for:
870You are charged for:
871871 
8728721. Cache read tokens for `A`.
8738732. 1-hour cache write tokens for `(B - A)`.
from line 876
876876Here are three examples. This depicts the input tokens of 3 requests, each of which has different cache hits and cache misses. Each has a different calculated pricing, shown in the colored boxes, as a result.
877877 
878878<Frame>
879 ![Three requests with different cache hits and misses: A, B, and C mark where cache reads, 1-hour writes, and 5-minute writes end](https://platform.claude.com/docs/images/prompt-cache-mixed-ttl.svg)
879 ![Three requests with different cache hits and misses: A, B, and C mark where reads, 1-hour writes, and 5-minute writes end](https://platform.claude.com/docs/images/prompt-cache-mixed-ttl.svg)
880880</Frame>
881881 
882882***
from line 889
889889 
890890Set `max_tokens: 0` in your request. The API reads your prompt into the model and writes the cache at any `cache_control` breakpoint, then returns immediately without generating any output. The response has an empty `content` array, `stop_reason: "max_tokens"`, and a fully populated `usage` block.
891891 
892Place the `cache_control` breakpoint on the last block that is shared with the follow-up request (typically your system prompt or tool definitions), not on the placeholder user message. Otherwise the cache entry is keyed to the placeholder and the follow-up request won't hit it. Use the same thinking configuration and `output_config.effort` as your follow-up requests too: those values are rendered into the prompt (see [What invalidates the cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache)), so a pre-warm with a different configuration can write an entry your real traffic never hits. This means using an [explicit cache breakpoint](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints) rather than [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching), since automatic caching places the breakpoint on the last block, which here is the placeholder. The placeholder user message can be any string with non-whitespace content (the examples here use `"warmup"`); its content is read into the model but never answered.
892Place the `cache_control` breakpoint on the last block that is shared with the follow-up request (typically your system prompt or tool definitions), not on the placeholder user message. Otherwise the cache entry is keyed to the placeholder and the follow-up request won't hit it. Use the same thinking configuration and `output_config.effort` as your follow-up requests too: those values are rendered into the prompt (see [What invalidates the cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache)), so a pre-warm with a different configuration can write an entry your real traffic never hits. This means using an [explicit cache breakpoint](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints) rather than [automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching), because automatic caching places the breakpoint on the last block, which here is the placeholder. The placeholder user message can be any string with non-whitespace content (the examples here use `"warmup"`); its content is read into the model but never answered.
893893 
894894<Note>
895895 A pre-warm request incurs a **cache write** charge if the prefix is not already cached, the same as any other request. Check `usage.cache_creation_input_tokens` in the response to confirm a write occurred. Zero output tokens are billed.
from line 1127
11271127 
11281128### Typical usage pattern
11291129 
1130Fire a pre-warm request when your application starts (or on a scheduled interval), then send real user requests after the pre-warm completes:
1130Make a pre-warm request when your application starts (or on a scheduled interval), then send real user requests after the pre-warm completes:
11311131 
11321132<CodeGroup>
11331133 ```bash cURL
from line 1513
15131513 
15141514### Limitations
15151515 
1516A `max_tokens: 0` request is rejected with an `invalid_request_error` if any of the following are set, since each implies output that a zero-token budget cannot produce:
1516A `max_tokens: 0` request is rejected with an `invalid_request_error` if any of the following are set, because each implies output that a zero-token budget cannot produce:
15171517 
15181518* `stream: true`
15191519* [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) (`thinking.type: "enabled"`)
from line 1530
15301530 
15311531## Prompt caching examples
15321532 
1533To help you get started with prompt caching, the [prompt caching cookbook](https://platform.claude.com/cookbook/misc-prompt-caching) provides detailed examples and best practices.
1533To help you get started with prompt caching, the [prompt caching recipe](https://platform.claude.com/cookbook/misc-prompt-caching) in the Claude Cookbook provides detailed examples and best practices.
15341534 
15351535The following code snippets showcase various prompt caching patterns. These examples demonstrate how to implement caching in different scenarios, helping you understand the practical applications of this feature:
15361536 
from line 2237
22372237 
22382238 When this is set up properly, you should see the following in the usage response of each request:
22392239 
2240 * `input_tokens`: Number of tokens in the new user message (will be minimal)
2240 * `input_tokens`: Number of tokens in the new user message (minimal)
22412241 * `cache_creation_input_tokens`: Number of tokens in the new assistant and user turns
22422242 * `cache_read_input_tokens`: Number of tokens in the conversation up to the previous turn
22432243 </Accordion>
from line 3134
31343134 
31353135 This approach provides maximum flexibility:
31363136 
3137 * If you append a new turn to the conversation without changing earlier content, all four cache segments are reused
3138 * If you update the RAG documents but keep the same tools and instructions, the first two cache segments are reused
3139 * If you change the conversation but keep the same tools, instructions, and documents, the first three segments are reused
3140 * Changes at any breakpoint invalidate that segment and everything after it, while earlier cached segments remain valid
3137 * If you append a new turn to the conversation without changing earlier content, all four cache segments are reused.
3138 * If you update the RAG documents but keep the same tools and instructions, the first two cache segments are reused.
3139 * If you change the conversation but keep the same tools, instructions, and documents, the first three segments are reused.
3140 * Changes at any breakpoint invalidate that segment and everything after it, whereas earlier cached segments remain valid.
31413141 
31423142 For the first request:
31433143 
from line 3174
31743174 
31753175<AccordionGroup>
31763176 <Accordion title="Do I need multiple cache breakpoints or is one at the end sufficient?">
3177 **In most cases, a single cache breakpoint at the end of your static content is sufficient.** Cache writes happen only at the block you mark. Place it on the last block that stays identical across requests, and every subsequent request reads that same entry. If a later block varies per request (a timestamp, the incoming message), keep the breakpoint before it, on the last stable block.
3177 **In most cases, a single cache breakpoint at the end of your static content is sufficient.** Cache writes occur only at the block you mark. Place it on the last block that stays identical across requests, and every subsequent request reads that same entry. If a later block varies with each request (a timestamp, the incoming message), keep the breakpoint before it, on the last stable block.
31783178 
31793179 You only need multiple breakpoints if:
31803180 
from line 3188
31883188 <Accordion title="Do cache breakpoints add extra cost?">
31893189 No, cache breakpoints themselves are free. You only pay for:
31903190 
3191 * Writing content to cache (25% more than base input tokens for 5-minute TTL)
3191 * Writing content to cache (25 percent more than base input tokens for 5-minute TTL)
31923192 * Reading from cache (a fraction of the base input token price, see [Pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing))
31933193 * Regular input tokens for uncached content
31943194 
from line 3251
32513251 </Accordion>
32523252 
32533253 <Accordion title="Can I use prompt caching with other API features?">
3254 Yes, prompt caching can be used alongside other API features like tool use and vision capabilities. However, changing whether there are images in a prompt or modifying tool use settings will break the cache.
3254 Yes, prompt caching can be used alongside other API features such as tool use and vision capabilities. However, changing whether there are images in a prompt or modifying tool use settings breaks the cache.
32553255 
32563256 For more details on cache invalidation, see [What invalidates the cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache).
32573257 </Accordion>
32583258 
32593259 <Accordion title="How does prompt caching affect pricing?">
3260 Prompt caching introduces a new pricing structure where 5-minute cache writes cost 25% more than base input tokens, 1-hour cache writes cost 2x base input tokens, and cache hits cost a fraction of the base input token price (see [Pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing) for the per-model multiplier).
3260 Prompt caching introduces a new pricing structure where 5-minute cache writes cost 25 percent more than base input tokens, 1-hour cache writes cost 2x base input tokens, and cache hits cost a fraction of the base input token price (see [Pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing) for the per-model multiplier).
32613261 </Accordion>
32623262 
32633263 <Accordion title="Can I manually clear the cache?">
from line 3289
32893289 <Accordion title="Can I use prompt caching with the Batches API?">
32903290 Yes, it is possible to use prompt caching with your [Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing) requests. However, because asynchronous batch requests can be processed concurrently and in any order, cache hits are provided on a best-effort basis.
32913291 
3292 The [1-hour cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) can help improve your cache hits. The most cost effective way of using it is the following:
3292 The [1-hour cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) can help improve your cache hits. The most cost-effective way of using it is the following:
32933293 
32943294 * Gather a set of message requests that have a shared prefix.
32953295 * Send a batch request with a single request that has this shared prefix and a 1-hour cache block. This writes the prefix to the 1-hour cache.
3296 * As soon as this is complete, submit the rest of the requests. You will have to monitor the job to know when it completes.
3296 * As soon as this is complete, submit the rest of the requests. You have to monitor the job to know when it completes.
32973297 
32983298 This is typically better than using the 5-minute cache because it's common for batch requests to take between 5 minutes and 1 hour to complete.
32993299 </Accordion>

build-with-claude/prompt-engineering/claude-prompting-best-practices Changed · +51 / -51 lines

### Leverage thinking and interleaved thinking capabilities ### Leverage thinking & interleaved thinking capabilities

from line 35
3535 
3636### Be clear and direct
3737 
38Claude responds well to clear, explicit instructions. Being specific about your desired output can help enhance results. If you want "above and beyond" behavior, explicitly request it rather than relying on the model to infer this from vague prompts.
38Claude responds well to clear, explicit instructions. Being specific about the output you want can help enhance results. If you want Claude to do more than the task strictly requires, explicitly request it rather than relying on the model to infer this from vague prompts.
3939 
4040Think of Claude as a brilliant but new employee who lacks context on your norms and workflows. The more precisely you explain what you want, the better the result.
4141 
42**Golden rule:** Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too.
42**Key test:** Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too.
4343 
44* Be specific about the desired output format and constraints.
44* Be specific about the output format and constraints you want.
4545* Provide instructions as sequential steps using numbered lists or bullet points when the order or completeness of steps matters.
4646 
4747<Accordion title="Example: Creating an analytics dashboard" defaultOpen>
from line 60
6060 
6161### Add context to improve performance
6262 
63Providing context or motivation behind your instructions, such as explaining to Claude why such behavior is important, can help Claude better understand your goals and deliver more targeted responses.
63Providing context or motivation behind your instructions, such as explaining to Claude why such behavior is important, can give Claude more information about your goals and help it deliver more targeted responses.
6464 
6565<Accordion title="Example: Formatting preferences" defaultOpen>
6666 **Less effective:**
from line 76
7676 ```
7777</Accordion>
7878 
79Claude is smart enough to generalize from the explanation.
79Claude can generalize from the explanation.
8080 
8181### Use examples effectively
8282 
from line 240
240240 
241241When working with large documents or data-rich inputs (20k+ tokens), structure your prompt carefully to get the best results:
242242 
243* **Put longform data at the top:** Place your long documents and inputs near the top of your prompt, above your query, instructions, and examples. This improves performance across all models.
243* **Put long-form data at the top:** Place your long documents and inputs near the top of your prompt, above your query, instructions, and examples. This improves performance across all models.
244244 
245245 <Note>
246246 Queries at the end can improve response quality by up to 30 percent in tests, especially with complex, multidocument inputs.
from line 323
323323 
324324* **More direct and grounded:** Provides fact-based progress reports rather than self-celebratory updates
325325* **More conversational:** Slightly more fluent and colloquial, less machine-like
326* **Less verbose:** May skip detailed summaries for efficiency unless prompted otherwise
326* **Less verbose:** Might skip detailed summaries for efficiency unless prompted otherwise
327327 
328This means Claude may skip verbal summaries after tool calls, jumping directly to the next action. If you prefer more visibility into its work:
328This means Claude might skip verbal summaries after tool calls, jumping directly to the next action. If you prefer more visibility into its work:
329329 
330330```text Sample prompt wrap
331331After completing a task that involves tool use, provide a quick summary of the work you've done.
from line 346
346346 
347347 * Try: "Write the prose sections of your response in \<smoothly\_flowing\_prose\_paragraphs> tags."
348348 
3493. **Match your prompt style to the desired output**
3493. **Match your prompt style to the output you want**
350350 
351 The formatting style used in your prompt may influence Claude's response style. If you are still experiencing steerability issues with output formatting, try matching your prompt style to your desired output style as closely as possible. For example, removing markdown from your prompt can reduce the volume of markdown in the output.
351 The formatting style used in your prompt might influence Claude's response style. If you are still experiencing steerability issues with output formatting, try matching your prompt style to the output style you want as closely as possible. For example, removing markdown from your prompt can reduce the volume of markdown in the output.
352352 
3533534. **Use detailed prompts for specific formatting preferences**
354354 
from line 406
406406Here are common prefill scenarios and how to migrate away from them:
407407 
408408<Accordion title="Controlling output formatting">
409 Prefills have been used to force specific output formats like JSON/YAML, classification, and similar patterns where the prefill constrains Claude to a particular structure.
409 Prefills have been used to force specific output formats such as JSON/YAML, classification, and similar patterns where the prefill constrains Claude to a particular structure.
410410 
411 **Migration:** The [Structured Outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) feature is designed specifically to constrain Claude's responses to follow a given schema. Try asking the model to conform to your output structure first, as newer models can reliably match complex schemas when told to, especially if implemented with retries. For classification tasks, use either tools with an enum field containing your valid labels or structured outputs.
411 **Migration:** The [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) feature is designed specifically to constrain Claude's responses to follow a given schema. Try asking the model to conform to your output structure first, as newer models can reliably match complex schemas when told to, especially if implemented with retries. For classification tasks, use either tools with an enum field containing your valid labels or structured outputs.
412412</Accordion>
413413 
414414<Accordion title="Eliminating preambles">
415 Prefills like `Here is the requested summary:\n` were used to skip introductory text.
415 Prefills such as `Here is the requested summary:\n` were used to skip introductory text.
416416 
417417 **Migration:** Use direct instructions in the system prompt: "Respond directly without preamble. Do not start with phrases like 'Here is...', 'Based on...', etc." Alternatively, direct the model to output within XML tags, use structured outputs, or use tool calling. If the occasional preamble slips through, strip it in post-processing.
418418</Accordion>
from line 424
424424</Accordion>
425425 
426426<Accordion title="Continuations">
427 Prefills were used to continue partial completions, resume interrupted responses, or pick up where a previous generation left off.
427 Prefills were used to continue partial completions, resume interrupted responses, or extend a previous generation from where it ended.
428428 
429429 **Migration:** Move the continuation to the user message, and include the final text from the interrupted response: "Your previous response was interrupted and ended with \`\[previous\_response]\`. Continue from where you left off." If this is part of error-handling or incomplete-response-handling and there is no UX penalty, retry the request.
430430</Accordion>
from line 474
474474</default_to_action>
475475```
476476 
477On the other hand, if you want the model to be more hesitant by default, less prone to jumping straight into implementations, and only take action if requested, you can steer this behavior with a prompt like the following:
477On the other hand, if you want the model to be more hesitant by default, less prone to starting implementations immediately, and only take action if requested, you can steer this behavior with a prompt such as the following:
478478 
479479```text Sample prompt for conservative action wrap
480480<do_not_act_before_instructions>
from line 485
485485</do_not_act_before_instructions>
486486```
487487 
488Claude Opus 4.5 and Claude Opus 4.6 are also more responsive to the system prompt than previous models. If your prompts were designed to reduce undertriggering on tools or skills, these models may now overtrigger. The fix is to dial back any aggressive language. Where you might have said "CRITICAL: You MUST use this tool when...", you can use more normal prompting like "Use this tool when...".
488Claude Opus 4.5 and Claude Opus 4.6 are also more responsive to the system prompt than previous models. If your prompts were designed to reduce undertriggering on tools or skills, these models might now overtrigger. The fix is to soften any aggressive language. Where you might have said "CRITICAL: You MUST use this tool when...", you can use more normal prompting such as "Use this tool when...".
489489 
490490### Optimize parallel tool calling
491491 
492Claude's latest models run independent tool calls in parallel. These models will:
492Claude's latest models run independent tool calls in parallel. These models:
493493 
494494* Run multiple speculative searches during research
495495* Read several files at once to build context faster
496496* Run bash commands in parallel (which can even bottleneck system performance)
497497 
498This behavior is steerable. While the model has a high success rate in parallel tool calling without prompting, you can boost this to \~100% or adjust the aggression level:
498This behavior is steerable. Although the model has a high success rate in parallel tool calling without prompting, you can boost this to about 100 percent or adjust the aggression level:
499499 
500500```text Sample prompt for maximum parallel efficiency wrap
501501<use_parallel_tool_calls>
from line 521
521521 
522522### Overthinking and excessive thoroughness
523523 
524Claude Opus 4.6 does more upfront exploration than previous models, especially at higher [`effort`](https://platform.claude.com/docs/en/build-with-claude/effort) settings. This initial work often helps to optimize the final results, but the model may gather extensive context or pursue multiple threads of research without being prompted. If your prompts previously encouraged the model to be more thorough, you should tune that guidance for Claude Opus 4.6:
524Claude Opus 4.6 does more upfront exploration than previous models, especially at higher [`effort`](https://platform.claude.com/docs/en/build-with-claude/effort) settings. This initial work often helps to optimize the final results, but the model might gather extensive context or pursue multiple threads of research without being prompted. If your prompts previously encouraged the model to be more thorough, you should tune that guidance for Claude Opus 4.6:
525525 
526* **Replace blanket defaults with more targeted instructions.** Instead of "Default to using \[tool]," add guidance like "Use \[tool] when it would enhance your understanding of the problem."
527* **Remove over-prompting.** Tools that undertriggered in previous models are likely to trigger appropriately now. Instructions like "If in doubt, use \[tool]" will cause overtriggering.
526* **Replace blanket defaults with more targeted instructions.** Instead of "Default to using \[tool]," add guidance such as "Use \[tool] when it would enhance your understanding of the problem."
527* **Remove over-prompting.** Tools that undertriggered in previous models are likely to trigger appropriately now. Instructions such as "If in doubt, use \[tool]" cause overtriggering.
528528* **Use effort as a fallback.** If Claude continues to be overly aggressive, use a lower setting for `effort`.
529529 
530In some cases, Claude Opus 4.6 may think extensively, which can inflate thinking tokens and slow down responses. If this behavior is undesirable, you can add explicit instructions to constrain its reasoning, or you can lower the `effort` setting to reduce overall thinking and token usage.
530In some cases, Claude Opus 4.6 might think extensively, which can inflate thinking tokens and slow down responses. If this behavior is undesirable, you can add explicit instructions to constrain its reasoning, or you can lower the `effort` setting to reduce overall thinking and token usage.
531531 
532532```text Sample prompt wrap
533533When you're deciding how to approach a problem, choose an approach and commit to it.
from line 538
538538 
539539If you need a hard ceiling on thinking costs, extended thinking with a `budget_tokens` cap is still functional on Opus 4.6 and Sonnet 4.6 but is deprecated. On Claude 4.7 and later models, setting `budget_tokens` returns a 400 error. Prefer lowering the [effort](https://platform.claude.com/docs/en/build-with-claude/effort) setting or using `max_tokens` as a hard limit with [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking).
540540 
541### Leverage thinking & interleaved thinking capabilities
541### Leverage thinking and interleaved thinking capabilities
542542 
543543Claude's latest models offer thinking capabilities that can be especially helpful for tasks involving reflection after tool use or complex multistep reasoning. You can guide its initial or interleaved thinking for better results.
544544 
from line 554
554554information, and then take the best next action.
555555```
556556 
557The triggering behavior for adaptive thinking is promptable. If you find the model thinking more often than you'd like, which can happen with large or complex system prompts, add guidance to steer it:
557The triggering behavior for adaptive thinking is promptable. If you find the model thinking more often than you'd like, which can occur with large or complex system prompts, add guidance to steer it:
558558 
559559```text Sample prompt wrap
560560Thinking adds latency and should only be used when it will meaningfully improve
from line 773
773773 
774774If you are not using extended thinking, you don't need to add a `thinking` parameter. On Claude Opus 4.6 through Claude Opus 4.8 and Claude Sonnet 4.6, thinking is off when you omit the `thinking` parameter. On Claude Opus 5, Claude Sonnet 5.5, Claude Sonnet 5, and Claude Haiku 5.5, thinking is on by default when you omit the `thinking` parameter, so a response can begin with `thinking` blocks. Select content blocks by `type` rather than by position, and leave room in `max_tokens` for thinking. On Claude Opus 5 and Claude Haiku 5.5, you can disable it only at effort `high` or lower. On Claude Sonnet 5.5, the lowest thinking setting is `between_tools`, accepted at effort `high` or lower. On Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, and Claude Opus 5.5, thinking is always on, regardless of whether you set the `thinking` parameter.
775775 
776* **Prefer general instructions over prescriptive steps.** A prompt like "think thoroughly" often produces better reasoning than a hand-written step-by-step plan. Claude's reasoning frequently exceeds what a human would prescribe.
776* **Prefer general instructions over prescriptive steps.** A prompt such as "think thoroughly" often produces better reasoning than a hand-written step-by-step plan. Claude's reasoning frequently exceeds what a human would prescribe.
777777* **Multishot examples work with thinking.** Worked examples in your prompt shape how Claude approaches similar problems in its own thinking blocks. Present each example as a problem, the method to apply, and the expected answer.
778778* **Manual chain-of-thought (CoT) prompting as a fallback.** When thinking is off, you can still encourage step-by-step reasoning by asking Claude to think through the problem before it answers, and to put the final answer in `<answer>` tags so you can extract it. On Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5, and Claude Sonnet 5.5, rely on thinking instead, at a lower [effort](https://platform.claude.com/docs/en/build-with-claude/effort) level if cost or latency matters: a prompt that asks the model to write out its reasoning, for example in `<thinking>` tags, may be declined. See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
779779* **Ask Claude to self-check.** Append something like "Before you finish, verify your answer against \[test criteria]." This catches errors reliably, especially for coding and math. Claude Opus 5 is the exception: it verifies its own work well without explicit instruction, and verification instructions carried over from prompts tuned for earlier models can cause over-verification, adding tokens and latency. On Claude Opus 5, remove these instructions rather than rewriting them. See [Task scope and over-verification](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#task-scope-and-over-verification).
780780 
781781<Note>
782 When extended thinking is disabled, Claude Opus 4.5 is particularly sensitive to the word "think" and its variants. Consider using alternatives like "consider," "evaluate," or "reason through" in those cases.
782 When extended thinking is disabled, Claude Opus 4.5 is particularly sensitive to the word "think" and its variants. Consider using alternatives such as "consider," "evaluate," or "reason through" in those cases.
783783</Note>
784784 
785785<Info>
from line 794
794794 
795795#### Context awareness and multiwindow workflows
796796 
797Claude Sonnet 5, Claude Sonnet 4.6, Claude Sonnet 4.5 (deprecated), and Claude Haiku 4.5 feature [context awareness](https://platform.claude.com/docs/en/build-with-claude/context-windows#context-awareness), enabling the model to track its remaining context window (that is, its "token budget") throughout a conversation. This enables Claude to execute tasks and manage context more effectively by understanding how much space it has to work.
797Claude Sonnet 5, Claude Sonnet 4.6, Claude Sonnet 4.5 (deprecated), and Claude Haiku 4.5 feature [context awareness](https://platform.claude.com/docs/en/build-with-claude/context-windows#context-awareness), which lets the model track its remaining context window (that is, its "token budget") throughout a conversation. This allows Claude to run tasks and manage context more effectively based on how much space it has to work.
798798 
799799**Managing context limits:**
800800 
801If you are using Claude in an agent harness that compacts context or allows saving context to external files (like in Claude Code), consider adding this information to your prompt so Claude can behave accordingly. Otherwise, Claude may sometimes naturally try to wrap up work as it approaches the context limit. The following is an example prompt:
801If you are using Claude in an agent harness that compacts context or allows saving context to external files (as in Claude Code), consider adding this information to your prompt so Claude can behave accordingly. Otherwise, Claude might sometimes naturally attempt to bring its work to a close as it approaches the context limit. The following is an example prompt:
802802 
803803```text Sample prompt wrap
804804Your context window will be automatically compacted as it approaches its limit, allowing
from line 820
820820 
8218212. **Have the model write tests in a structured format:** Ask Claude to create tests before starting work and keep track of them in a structured format (for example, `tests.json`). This leads to better long-term ability to iterate. Remind Claude of the importance of tests: "It is unacceptable to remove or edit tests because this could lead to missing or buggy functionality."
822822 
8233. **Set up quality of life tools:** Encourage Claude to create setup scripts (for example, `init.sh`) to gracefully start servers, run test suites, and linters. This prevents repeated work when continuing from a fresh context window.
8233. **Set up convenience tools:** Encourage Claude to create setup scripts (for example, `init.sh`) to gracefully start servers and run test suites and linters. This prevents repeated work when continuing from a fresh context window.
824824 
8254. **Starting fresh versus compacting:** When a context window is cleared, consider starting with a brand new context window rather than using compaction. Claude's latest models are extremely effective at discovering state from the local filesystem. In some cases, you may want to take advantage of this over compaction. Be prescriptive about how it should start:
8254. **Starting fresh versus compacting:** When a context window is cleared, consider starting with a brand new context window rather than using compaction. Claude's latest models are extremely effective at discovering state from the local filesystem. In some cases, you might want to take advantage of this over compaction. Be prescriptive about how it should start:
826826 
827827 * "Call pwd; you can only read and write files in this directory."
828828 * "Review progress.txt, tests.json, and the git logs."
from line 841
841841 
842842#### State management best practices
843843 
844* **Use structured formats for state data:** When tracking structured information (like test results or task status), use JSON or other structured formats to help Claude understand schema requirements.
844* **Use structured formats for state data:** When tracking structured information (such as test results or task status), use JSON or other structured formats to make schema requirements explicit to Claude.
845845* **Use unstructured text for progress notes:** Freeform progress notes work well for tracking general progress and context.
846846* **Use git for state tracking:** Git provides a log of what's been done and checkpoints that can be restored. Claude's latest models perform especially well in using git to track state across multiple sessions.
847847* **Emphasize incremental progress:** Explicitly ask Claude to keep track of its progress and focus on incremental work.
from line 873
873873 
874874### Balancing autonomy and safety
875875 
876Without guidance, Claude Opus 4.6 may take actions that are difficult to reverse or affect shared systems, such as deleting files, force-pushing, or posting to external services. If you want Claude Opus 4.6 to confirm before taking potentially risky actions, add guidance to your prompt:
876Without guidance, Claude Opus 4.6 might take actions that are difficult to reverse or affect shared systems, such as deleting files, force-pushing, or posting to external services. If you want Claude Opus 4.6 to confirm before taking potentially risky actions, add guidance to your prompt:
877877 
878878```text Sample prompt wrap
879879Consider the reversibility and potential impact of your actions. You are encouraged to
from line 919
919919To take advantage of this behavior:
920920 
9219211. **Ensure well-defined subagent tools:** Have subagent tools available and described in tool definitions.
9222. **Let Claude orchestrate naturally:** Claude will delegate appropriately without explicit instruction.
9233. **Watch for overuse:** Claude Opus 4.6 has a strong predilection for subagents and may spawn them in situations where a simpler, direct approach would suffice. For example, the model may spawn subagents for code exploration when a direct grep call is faster and sufficient. Claude Opus 5 also delegates to subagents more readily than prior models; see [Controlling subagent spawning](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#controlling-subagent-spawning) for guidance and a sample damping prompt.
9222. **Let Claude orchestrate naturally:** Claude delegates appropriately without explicit instruction.
9233. **Watch for overuse:** Claude Opus 4.6 has a strong tendency to use subagents and might spawn them in situations where a simpler, direct approach would suffice. For example, the model might spawn subagents for code exploration when a direct grep call is faster and sufficient. Claude Opus 5 also delegates to subagents more readily than prior models; see [Controlling subagent spawning](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#controlling-subagent-spawning) for guidance and a sample damping prompt.
924924 
925925If you're seeing excessive subagent use, add explicit guidance about when subagents are and aren't warranted:
926926 
from line 939
939939 
940940### Reduce file creation in agentic coding
941941 
942Claude's latest models may sometimes create new files for testing and iteration purposes, particularly when working with code. This approach allows Claude to use files, especially Python scripts, as a 'temporary scratchpad' before saving its final output. Using temporary files can improve outcomes particularly for agentic coding use cases.
942Claude's latest models might sometimes create new files for testing and iteration purposes, particularly when working with code. This approach allows Claude to use files, especially Python scripts, as a 'temporary scratchpad' before saving its final output. Using temporary files can improve outcomes particularly for agentic coding use cases.
943943 
944If you'd prefer to minimize net new file creation, you can instruct Claude to clean up after itself:
944If you'd prefer to minimize the number of new files left behind, you can instruct Claude to clean up after itself:
945945 
946946```text Sample prompt wrap
947947If you create any temporary new files, scripts, or helper files for iteration, clean up
from line 976
976976 
977977### Avoid focusing on passing tests and hardcoding
978978 
979Claude can sometimes focus too heavily on making tests pass at the expense of more general solutions, or may use workarounds like helper scripts for complex refactoring instead of using standard tools directly. To prevent this behavior and get solutions that generalize:
979Claude can sometimes focus too heavily on making tests pass at the expense of more general solutions, or might use workarounds such as helper scripts for complex refactoring instead of using standard tools directly. To prevent this behavior and get solutions that generalize:
980980 
981981```text Sample prompt wrap
982982Please write a high-quality, general-purpose solution using the standard tools
from line 1018
10181018 
10191019### Frontend design
10201020 
1021Claude Opus 4.5 and Claude Opus 4.6 build complex, real-world web applications with strong frontend design. However, without guidance, models can default to generic patterns that create what users call the "AI slop" aesthetic. To create distinctive, creative frontends that surprise and delight:
1021Claude Opus 4.5 and Claude Opus 4.6 build complex, real-world web applications with strong frontend design. However, without guidance, models can default to generic patterns that create what users call the "AI slop" aesthetic. To create distinctive, creative front ends that surprise and delight:
10221022 
10231023<Tip>
10241024 For a detailed guide on improving frontend design, see the blog post on [improving frontend design through skills](https://www.claude.com/blog/improving-frontend-design-through-skills).
from line 1113
11131113 
11141114When migrating to current Claude models from earlier generations:
11151115 
11161. **Be specific about desired behavior:** Consider describing exactly what you'd like to see in the output.
11161. **Be specific about the behavior you want:** Consider describing exactly what you'd like to see in the output.
11171117 
11182. **Frame your instructions with modifiers:** Adding modifiers that encourage Claude to increase the quality and detail of its output can help better shape Claude's performance. For example, instead of "Create an analytics dashboard", use "Create an analytics dashboard. Include as many relevant features and interactions as possible. Go beyond the basics to create a fully-featured implementation."
11182. **Frame your instructions with modifiers:** Adding modifiers that encourage Claude to increase the quality and detail of its output can help better shape Claude's performance. For example, instead of "Create an analytics dashboard," use "Create an analytics dashboard. Include as many relevant features and interactions as possible. Go beyond the basics to create a fully-featured implementation."
11191119 
11203. **Request specific features explicitly:** Animations and interactive elements should be requested explicitly when desired.
11203. **Request specific features explicitly:** Ask explicitly for animations and interactive elements when you want them.
11211121 
112211224. **Update thinking configuration:** Claude 4.6 and later models use [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {type: "adaptive"}`) instead of manual thinking with `budget_tokens`. On Claude 4.7 and later models, setting `budget_tokens` returns a 400 error. Use the [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort) to control thinking depth.
11231123 
112411245. **Migrate away from prefilled responses:** Prefilled responses on the last assistant turn are no longer supported starting with Claude 4.6 models and Claude Mythos Preview. See [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) for detailed guidance on alternatives.
11251125 
11266. **Tune anti-laziness prompting:** If your prompts previously encouraged the model to be more thorough or use tools more aggressively, dial back that guidance. Claude 4.6 models are more proactive and may overtrigger on instructions that were needed for previous models.
11266. **Tune anti-laziness prompting:** If your prompts previously encouraged the model to be more thorough or use tools more aggressively, reduce that guidance. Claude 4.6 models are more proactive and might overtrigger on instructions that were needed for previous models.
11271127 
112811287. **Pass thinking blocks back unchanged and keep history append-only:** Append each assistant turn exactly as the API returned it, thinking blocks included. On Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5, [modifying the conversation before a thinking block](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation) results in an error, or in the block being dropped if you opt into that: editing earlier messages, rebuilding `system` or `tools`, or summarizing older turns in place between requests invalidates every later thinking block, so move those changes to mid-conversation system messages and server-side context management. See [Keep the conversation history append-only](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#keep-the-conversation-history-append-only).
11291129 

build-with-claude/prompt-engineering/prompting-claude-fable-5 Changed · +7 / -7 lines

from line 8
88 
99Claude Fable 5 takes on problems that were previously too complex, long-running, or ambiguous for prior models, and is particularly effective at end-to-end work that takes a person hours, days, or weeks to complete. The teams seeing the best outcomes apply Claude Fable 5 to their hardest unsolved problems; testing it only on simpler workloads tends to undersell its capability range. It also performs reliably on more straightforward tasks.
1010 
11Claude Fable 5 has several behavioral differences from Claude Opus 4.8 that may require prompt or scaffolding updates. Capability improvements at this level are also a good prompt to re-evaluate which instructions, tools, and guardrails are still needed. The patterns below cover the behaviors that most often require tuning.
11Claude Fable 5 has several behavioral differences from Claude Opus 4.8 that might require prompt or scaffolding updates. Capability improvements at this level are also a good prompt to re-evaluate which instructions, tools, and guardrails are still needed. The following patterns cover the behaviors that most often require tuning.
1212 
1313<Note>
1414 For how thinking works on Claude Fable 5 and Claude Mythos 5 (adaptive thinking only, summarized-only thinking output, no extended thinking budgets), see [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking). For the `refusal` stop reason and fallback handling, see [Refusals and fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback).
1515 
16 Claude Fable 5 runs safety classifiers that target offensive cybersecurity techniques (such as building exploits, malware, or attack tooling), biology and life sciences content (such as lab methods or molecular mechanisms), and extraction of the model's summarized thinking. Benign cybersecurity work and beneficial life sciences tasks may also trigger these safeguards. To re-route declined requests automatically, configure [server-side or client-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback) to Claude Opus 4.8.
16 Claude Fable 5 runs safety classifiers that target offensive cybersecurity techniques (such as building exploits, malware, or attack tooling), biology and life sciences content (such as lab methods or molecular mechanisms), and extraction of the model's summarized thinking. Benign cybersecurity work and beneficial life sciences tasks might also trigger these safeguards. To re-route declined requests automatically, configure [server-side or client-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback) to Claude Opus 4.8.
1717</Note>
1818 
1919## Capability improvements
from line 24
2424* **First-shot correctness on complex, well-specified problems.** Early testers reported single-pass implementations of systems that previously took days of iteration.
2525* **Vision.** Claude Fable 5 interprets dense technical images, web applications, and detailed screenshots with substantially higher accuracy, often while using fewer output tokens, and is trained to use bash and crop tools to handle flipped, blurry, or noisy images.
2626* **Enterprise workflows.** Claude Fable 5 follows instructions, stays in scope, and produces professional-grade output on financial analysis, spreadsheets, slides, and documents.
27* **Code review and debugging.** Bug-finding recall (outside the cybersecurity domains the safety classifiers cover) is noticeably higher than Claude Opus 4.8, including search across codebases and repository history.
27* **Code review and debugging.** Bug-finding recall (outside the cybersecurity domains the safety classifiers cover) is noticeably higher than Claude Opus 4.8, including search across code bases and repository history.
2828* **Navigating ambiguity.** Claude Fable 5 performs well when given complex, multithreaded requests and asked to determine next steps.
2929* **Delegation and collaboration.** Claude Fable 5 is significantly more dependable at dispatching and sustaining parallel subagents, and reliably manages ongoing communication with long-running subagents and peer agents.
3030 
from line 50
5050 
5151## Strong instruction following
5252 
53Instruction-following is improved enough that you can steer most behaviors with a brief instruction rather than enumerating each behavior by name. For example, when un-steered, Claude Fable 5 can elaborate beyond what the task needs, especially at higher effort settings: surveying options it won't pursue, explaining root causes at length, producing heavily-structured PR descriptions, or writing comments that narrate what the next line does. A short brevity instruction is as effective as listing each pattern:
53Instruction-following is improved enough that you can steer most behaviors with a brief instruction rather than enumerating each behavior by name. For example, when un-steered, Claude Fable 5 can elaborate beyond what the task needs, especially at higher effort settings: surveying options it won't pursue, explaining root causes at length, producing heavily structured PR descriptions, or writing comments that narrate what the next line does. A short brevity instruction is as effective as listing each pattern:
5454 
5555```text wrap
5656Lead with the outcome. Your first sentence after finishing should answer "what happened" or "what did you find": the thing the user would ask for if they said "just give me the TLDR." Supporting detail and reasoning come after. Being readable and being concise are different things, and readability matters more.
from line 120
120120 
121121## Give the reason, not only the request
122122 
123Claude Fable 5 tends to perform better when it understands the intent behind a request: context lets it connect the task to relevant information rather than inferring intent on its own. Provide context about why you're asking, especially for long-running agents drawing on multiple workstreams:
123Claude Fable 5 tends to perform better when the prompt states the intent behind a request: context lets it connect the task to relevant information rather than inferring intent on its own. Provide context about why you're asking, especially for long-running agents drawing on multiple workstreams:
124124 
125125```text wrap
126126I'm working on [the larger task] for [who it's for]. They need [what the output enables]. With that in mind: [request].
from line 169
169169 
170170## Recommended scaffolding changes
171171 
172* **Start at the top of your difficulty range.** Pick a task harder than what you'd assign to prior models, and have Claude Fable 5 scope it, ask clarifying questions, and execute.
172* **Start at the top of your difficulty range.** Pick a task harder than what you'd assign to prior models, and have Claude Fable 5 scope it, ask clarifying questions, and carry it out.
173173* **Make self-verification explicit in long-run prompts.** Separate, fresh-context verifier subagents tend to outperform self-critique. For long-running tasks, instruct: `Establish a method for checking your own work at an interval of [X] as you build. Run this every [X interval], verifying your work with subagents against the specification.`
174174* **Refactor existing prompts and skills.** Skills developed for prior models are often too prescriptive for Claude Fable 5 and can degrade output quality. Review and consider removing older instructions if default performance is better. Claude Fable 5 also does a good job of updating skills on the fly based on what it learns from the task at hand.
175* **Don't instruct Claude to reproduce its reasoning in the response.** Prompts, skills, or harness instructions that tell the model to echo, transcribe, or explain its internal reasoning as response text may trigger the [`reasoning_extraction` refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response) on Claude Fable 5. Server-side fallback with `fallbacks: "default"` doesn't retry requests declined with `reasoning_extraction`; that refusal is returned to you. Audit existing skills and system prompts for reflection or show-your-thinking instructions when migrating. If your application needs reasoning visibility, read the structured `thinking` blocks from [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) instead, and use a [send-to-user tool](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5#create-a-send-to-user-tool) to surface progress during long runs. You can still ask for a short explanation of the answer or a summary of the actions taken; see [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
175* **Don't instruct Claude to reproduce its reasoning in the response.** Prompts, skills, or harness instructions that tell the model to echo, transcribe, or explain its internal reasoning as response text might trigger the [`reasoning_extraction` refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response) on Claude Fable 5. Server-side fallback with `fallbacks: "default"` doesn't retry requests declined with `reasoning_extraction`; that refusal is returned to you. Audit existing skills and system prompts for reflection or show-your-thinking instructions when migrating. If your application needs reasoning visibility, read the structured `thinking` blocks from [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) instead, and use a [send-to-user tool](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5#create-a-send-to-user-tool) to surface progress during long runs. You can still ask for a short explanation of the answer or a summary of the actions taken; see [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
176176* **Create a send-to-user tool.** For long, asynchronous agents, a client-side tool delivers messages to the user verbatim without ending the turn. See [Create a send-to-user tool](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5#create-a-send-to-user-tool).
177177 

build-with-claude/prompt-engineering/prompting-claude-fable-5-1 Changed · +18 / -18 lines

from line 10
1010 
1111* Unsure which effort level to run, or latency and cost are higher than the task warrants: [Consider all effort levels](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#consider-all-effort-levels)
1212* Little or no text between tool calls: [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)
13* One tool call per turn in agent loops: [Batch independent tool calls in agent loops](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#batch-independent-tool-calls-in-agent-loops)
13* One tool call for each turn in agent loops: [Batch independent tool calls in agent loops](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#batch-independent-tool-calls-in-agent-loops)
1414* Requests fail with `bound to a different conversation`, or your harness edits earlier turns between requests: [Keep the conversation history append-only](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#keep-the-conversation-history-append-only)
1515* Prose runs long and dense: [Writing density](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#writing-density)
1616* Chat replies carry less structure than the content needs: [Formatting in chat](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#formatting-in-chat)
from line 28
2828<Note>
2929 Claude Fable 5.1 runs safety classifiers and can return `stop_reason: "refusal"`. See [Refusals, fallback, and billing](https://platform.claude.com/docs/en/models/fable-5-1/whats-new-fable-5-1#refusals-fallback-and-billing) and [Reduce safeguard false positives](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#reduce-safeguard-false-positives).
3030 
31 Prompts, skills, and tool descriptions that ask the model to write out its thinking or reasoning may be declined with the `reasoning_extraction` category. Ask for a short explanation or a summary of the actions taken instead, or read the reasoning from [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) blocks (`display: "summarized"`). See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
31 Prompts, skills, and tool descriptions that ask the model to write its thinking or reasoning might be declined with the `reasoning_extraction` category. Ask for a short explanation or a summary of the actions taken instead, or read the reasoning from [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) blocks (`display: "summarized"`). See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
3232</Note>
3333 
3434## Consider all effort levels
from line 43
4343 
4444Claude Fable 5.1's default behavior is to write fewer user-facing updates during long tool-calling turns than Claude Fable 5 does. This becomes more pronounced at higher effort and in longer tool chains. Users see the agent go quiet for minutes at a time, or a final message that covers only the last step rather than the whole task.
4545 
46First, check that your client receives progress updates at all. The model's short notes between tool calls, what it just found and what it's doing next, come back as [progress-update `thinking` blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates), and those blocks are empty under the default `thinking.display` of `"omitted"`. Set `display: "updates"` (beta, `thinking-display-updates-2026-08-18` header) and render each non-empty `thinking` block as a status line, or set `"summarized"` to receive them along with summarized reasoning. If you aren't requesting them, the model's updates may simply not be reaching your users.
46First, check that your client receives progress updates at all. The model's short notes between tool calls, what it just found and what it's doing next, come back as [progress-update `thinking` blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates), and those blocks are empty under the default `thinking.display` of `"omitted"`. Set `display: "updates"` (beta, `thinking-display-updates-2026-08-18` header) and render each non-empty `thinking` block as a status line, or set `"summarized"` to receive them along with summarized reasoning. If you aren't requesting them, the model's updates might simply not be reaching your users.
4747 
48Second, audit your prompt for instructions that suppress narration. Some earlier models were eager to give updates while working, which led to system prompt lines such as "hold all findings for the final response." Remove lines like that before adding anything.
48Second, audit your prompt for instructions that suppress narration. Some earlier models gave frequent updates while working, which led to system prompt lines such as "hold all findings for the final response." Remove lines like that before adding anything.
4949 
5050If you still want more updates, for example when pair programming or in other human-in-the-loop work, add a short system prompt line that says when you want user-facing text from the model and what each update should contain:
5151 
from line 53
5353Before you start, say in a line what you're about to do; brief updates while you work help the user follow along. Close with a short recap that stands on its own — what you found, what you did, and what's next — so a reader who only sees the last message has the full picture.
5454```
5555 
56If your product collapses or hides tool output, tell the model. Otherwise it may run commands to "show" the user output that your UI never displays. Deliver the note in a [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) (`clear_at: "next_user_message"`, beta):
56If your product collapses or hides tool output, tell the model. Otherwise it may run commands to "show" the user output that your UI never displays. Each time you send back tool output that your UI hides, follow it with the note in a [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) (`clear_at: "next_user_message"`, beta):
5757 
5858```text wrap
5959Only you see that command's output — the user's terminal shows at most a few lines of it. If the user needs to read any of it, put it in your reply.
from line 61
6161 
6262## Batch independent tool calls in agent loops
6363 
64Claude Fable 5.1 usually issues parallel tool calls as expected: when a request names several things to fetch, it issues those calls in parallel. The exception is coding and computer-use loops where the next independent calls are implied by the task rather than explicitly requested (custom coding agents, bash-and-editor harnesses, computer use): there it may issue them one per turn instead. This doesn't affect answer quality, but each extra turn costs tokens, a round trip, and wall-clock time. A one-sentence nudge at the end of the current request addresses it:
64Claude Fable 5.1 usually issues parallel tool calls as expected: when a request names several things to fetch, it issues those calls in parallel. The exception is coding and computer-use loops where the next independent calls are implied by the task rather than explicitly requested (custom coding agents, bash-and-editor harnesses, computer use): there it might issue them one in each turn instead. This doesn't affect answer quality, but each extra turn costs tokens, a round trip, and wall-clock time. A one-sentence nudge at the end of the current request addresses it:
6565 
6666```text wrap
6767First privately list what you need next; then request every item that doesn't depend on another's result in this one response.
from line 69
6969 
7070Each time you send tool results back, append it after that user message as a [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages): a `role: "system"` entry in `messages` with `clear_at: "next_user_message"`. Once a later user message exists, the API clears the earlier copies, so the model reads only the newest one. Turn-scoped system messages are in beta and require the [beta header](https://platform.claude.com/docs/en/api/beta-headers) `mid-conversation-system-clear-at-2026-08-21`. Without the beta, place the sentence in a text block after the `tool_result` blocks in the same user message instead.
7171 
72Append a fresh copy each turn and leave the earlier copies where they are, byte-for-byte. They stay in the array, but once cleared the model doesn't see them and they cost no input tokens. Deleting or rewriting them is an edit to earlier turns: it restarts the [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) from that point and invalidates the thinking blocks that came after them (see [Keep the conversation history append-only](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#keep-the-conversation-history-append-only)).
72Append a fresh copy each turn and leave the earlier copies where they are, byte-for-byte. They stay in the array, but once cleared the model doesn't see them and they cost no input tokens. Deleting or rewriting them is an edit to earlier turns: it invalidates the thinking blocks that came after them (see [Keep the conversation history append-only](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#keep-the-conversation-history-append-only)).
7373 
7474The following loop shows this placement. Each assistant turn goes back exactly as returned, each user turn carries only the tool results, and a fresh turn-scoped copy of the nudge follows it.
7575 
from line 711
711711 response = nil
712712 loop do
713713 response = client.beta.messages.create(
714 model: "claude-fable-5-1",
714 model: Anthropic::Model::CLAUDE_FABLE_5_1,
715715 max_tokens: 16000,
716716 betas: ["mid-conversation-system-clear-at-2026-08-21"],
717717 tools: tools,
from line 751
751751 
752752Append each assistant turn to the history exactly as the API returned it, thinking blocks included, and don't edit earlier turns between requests. For new accounts created on or after August 31, 2026, Claude Fable 5.1's thinking blocks are valid [only in the exact conversation that produced them](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation): a request that replays a thinking block after its prefix (the system prompt, the tool list, or any earlier message) has changed returns a 400, or drops the affected blocks if you set `thinking.block_binding.prefix_mismatch_behavior: "drop_block"` (beta, `thinking-binding-controls-2026-08-01` header). Adopt the pattern even if the check isn't enforced for your account, so the same code works on every account.
753753 
754The history edits that trip the check are the same ones that restart the [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): injecting and removing per-turn reminders, summarizing older turns in place, or changing the system prompt mid-session. Send per-turn reminders as [turn-scoped system messages](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages), change instructions or tools with a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) instead of rewriting `system` or `tools`, and let server-side [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) or [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) do any trimming. If you compact on the client, the simplest shape is to replace the whole history with one summary message plus the new user turn and replay nothing else: no thinking blocks carry over, so nothing fails, and the model thinks afresh on the compacted conversation (see [Custom compaction on the client](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client)). Because cache reads are now cheaper (see [Pricing](https://platform.claude.com/docs/en/models/fable-5-1/whats-new-fable-5-1#pricing)), compacting early to save cost may no longer be the right cost-intelligence tradeoff on Claude Fable 5.1, so experiment with later compaction points.
754Most history edits that trip the check also restart the [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): injecting and removing per-turn reminders, summarizing older turns in place, or changing the system prompt mid-session. Send per-turn reminders as [turn-scoped system messages](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages), change instructions or tools with a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) instead of rewriting `system` or `tools`, and let server-side [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) or [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) do any trimming. If you compact on the client, the simplest shape is to replace the whole history with one summary message plus the new user turn and replay nothing else: no thinking blocks carry over, so nothing fails, and the model thinks afresh on the compacted conversation (see [Custom compaction on the client](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#custom-compaction-on-the-client)). Because cache reads are now cheaper (see [Pricing](https://platform.claude.com/docs/en/models/fable-5-1/whats-new-fable-5-1#pricing)), compacting early to save cost may no longer be the right cost-intelligence tradeoff on Claude Fable 5.1, so experiment with later compaction points.
755755 
756756To find edits your harness already makes, run a session with `prefix_mismatch_behavior: "drop_block"` and log `input_transformations`, as described in [How to tell whether your integration is impacted](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#how-to-tell-whether-your-integration-is-impacted), or capture the exact requests it sends over a few normal turns and confirm that consecutive requests are byte-identical up to the appended turns.
757757 
from line 771
771771 
772772## Formatting in chat
773773 
774Earlier models overused bullets and bold in chat, and many prompts carry anti-formatting rules written to hold that down. Claude Fable 5.1 leans the other way: it uses bold less and is less likely to reach for headers, lists, or quotation marks. If your prompt contains anti-formatting language, remove it or replace it with a rule that says when specific formatting is appropriate, such as the following:
774Earlier models overused bullets and bold in chat, and many prompts carry anti-formatting rules written to reduce that. Claude Fable 5.1 tends toward the opposite: it uses bold less and is less likely to reach for headers, lists, or quotation marks. If your prompt contains anti-formatting language, remove it or replace it with a rule that says when specific formatting is appropriate, such as the following:
775775 
776776```text wrap
777777Use lists and bullet points when asked to, or when the content is multifaceted enough that they help with clarity. If the person explicitly requests minimal formatting, always format your responses without bullet points, headers, lists, or bold emphasis, as requested. In conversational, personal, or emotional exchanges, keep to plain prose.
from line 797
797797 
798798## Finish the whole task
799799 
800Claude Fable 5.1 can execute very long tasks without much guidance on methodology, especially when the goal is clear. On complex asynchronous workloads, though, nudge it not to end its turn before the work is done. Without the nudge, the model sometimes describes what it would do next instead of doing it ("Next, I'll …") or stops to ask permission for a step the original request already covered ("Shall I apply this?"). Users have to reply "continue" or "go ahead," which suits pair programming and other human-in-the-loop work but doesn't use the model's full long-horizon capability.
800Claude Fable 5.1 can run very long tasks without much guidance on methodology, especially when the goal is clear. On complex asynchronous workloads, though, nudge it not to end its turn before the work is done. Without the nudge, the model sometimes describes what it would do next instead of doing it ("Next, I'll …") or stops to ask permission for a step the original request already covered ("Shall I apply this?"). Users have to reply "continue" or "go ahead," which suits pair programming and other human-in-the-loop work but doesn't use the model's full long-horizon capability.
801801 
802802Two system prompt additions together mitigate this. Apply both. If you need to limit prompt length, use only the first, which keeps most of the effect. The first tells the model not to ask about work already requested and to carry out the next steps it has stated:
803803 
from line 834
834834 
835835## Keep changes and tests to what the task asks for
836836 
837When asked to implement an open-ended feature, Claude Fable 5.1 delivers what's asked for and sometimes more: it may fix nearby code, extend behavior the task didn't mention, or commit more test files than the change warrants. It responds well to explicit instructions about what to leave out. With the following instruction, unrequested additions and committed test code drop substantially with no measurable change in task success:
837When asked to implement an open-ended feature, Claude Fable 5.1 delivers what's asked for and sometimes more: it might fix nearby code, extend behavior the task didn't mention, or commit more test files than the change warrants. It responds well to explicit instructions about what to leave out. With the following instruction, unrequested additions and committed test code drop substantially with no measurable change in task success:
838838 
839839```text wrap
840840If, while working or testing, you find a pre-existing bug, a performance concern, or behavior the task doesn't mention, don't fix, optimize or extend it in this change unless the requested behavior cannot work without it; report it as a follow-up in your summary. Where the task is ambiguous, implement the reading its wording and the surrounding code most directly support, state that assumption in your summary, and don't build for the other readings as well. Verify your work however you like; scratch scripts and quick checks need not be kept. Commit tests only where the task asks for them or this repository already keeps tests for this kind of change, sized like the neighboring test files — roughly one focused test per stated behavior — and don't turn scratch checks into additional permanent test files. This is about extras only: implement every behavior the task asks for, completely.
from line 860
860860 
861861## Prefer targeted edits over whole-file rewrites
862862 
863If Claude Fable 5.1 rewrites whole files for small changes, append the following instruction to the system prompt or the first user message. Claude Fable 5.1 is more likely than Claude Fable 5 to rewrite an entire text file rather than make a targeted edit. The resulting file is usually the same, but unless the file is short or most of it is changing, a rewrite costs more output tokens and time. The instruction brings Claude Fable 5.1 back in line with Claude Fable 5 for small and medium changes.
863If Claude Fable 5.1 rewrites whole files for small changes, append the following instruction to the system prompt or the first user message. Claude Fable 5.1 is more likely than Claude Fable 5 to rewrite an entire text file rather than make a targeted edit. The resulting file is usually the same, but unless the file is short or most of it is changing, a rewrite costs more output tokens and time. With the instruction, Claude Fable 5.1 behaves like Claude Fable 5 on small and medium changes.
864864 
865865```text wrap
866866The number of tokens used to edit files is best minimized, all else being equal. Therefore, when it will not affect the end result, try to surgically edit a file rather than rewrite the entire thing.
from line 868
868868 
869869## Leave room for long outputs at xhigh and max effort
870870 
871At `xhigh` and especially `max` effort, Claude Fable 5.1 can think for longer before it starts writing its reply. When a single request asks for a long deliverable, such as a full rewrite of a long document, it may draft much of that deliverable in its thinking and then write it out again as the reply, which means a longer wait and more output tokens. The simplest approach is to run requests like these at `high`, the recommended starting point, and move to `xhigh` or `max` only where you've measured a quality gain (see [Consider all effort levels](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#consider-all-effort-levels)). If you do run them at `xhigh` or `max`:
871At `xhigh` and especially `max` effort, Claude Fable 5.1 can think for longer before it starts writing its reply. When a single request asks for a long deliverable, such as a full rewrite of a long document, it might draft much of that deliverable in its thinking and then write it again as the reply, which means a longer wait and more output tokens. The simplest approach is to run requests like these at `high`, the recommended starting point, and move to `xhigh` or `max` only where you've measured a quality gain (see [Consider all effort levels](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#consider-all-effort-levels)). If you do run them at `xhigh` or `max`:
872872 
873873* Set `max_tokens` to leave room for the thinking and the reply, not just the reply length you expect.
874874* Append the following note to the end of the user message. It makes the thinking much shorter on prose and code requests. Replace `[max_tokens]` with the request's actual `max_tokens` value, for example 64,000.
from line 885
885885 
886886* Have the tool that starts a subagent return immediately.
887887* Pass each subagent's result back to the lead in a later `user` message once it's ready.
888* Give the lead a separate tool it can call when it wants to wait for a result.
888* Give the lead a separate tool it can call to wait for a result.
889889 
890The model still often chooses to wait. The time savings come from the runs where it carries on with other work.
890The model still often waits. The time savings come from the runs where it carries on with other work.
891891 
892892## Give vision work tools to crop and zoom
893893 

build-with-claude/prompt-engineering/prompting-claude-haiku-5-5 Changed · +4 / -4 lines

from line 50
5050 
5151Render the date once, when the conversation starts, and send the same `system` and `tools` on every later request in that conversation (see [Keep earlier turns unchanged](https://platform.claude.com/docs/en/models/haiku-5-5/migration-guide#keep-earlier-turns-unchanged)). When a conversation continues on a later day, [give the new date in the newest turn](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#changing-context) instead.
5252 
53The model also sometimes needs an extra nudge to search. This happens most at `low` effort and with long system prompts. To fix it, add this text directly after the date:
53The model also sometimes needs an extra nudge to search. This occurs most at `low` effort and with long system prompts. To fix it, add this text directly after the date:
5454 
5555```text wrap
5656Your training data ends well before today's date. Records, office holders, prices, versions, rules and anything "latest" may have changed since then, so search for those before you answer, even when you feel sure. Facts that can't change need no search. When the answer depends on where the user is, put the user's country or region in the search query.
from line 121
121121 
122122## Keep reasoning out of user-facing text
123123 
124Claude Haiku 5.5 sometimes writes reasoning-like text in the reply that users see. This happens more often with thinking off or at `low` effort. If you see this behavior, switch to adaptive thinking and `medium` effort.
124Claude Haiku 5.5 sometimes writes reasoning-like text in the reply that users see. This occurs more often with thinking off or at `low` effort. If you see this behavior, switch to adaptive thinking and `medium` effort.
125125 
126126## Safeguard refusals
127127 
from line 128
128128Claude Haiku 5.5 runs safety classifiers that can decline a request. A declined request returns a response with `stop_reason: "refusal"`, and `stop_details.category` names the [refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response):
129129 
130130* `cyber`: the request could enable cyber harm, such as malware or exploit development. Finding vulnerabilities in source code is allowed. High-risk dual-use cybersecurity work isn't allowed. Benign cybersecurity work can also trigger this category. If the `cyber` classifier blocks your organization's legitimate security work, you can apply to the [Cyber Verification Program](https://support.claude.com/en/articles/14604842).
131* `frontier_llm`: the request could assist the development of competing AI models.
131* `frontier_llm`: the request could help with the development of competing AI models.
132132* `bio`: the request could enable biological harm, such as dangerous lab methods. Everyday health and educational questions aren't affected. If the `bio` classifier blocks your organization's life sciences work, you can apply to the [Life Sciences Verification Program](https://www.anthropic.com/news/life-sciences-verification-program).
133* `general_harms`: the request falls under a usage-policy area other than the three above. Benign work can also trigger this category.
133* `general_harms`: the request falls under a usage-policy area other than the previous three. Benign work can also trigger this category.
134134 
135135If you're moving from Claude Haiku 4.5, these refusals are new.
136136 

build-with-claude/prompt-engineering/prompting-claude-opus-4-8 Changed · +11 / -11 lines

from line 14
1414 
1515## Response length and verbosity
1616 
17Claude Opus 4.8 calibrates response length to how complex it judges the task to be, rather than defaulting to a fixed verbosity. This usually means shorter answers on simple lookups and much longer ones on open-ended analysis.
17Claude Opus 4.8 calibrates response length to the complexity of the task, rather than defaulting to a fixed verbosity. This usually means shorter answers on simple lookups and much longer ones on open-ended analysis.
1818 
19If your product depends on a certain style or verbosity of output, you may need to tune your prompts. As an example, to decrease verbosity, you might add:
19If your product depends on a certain style or verbosity of output, you might need to tune your prompts. As an example, to decrease verbosity, you might add:
2020 
2121```text wrap
2222Provide concise, focused responses. Skip non-essential context, and keep examples minimal.
from line 28
2828 
2929The [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort) allows you to tune Claude's intelligence versus token spend, trading off capability for faster speed and lower costs. Start with the `xhigh` effort level for coding and agentic use cases, and use a minimum of `high` effort for most intelligence-sensitive use cases. Experiment with other effort levels to further tune token usage and intelligence:
3030 
31* **`max`:** Max effort can deliver performance gains in some use cases, but may show diminishing returns from increased token usage. This setting can also sometimes be prone to overthinking. Test max effort for intelligence-demanding tasks.
31* **`max`:** Max effort can deliver performance gains in some use cases, but might show diminishing returns from increased token usage. This setting can also sometimes be prone to overthinking. Test max effort for intelligence-demanding tasks.
3232* **`xhigh`:** Extra high effort is the best setting for most coding and agentic use cases.
3333* **`high`:** This setting balances token usage and intelligence. For most intelligence-sensitive use cases, use a minimum of `high` effort.
3434* **`medium`:** Good for cost-sensitive use cases that need to reduce token usage while trading off intelligence.
3535* **`low`:** Reserve for short, scoped tasks and latency-sensitive workloads that are not intelligence-sensitive.
3636 
37Claude Opus 4.8 respects effort levels strictly, especially at the low end. At `low` and `medium`, the model scopes its work to what was asked rather than going above and beyond. This is good for latency and cost, but on moderately complex tasks running at `low` effort there is some risk of under-thinking.
37Claude Opus 4.8 respects effort levels strictly, especially at the low end. At `low` and `medium`, the model scopes its work to what was asked rather than going beyond the request. This is good for latency and cost, but on moderately complex tasks running at `low` effort there is some risk of under-thinking.
3838 
3939If you observe shallow reasoning on complex problems, raise effort to `high` or `xhigh` rather than prompting around it. If you need to keep effort at `low` for latency, add targeted guidance:
4040 
from line 44
4444 
4545Effort is likely to be more important for this model than for any prior Opus, so experiment with it actively when you upgrade.
4646 
47On Claude Opus 4.8, thinking is off unless you explicitly set `thinking: {type: "adaptive"}`. The triggering behavior for [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) is steerable. If you find the model thinking more often than you'd like, which can happen with large or complex system prompts, add guidance to steer it. As always, measure the effect of any prompting changes on performance. Example:
47On Claude Opus 4.8, thinking is off unless you explicitly set `thinking: {type: "adaptive"}`. The triggering behavior for [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) is steerable. If you find the model thinking more often than you'd like, which can occur with large or complex system prompts, add guidance to steer it. As always, measure the effect of any prompting changes on performance. Example:
4848 
4949```text wrap
5050Thinking adds latency and should only be used when it will meaningfully improve answer quality — typically for problems that require multistep reasoning. When in doubt, respond directly.
from line 70
7070 
7171## Tone and writing style
7272 
73As with any new model, prose style on long-form writing may shift. Claude Opus 4.8 tends toward a direct, opinionated style with minimal validation-forward phrasing and sparing emoji use. If your product relies on a specific voice, re-evaluate style prompts against the new baseline.
73As with any new model, prose style on long-form writing might shift. Claude Opus 4.8 tends toward a direct, opinionated style with minimal validation-forward phrasing and sparing emoji use. If your product relies on a specific voice, re-evaluate style prompts against the new baseline.
7474 
7575For instance, if your product voice is warmer or more conversational, add:
7676 
from line 90
9090 
9191## Design and frontend defaults
9292 
93Claude Opus 4.8 has strong design instincts, with a consistent default house style: warm cream/off-white backgrounds (\~`#F4F1EA`), serif display type (Georgia, Fraunces, Playfair), italic word-accents, and a terracotta/amber accent. This reads well for editorial, hospitality, and portfolio briefs, but will feel off for dashboards, dev tools, fintech, healthcare, or enterprise apps. The default appears in slide decks and web UIs.
93Claude Opus 4.8 has strong design instincts, with a consistent default house style: warm cream/off-white backgrounds (\~`#F4F1EA`), serif display type (Georgia, Fraunces, Playfair), italic word-accents, and a terracotta/amber accent. This reads well for editorial, hospitality, and portfolio briefs, but feels off for dashboards, dev tools, fintech, healthcare, or enterprise apps. The default appears in slide decks and web UIs.
9494 
9595This default is persistent. Generic instructions ("don't use cream," "make it clean and minimal") tend to shift the model to a different fixed palette rather than producing variety. Two approaches work reliably:
9696 
from line 125
125125Before building, propose 4 distinct visual directions tailored to this brief (each as: bg hex / accent hex / typeface — one-line rationale). Ask the user to pick one, then implement only that direction.
126126```
127127 
128Additionally, Claude Opus 4.8 requires less frontend design prompting than previous models to avoid generic patterns that users call the "AI slop" aesthetic. With earlier models, Anthropic recommended a lengthier prompt snippet in the [frontend-design skill](https://github.com/anthropics/claude-code/blob/main/plugins/frontend-design/skills/frontend-design/SKILL.md). However, Claude Opus 4.8 generates distinctive, creative frontends with more minimal prompting guidance. This prompt snippet works well with the preceding prompting advice for variety:
128Additionally, Claude Opus 4.8 requires less frontend design prompting than previous models to avoid generic patterns that users call the "AI slop" aesthetic. With earlier models, Anthropic recommended a lengthier prompt snippet in the [frontend-design skill](https://github.com/anthropics/claude-code/blob/main/plugins/frontend-design/skills/frontend-design/SKILL.md). However, Claude Opus 4.8 generates distinctive, creative front ends with more minimal prompting guidance. This prompt snippet works well with the preceding prompting advice for variety:
129129 
130130```text wrap
131131<frontend_aesthetics>
from line 135
135135 
136136## Interactive coding products
137137 
138Claude Opus 4.8's token usage and behavior can differ between autonomous, asynchronous coding agents with a single user turn and interactive, synchronous coding agents with multiple user turns. Specifically, it tends to use more tokens in interactive settings, primarily because it reasons more after user turns. This can improve long-horizon coherence, instruction following, and coding capabilities in long, interactive coding sessions, but also comes with more token usage. To maximize both performance and token efficiency in coding products, use `xhigh` or `high` effort, add autonomous features like an auto mode, and reduce the number of human interactions required from your users.
138Claude Opus 4.8's token usage and behavior can differ between autonomous, asynchronous coding agents with a single user turn and interactive, synchronous coding agents with multiple user turns. Specifically, it tends to use more tokens in interactive settings, primarily because it reasons more after user turns. This can improve long-horizon coherence, instruction following, and coding capabilities in long, interactive coding sessions, but also comes with more token usage. To maximize both performance and token efficiency in coding products, use `xhigh` or `high` effort, add autonomous features such as an auto mode, and reduce the number of human interactions required from your users.
139139 
140140Of course, when limiting the number of required user interactions, it's important to specify the task, intent, and relevant constraints upfront in the first human turn. Providing well-specified, clear, and accurate task descriptions upfront can help maximize autonomy and intelligence while minimizing extra token usage after user turns. Because Claude Opus 4.8 is more autonomous than prior models, this usage pattern helps to maximize performance. In contrast, ambiguous or underspecified prompts conveyed progressively over multiple user turns tend to relatively reduce token efficiency and sometimes performance.
141141 
142142## Code review harnesses
143143 
144Claude Opus 4.8 is meaningfully better at finding bugs than prior models, and has both higher recall and precision in internal evals. However, if your code-review harness was tuned for an earlier model, you may initially see lower recall. This is likely a harness effect, not a capability regression. When a review prompt says things like "only report high-severity issues," "be conservative," or "don't nitpick," Claude Opus 4.8 may follow that instruction more faithfully than earlier models did: it may investigate the code just as thoroughly, identify the bugs, and then not report findings it judges to be below your stated bar. This can show up as the model doing the same depth of investigation but converting fewer investigations into reported findings, especially on lower-severity bugs. Precision typically rises, but measured recall can fall even though the model's underlying bug-finding ability has improved.
144Claude Opus 4.8 is meaningfully better at finding bugs than prior models, and has both higher recall and precision in internal evals. However, if your code-review harness was tuned for an earlier model, you may initially see lower recall. This is likely a harness effect, not a capability regression. When a review prompt says things like "only report high-severity issues," "be conservative," or "don't nitpick," Claude Opus 4.8 may follow that instruction more faithfully than earlier models did: it may investigate the code just as thoroughly, identify the bugs, and then not report findings it determines to be below your stated bar. This can show up as the model doing the same depth of investigation but converting fewer investigations into reported findings, especially on lower-severity bugs. Precision typically rises, but measured recall can fall even though the model's underlying bug-finding ability has improved.
145145 
146146Some recommended prompt language:
147147 
from line 151
151151 
152152This prompt can be used without having an actual second step, but moving confidence filtering out of the finding step often helps. If your harness has a separate verification, deduplication, or ranking stage, tell the model explicitly that its job at the finding stage is coverage rather than filtering.
153153 
154If you do want the model to self-filter in a single pass, be concrete about where the bar is rather than using qualitative terms like "important": for example, "report any bugs that could cause incorrect behavior, a test failure, or a misleading result; only omit nits like pure style or naming preferences."
154If you do want the model to self-filter in a single pass, be concrete about where the bar is rather than using qualitative terms such as "important": for example, "report any bugs that could cause incorrect behavior, a test failure, or a misleading result; only omit nits like pure style or naming preferences."
155155 
156156Iterate on prompts against a subset of your evals or test cases to validate recall or F1 score gains.
157157 

build-with-claude/prompt-engineering/prompting-claude-opus-5 Changed · +8 / -8 lines

from line 12
1212 
1313Compared with Claude Opus 4.8, the improvements most relevant to prompting are:
1414 
15* **Agentic coding:** Claude Opus 5 is strongest on difficult coding tasks: multi-file features, larger refactors, and end-to-end feature work. It completes full tasks rather than leaving stubs or placeholders, and it performs best when given the complete task specification up front and left to run. It also performs well on easier tasks like single-turn edits, where the difference from prior models is smaller.
16* **Code review and bug-finding:** Claude Opus 5 reviews code with high precision and recall: it finds real bugs at a high rate per pass, and its additional findings are mostly real issues rather than false positives. Accuracy holds at lower effort settings, which supports a fast pass at review time and a more thorough pass later. If your review prompt says "only report high-severity issues" or "be conservative," the model may follow that instruction literally and report less; ask it to report everything and filter in a separate pass instead.
15* **Agentic coding:** Claude Opus 5 is strongest on difficult coding tasks: multifile features, larger refactors, and end-to-end feature work. It completes full tasks rather than leaving stubs or placeholders, and it performs best when given the complete task specification up front and left to run. It also performs well on easier tasks such as single-turn edits, where the difference from prior models is smaller.
16* **Code review and bug-finding:** Claude Opus 5 reviews code with high precision and recall: it finds real bugs at a high rate per pass, and its additional findings are mostly real issues rather than false positives. Accuracy holds at lower effort settings, which supports a fast pass at review time and a more thorough pass later. If your review prompt says "only report high-severity issues" or "be conservative," the model might follow that instruction literally and report less; ask it to report everything and filter in a separate pass instead.
1717* **Efficiency at lower effort:** `low` and `medium` [effort](https://platform.claude.com/docs/en/build-with-claude/effort) produce strong quality at a fraction of the tokens and latency of higher settings. Start with the default (`high`) and adjust based on your evals: use `low` and `medium` liberally as your primary control for token cost and response time wherever quality holds, and step up to `xhigh` for demanding coding and agentic work. If you carried effort defaults over from a prior model, re-run an effort sweep on your own evals. See [Effort](https://platform.claude.com/docs/en/build-with-claude/effort#recommended-effort-levels-for-claude-opus-5) for the full recommendations.
18* **Vision:** Claude Opus 5 is strong on chart, document, and diagram understanding, and on UI and frontend visual replication. Re-validate any prompt-side vision workarounds you tuned for prior models; they may no longer be needed. Vision performance is strongest when the model has tools to iteratively analyze, crop, and visually verify its work, and tool use is a more cost-effective lever than thinking alone.
18* **Vision:** Claude Opus 5 is strong on chart, document, and diagram understanding, and on UI and frontend visual replication. Re-validate any prompt-side vision workarounds you tuned for prior models; they might no longer be needed. Vision performance is strongest when the model has tools to iteratively analyze, crop, and visually verify its work, and tool use is a more cost-effective lever than thinking alone.
1919* **Long-context work:** Claude Opus 5 has a [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows) as both the default and the maximum, and its instruction following, tool calling, and reasoning stay consistent throughout the window.
20* **Office and document tasks:** Claude Opus 5 generates and works with complex, multi-sheet spreadsheets with non-trivial formulas, and it produces well-structured slide decks. Prompt it with any specific styles or templates it needs to follow.
21* **Multi-agent coordination:** Claude Opus 5 coordinates teams of subagents well, with effective writer-verifier patterns and few cases of agents overwriting each other's work. For cost-sensitive workloads, cap delegation; see [Controlling subagent spawning](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#controlling-subagent-spawning).
20* **Office and document tasks:** Claude Opus 5 generates and works with complex, multisheet spreadsheets with non-trivial formulas, and it produces well-structured slide decks. Prompt it with any specific styles or templates it needs to follow.
21* **Multiagent coordination:** Claude Opus 5 coordinates teams of subagents well, with effective writer-verifier patterns and few cases of agents overwriting each other's work. For cost-sensitive workloads, cap delegation; see [Controlling subagent spawning](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#controlling-subagent-spawning).
2222 
2323## Response length and verbosity
2424 
from line 68
6868 
6969## Controlling subagent spawning
7070 
71Claude Opus 5 delegates to subagents more readily than prior models. Delegation pays off on genuinely independent, sizeable tracks of work, but it multiplies cost and time when applied to small tasks. If your harness supports subagents, give explicit guidance on which scenarios warrant delegation, or set deterministic caps on how many agents can be launched. For example:
71Claude Opus 5 delegates to subagents more readily than prior models. Delegation is worthwhile for genuinely independent, sizeable tracks of work, but it multiplies cost and time when applied to small tasks. If your harness supports subagents, give explicit guidance on which scenarios warrant delegation, or set deterministic caps on how many agents can be launched. For example:
7272 
7373```text wrap
7474Delegate to a subagent only for large tasks that are genuinely independent and parallelizable, such as a wide multi-file investigation. Do not delegate work you can finish yourself in a handful of tool calls, and do not use subagents to verify or double-check your own work. If one subagent can complete the task, use one rather than several, and keep spawn counts low.
7575```
7676 
77If your harness is Claude Code or the Claude Agent SDK, the deterministic caps are the `CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` and `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` environment variables and the SDK's `max_budget_usd` (typescript: `maxBudgetUsd`) option. They require Claude Code 2.1.217 or later, so update a pinned SDK before pointing it at Claude Opus 5. Claude Code adds a delegation instruction of its own on Claude Opus 5 only when you use its `claude_code` system prompt preset; with a custom or omitted system prompt, add a delegation instruction such as the example in this section yourself. See [Cap subagent depth, concurrency, and spend](https://code.claude.com/docs/en/agent-sdk/subagents#cap-subagent-depth-concurrency-and-spend) in the Agent SDK docs.
77If your harness is Claude Code or the Claude Agent SDK, the deterministic caps are the `CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` and `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` environment variables and the SDK's `max_budget_usd` (typescript: `maxBudgetUsd`) option. Older versions of Claude Code don't have them, so use the latest version and update a pinned SDK before pointing it at Claude Opus 5. Claude Code adds a delegation instruction of its own on Claude Opus 5 only when you use its `claude_code` system prompt preset; with a custom or omitted system prompt, add a delegation instruction such as the example in this section yourself. See [Cap subagent depth, concurrency, and spend](https://code.claude.com/docs/en/agent-sdk/subagents#cap-subagent-depth-concurrency-and-spend) in the Agent SDK docs.
7878 
7979## Self-correction
8080 
from line 104
104104 
105105## Reasoning in the response
106106 
107Prompts, skills, and tool descriptions that ask Claude Opus 5 to write out its thinking or reasoning, verbatim or in a fixed format, may be declined with the `reasoning_extraction` [refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response). Ask for a short explanation of the answer or a summary of the actions taken instead, and, if you need the reasoning, keep thinking on and read the [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) blocks (`display: "summarized"`). See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
107Prompts, skills, and tool descriptions that ask Claude Opus 5 to write its thinking or reasoning, verbatim or in a fixed format, might be declined with the `reasoning_extraction` [refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response). Ask for a short explanation of the answer or a summary of the actions taken instead, and, if you need the reasoning, keep thinking on and read the [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) blocks (`display: "summarized"`). See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
108108 

build-with-claude/prompt-engineering/prompting-claude-opus-5-5 Changed · +20 / -20 lines

## Explore context in multiapp workflows ## Explore context in multi-app workflows

from line 1
11---
22title: Prompting Claude Opus 5.5
33url: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5
4description: "Behavioral differences from Claude Opus 5 and the prompting and harness patterns that address them: effort calibration, thinking behavior in API integrations and chat, progress updates, unattended and multiagent tasks, safeguard refusals, frontend design, complex visual inputs, multi-app workflows, and pasted text in user messages."
4description: "Behavioral differences from Claude Opus 5 and the prompting and harness patterns that address them: effort calibration, thinking behavior in API integrations and chat, progress updates, unattended and multiagent tasks, safeguard refusals, frontend design, complex visual inputs, multiapp workflows, and pasted text in user messages."
55---
66 
77This guide covers the prompting patterns specific to Claude Opus 5.5. For the model's capabilities and API changes, see [What's new in Claude Opus 5.5](https://platform.claude.com/docs/en/models/opus-5-5/whats-new-opus-5-5). For techniques that apply across all current Claude models, see [Prompting best practices](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices).
88 
9Claude Opus 5.5 generates output tokens more than 30 percent faster than Claude Opus 5 and tends to finish the same task with fewer tokens. Existing Claude Opus 5 prompts should perform well without changes, and the patterns in [Prompting Claude Opus 5](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5) remain a reasonable starting point. Start with the section that matches what you observe:
9Claude Opus 5.5 generates output tokens more than 30 percent faster than Claude Opus 5 and tends to complete the same task with fewer tokens. Existing Claude Opus 5 prompts should perform well without changes, and the patterns in [Prompting Claude Opus 5](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5) remain a reasonable starting point. Start with the section that matches what you observe:
1010 
11* Unsure which effort level to run, or turns run longer and cost more than they did on Claude Opus 5: [Calibrate effort](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#calibrate-effort)
11* You're unsure which effort level to run, or turns run longer and cost more than they did on Claude Opus 5: [Calibrate effort](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#calibrate-effort)
1212* Your Claude Opus 5 integration ran with thinking disabled: [Prompts written for thinking disabled](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#prompts-written-for-thinking-disabled)
1313* An unattended agent stops partway through a long task after reporting progress: [Unattended agentic runs](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#unattended-agentic-runs)
1414* Requests return `stop_reason: "refusal"`: [Safeguard refusals](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#safeguard-refusals)
1515* Long agentic turns look silent, or you want updates at predictable points: [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#user-facing-progress-updates)
16* An agent that works across several connected apps misses information the task didn't point to: [Explore context in multi-app workflows](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#explore-context-in-multi-app-workflows)
16* An agent that works across several connected apps misses information the task didn't point to: [Explore context in multiapp workflows](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#explore-context-in-multi-app-workflows)
1717* You run a team of agents and want it to finish sooner: [Time signals for multiagent harnesses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#time-signals-for-multi-agent-harnesses)
1818* Replies in a chat application start slowly because the model thinks at length first: [Thinking instructions in chat system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#thinking-instructions-in-chat-system-prompts)
1919* The model follows instructions that arrived inside text a user pasted: [Mark pasted text in user messages](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#mark-pasted-text-in-user-messages)
from line 28
2828 
2929The capabilities that matter most for prompting are:
3030 
31* **Agentic coding and code review:** The model is strongest on multistep work in a real repository, such as carrying a change through a large code base until its tests pass. In Anthropic's testing, at its default `medium` effort the model matched or beat Claude Opus 5 at `high` effort on such tasks, in fewer steps and with fewer tokens. It also sustains long-running autonomous work better than Claude Opus 5, such as multi-hour audits and migrations of large code bases run end to end with parallel subagents and little oversight. Early testers also reported stronger code review, with more bugs caught than on Claude Opus 5 and fewer false alarms, and it explains its changes in plain language.
31* **Agentic coding and code review:** The model is strongest on multistep work in a real repository, such as carrying a change through a large code base until its tests pass. In Anthropic's testing, at its default `medium` effort the model matched or beat Claude Opus 5 at `high` effort on such tasks, in fewer steps and with fewer tokens. It also sustains long-running autonomous work better than Claude Opus 5, such as multihour audits and migrations of large code bases run end to end with parallel subagents and little oversight. Early testers also reported stronger code review, with more bugs caught than on Claude Opus 5 and fewer false alarms, and it explains its changes in plain language.
3232* **Knowledge work:** The model is much less likely to state an incorrect figure or cite the wrong source. It's better at financial modeling tasks, such as building a financial model and one-page summary for a transaction or finding and fixing errors in a valuation workbook, and it catches details that are easy to miss in large inputs, such as a date in a long planning thread that falls on the wrong weekday or a chart in a slide deck that doesn't match the underlying figures. The spreadsheets, slides, and documents it produces need less editing before you share them.
3333* **Communication:** Its reports on agentic work, both the updates while it works and the summary when it finishes, say plainly what it did, what it found, and what it needs from you. See [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#user-facing-progress-updates).
3434* **Charts, diagrams, screenshots, and computer use:** The model reads visual material more accurately than Claude Opus 5 without extra tooling: in Anthropic's testing, even at its lowest effort setting it read values off dense charts more accurately than Claude Opus 5 did at its highest, using a small fraction of the output tokens. It is better, too, where meaning depends on position rather than text: which boxes an arrow connects in a flowchart, what changed between two versions of a diagram, or exactly when a meeting starts and ends in a calendar screenshot. It's also more reliable at computer use, where it operates applications from screenshots over many steps: at its default effort it matched the success rate that Claude Opus 5 reached only at a much higher effort setting. See [Tools for complex visual inputs](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#tools-for-complex-visual-inputs).
from line 50
5050Claude Opus 5 accepts `thinking: {"type": "disabled"}` at `high` effort or below; Claude Opus 5.5 doesn't, and the [migration guide](https://platform.claude.com/docs/en/models/opus-5-5/migration-guide#migrating-from-claude-opus-5) covers the request change. If your Claude Opus 5 integration ran with thinking disabled, four changes go with it:
5151 
5252* **Start at `low` effort and measure.** At `low` the model keeps its thinking short. How often it skips thinking altogether depends on your prompts, so measure latency and quality on your own traffic and move to `medium` if quality drops. If time to first token still matters after that, a system prompt line such as "Answer directly without deliberating." can reduce thinking further; measure quality when you add it, because less thinking can lower it.
53* **Remove instructions that stood in for thinking.** If your prompt asked the model to write out its reasoning in the response as a substitute for thinking, remove that instruction and read the reasoning from [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) blocks instead (`display: "summarized"`); a prompt that pushes the model to reproduce its reasoning in the response text may be declined with the `reasoning_extraction` [refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response).
53* **Remove instructions that stood in for thinking.** If your prompt asked the model to write its reasoning in the response as a substitute for thinking, remove that instruction and read the reasoning from [summarized thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#summarized-thinking) blocks instead (`display: "summarized"`); a prompt that pushes the model to reproduce its reasoning in the response text might be declined with the `reasoning_extraction` [refusal category](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response).
5454* **Re-test the thinking-disabled mitigations.** [Running with thinking disabled](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#running-with-thinking-disabled) recommends a combined instruction (permission to speak before a tool call, what to do when no tool fits, no internal tags) and removing any rule that tells the model not to think. Both address artifacts that appear on Claude Opus 5 only when thinking is disabled. With thinking always on, check whether you still need the instruction, and remove the no-thinking rule either way.
55* **Read the response by block type.** Check each block's type instead of assuming the first content block is text: a response may or may not begin with a `thinking` block, whose `thinking` field is empty under the default `display: "omitted"`.
55* **Read the response by block type.** Check each block's type instead of assuming the first content block is text: a response might or might not start with a `thinking` block, whose `thinking` field is empty under the default `display: "omitted"`.
5656 
5757## Unattended agentic runs
5858 
5959On long tasks with several parts, Claude Opus 5.5 keeps the user updated as it works, and some of those updates end the turn with text rather than a tool call ([`stop_reason: "end_turn"`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#end-turn)). An unattended agent loop that treats such a turn as the end of the task stops running there. A few harness and prompt changes help it keep running.
6060 
61Treat a text-only end of turn as a report rather than as proof the task is done. Keep the task's parts in a checklist the model updates, such as a to-do tool or a file. If a turn ends with items still open and no blocker stated, send a short user message naming them, like the following one. You can also state the completion condition up front and have a separate, smaller model check the conversation against it at each end of turn, returning its reason as the next user message when the condition isn't met. Either way, stop after two or three automatic continuations on the same task rather than repeating them indefinitely, so that a run that is genuinely stuck ends and can be reviewed.
61Treat a text-only end of turn as a report rather than as proof the task is done. Keep the task's parts in a checklist the model updates, such as a to-do tool or a file. If a turn ends with items still open and no blocker stated, send a short user message naming them, such as the following one. You can also state the completion condition up front and have a separate, smaller model check the conversation against it at each end of turn, returning its reason as the next user message when the condition isn't met. Either way, stop after two or three automatic continuations on the same task rather than repeating them indefinitely, so that a run that is genuinely stuck ends and can be reviewed.
6262 
6363```text wrap
6464Your task list still has open items: migrate the remaining two endpoints and update their tests. Continue with them. If one is blocked, say what is blocking it.
from line 68
6868 
6969A system prompt addition can also make these early stops less frequent. Claude Opus 5.5 is responsive to instructions that name the specific kinds of early stop you want it to avoid, such as ending the turn with a summary that announces the next step instead of taking it. It also helps to name the stops you do want, for example when no work can advance without the user's input.
7070 
71The following paragraph is one example of such an addition, written for agents that run fully unattended, where you want the model to keep working rather than stop to report. Treat it as a starting point: you might need to adapt it for your own application. Add it at the end of your system prompt from the first request of the session: adding it partway through changes the `system` prompt and invalidates the conversation's earlier thinking blocks (see [Preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions)). Because it tells the model to put status notes in the same message as its next tool call, those notes arrive between tool calls as progress updates, whose text comes back empty at the default `thinking.display`; set `display: "updates"` to receive a summary of each (see [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#user-facing-progress-updates)). With this addition the model carries on where it would otherwise have stopped to check in, so keep your own confirmation step for risky or irreversible actions, and leave the addition out of human-in-the-loop applications, where someone is there to answer. Expect somewhat more tool calls and output tokens per task.
71The following paragraph is one example of such an addition, written for agents that run fully unattended, where you want the model to keep working rather than stop to report. Treat it as a starting point: you might need to adapt it for your own application. Add it at the end of your system prompt from the first request of the session: adding it partway through changes the `system` prompt and invalidates the conversation's earlier thinking blocks (see [Add instructions with a mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#new-instructions)). Because it tells the model to put status notes in the same message as its next tool call, those notes arrive between tool calls as progress updates, whose text comes back empty at the default `thinking.display`; set `display: "updates"` to receive a summary of each (see [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#user-facing-progress-updates)). With this addition the model carries on where it would otherwise have stopped to check in, so keep your own confirmation step for risky or irreversible actions, and leave the addition out of human-in-the-loop applications, where someone is there to answer. Expect somewhat more tool calls and output tokens per task.
7272 
7373```text wrap
7474A standing instruction from the user, the person you are working for. It is about how your turns end. A message with no tool call in it ends your turn, and the work stops there until you are asked to continue. The user has seen you end turns in four ways while work they asked for was still owed, and does not want any of them. One: a long summary of what was done that closes by announcing the next step and has no tool call, so the next thing never starts. Two: an offer to carry on with something unless the user would prefer otherwise, which stops to wait for an answer the user was not going to give. Three: a list of decisions for the user when, by your own account, none of them blocks the rest of the work. Four: deciding that this is a good place to report, because the turn has been long or a milestone is done. Status notes are welcome, and so are your recommendations on open decisions, but put them in the same message as your next tool call and carry on with whatever does not depend on the user's answer. If you notice yourself inviting the user to redirect you or offering to wait, delete it and do the next thing. The stops the user does want are the ones where nothing can move without them, or where the thing blocking you is deliberately protected from you. This does not override the need for confirmation on risky or destructive actions.
from line 80
8080 
8181* **Biology:** The biology safeguards are the same as Claude Fable 5.1's and are new if you're coming from Claude Opus 5. Everyday health and educational questions are unaffected. If the biology classifier gets in the way of your organization's life sciences work, apply to the [Life Sciences Verification Program](https://www.anthropic.com/news/life-sciences-verification-program).
8282* **Cybersecurity:** Finding vulnerabilities in source code is allowed. High-risk dual-use cybersecurity activities are not. If the cybersecurity classifier gets in the way of your organization's legitimate security work, apply to the [Cyber Verification Program](https://support.claude.com/en/articles/14604842).
83* **Reasoning extraction:** Requests that push the model to reproduce its internal reasoning in the response text may be declined with the `reasoning_extraction` category. If your prompts ask the model to write out its reasoning in the response, remove those instructions, set `display: "summarized"`, and read the summarized reasoning from the thinking blocks instead; see [Prompts written for thinking disabled](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#prompts-written-for-thinking-disabled). You can still ask for a short explanation of the answer or a summary of the actions taken; see [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
83* **Reasoning extraction:** Requests that push the model to reproduce its internal reasoning in the response text might be declined with the `reasoning_extraction` category. If your prompts ask the model to write its reasoning in the response, remove those instructions, set `display: "summarized"`, and read the summarized reasoning from the thinking blocks instead; see [Prompts written for thinking disabled](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#prompts-written-for-thinking-disabled). You can still ask for a short explanation of the answer or a summary of the actions taken; see [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
8484 
8585A classifier decline arrives as a normal response with `stop_reason: "refusal"` and a `stop_details` object naming the category. You can have the request retried automatically on a fallback model, except for `reasoning_extraction` declines, which server-side fallback returns to you instead of retrying; see [Refusals and fallback](https://platform.claude.com/docs/en/models/opus-5-5/whats-new-opus-5-5#refusals-and-fallback).
8686 
from line 88
8888 
8989Between tool calls, Claude Opus 5.5 writes short user-facing progress updates: what it just found and what it's doing next. Four levers control what your users see.
9090 
91First, check that your client receives them: on Claude Opus 5.5 these notes come back as [progress-update `thinking` blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates) rather than `text` blocks, and their text is empty at the default `thinking.display`, so a client that renders only `text` blocks can look silent during a long agentic turn. Set `display: "updates"` (beta, `thinking-display-updates-2026-08-18` header) to receive a short summary of each note; the [migration guide](https://platform.claude.com/docs/en/models/opus-5-5/migration-guide#text-between-tool-calls) shows how to render them.
91First, check that your client receives them: on Claude Opus 5.5 these notes come back as [progress-update `thinking` blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates) rather than `text` blocks, and their text is empty at the default `thinking.display`, so a client that renders only `text` blocks can look silent during a long agentic turn. Set `display: "updates"` (beta, `thinking-display-updates-2026-08-18` header) to receive a short summary of each note; see [Text between tool calls is returned in thinking blocks](https://platform.claude.com/docs/en/models/opus-5-5/migration-guide#text-between-tool-calls) for how to render them.
9292 
93Second, if the model may need to hand the user something verbatim partway through a long turn, such as a code snippet, give it a simple tool for sending the user a message and tell it to reserve the tool for that content. Declare the tool in `tools` from the first request of the session: adding it to `tools` later edits the conversation's prefix and invalidates earlier thinking blocks (see [Preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#tool-changes)).
93Second, if the model might need to hand the user something verbatim partway through a long turn, such as a code snippet, give it a simple tool for sending the user a message and tell it to reserve the tool for that content. Declare the tool in `tools` from the first request of the session: adding it to `tools` later edits the conversation's prefix and invalidates earlier thinking blocks (see [tool changes in Preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#tool-changes)).
9494 
9595Third, if you want more frequent or predictable updates, such as a one-line statement of intent before the first tool call and a short recap at the end, say so in the system prompt; the model is responsive to such instructions. This helps most in human-in-the-loop work.
9696 
97Fourth, if long tool-calling turns still go quiet for longer than you want, have your harness ask for an update. With `display: "updates"` set (the first lever), count consecutive tool-calling steps that give the user nothing to read: no `text` block and no progress-update text. After several in a row (five, for example), append a reminder like the following one after the latest tool results, as a [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) (`clear_at: "next_user_message"`; beta, `mid-conversation-system-clear-at-2026-08-21` header). If the turn stays quiet, stop after two or three reminders rather than sending more. Because each reminder is appended and left in place, rather than inserted for one request and deleted on the next, the prompt cache keeps matching and the [thinking blocks](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) that follow it stay valid. In Anthropic's testing on agentic coding tasks, this roughly halved the share of tasks with a long silent stretch, with no measurable change in cost.
97Fourth, if long tool-calling turns still go quiet for longer than you want, have your harness ask for an update. With `display: "updates"` set (the first lever), count consecutive tool-calling steps that give the user nothing to read: no `text` block and no progress-update text. After several in a row (five, for example), append a reminder such as the following one after the latest tool results, as a [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) (`clear_at: "next_user_message"`, in beta with the `mid-conversation-system-clear-at-2026-08-21` header). If the turn stays quiet, stop after two or three reminders rather than sending more. Because each reminder is appended and left in place, rather than inserted for one request and deleted on the next, the prompt cache keeps matching and the [thinking blocks](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#per-turn-reminders) that follow it stay valid. In Anthropic's testing on agentic coding tasks, this roughly halved the share of tasks with a long silent stretch, with no measurable change in cost.
9898 
9999```text wrap
100100The user hasn't heard from you in a while — say in a few words what you're doing, then continue.
101101```
102102 
103## Explore context in multi-app workflows
103## Explore context in multiapp workflows
104104 
105105In workflow automation across several connected apps, such as email, documents, spreadsheets, and CRM records, the information a task depends on often sits somewhere the request doesn't explicitly mention: for example, a policy in an old email thread, a rule on another spreadsheet tab, or a note on a customer record. Claude Opus 5.5 tends to get to work quickly, and on loosely specified tasks it helps to tell the model to look through the relevant sources before acting. If your agent works across several apps on tasks like these, one sentence in the system prompt makes it look around before it changes anything:
106106 
from line 108
108108Before taking any action, explore broadly with tool calls: list and open the emails, documents, spreadsheet tabs and records across the available apps that could be relevant to this task, including ones the task does not explicitly mention, and use what you find.
109109```
110110 
111In Anthropic's testing on multi-app automation tasks, Claude Opus 5.5 completed noticeably more of them correctly with this instruction, at both `medium` and `max` effort, at the cost of slightly more tool calls and tokens. Because it tells the model to act on what it finds, keep untrusted content out of the records it searches.
111In Anthropic's testing on multiapp automation tasks, Claude Opus 5.5 completed noticeably more of them correctly with this instruction, at both `medium` and `max` effort, at the cost of slightly more tool calls and tokens. Because it tells the model to act on what it finds, keep untrusted content out of the records it searches.
112112 
113113## Time signals for multiagent harnesses
114114 
115Claude Opus 5.5 pays close attention to information about elapsed time, and in a multiagent setup, for example a lead agent that delegates to subagents, you can use that to speed up the work through better parallelization. If you can estimate how long the task should take, give the model a time budget: have your harness add a short line at the end of each message it sends back to the model giving the elapsed time against that budget, in seconds, for example `elapsed 340s / 1200s`. The model paces its work to finish inside the budget and usually finishes well before it, so set the budget somewhat above the time you actually want spent and tune it on a sample of your own tasks. If you can't predict a sensible budget, show the elapsed time alone and add one sentence to the system prompt:
115Claude Opus 5.5 is highly responsive to information about elapsed time, and in a multiagent setup, for example a lead agent that delegates to subagents, you can use that to speed up the work through better parallelization. If you can estimate how long the task should take, give the model a time budget: have your harness add a short line at the end of each message it sends back to the model giving the elapsed time against that budget, in seconds, for example `elapsed 340s / 1200s`. The model paces its work to finish inside the budget and usually finishes well before it, so set the budget somewhat above the time you actually want spent and tune it on a sample of your own tasks. If you can't predict a sensible budget, show the elapsed time alone and add one sentence to the system prompt:
116116 
117117```text wrap
118118Time matters here: do not spend time that can be avoided, and the earlier a correct result is obtained, the better.
from line 122
122122 
123123## Thinking instructions in chat system prompts
124124 
125In chat applications, if your system prompt contains instructions that tell Claude to think carefully before answering, consider removing them for Claude Opus 5.5. The model determines how much to think, and [effort](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#calibrate-effort) is the main control. In Anthropic's testing in a chat product, removing such a line made replies start sooner, with no clear decline in the quality of the reply.
125In chat applications, if your system prompt contains instructions that tell Claude to think carefully before answering, consider removing them for Claude Opus 5.5. The model determines how much to think, and the [effort level](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#calibrate-effort) is the main control. In Anthropic's testing in a chat product, removing such a line made replies start sooner, with no clear decline in the quality of the reply.
126126 
127127In multi-turn chat, Claude Opus 5.5 sometimes goes back over an earlier answer while it thinks about a new message, even a short follow-up, which adds thinking and latency on later turns. If you would rather the model treat earlier answers as settled, add two sentences at the end of the system prompt:
128128 
from line 130
130130Once you have answered something, treat that answer as done. On later turns, focus your thinking on what the user is asking now, and don't go back over an earlier answer unless the user asks about it or points out a problem with it.
131131```
132132 
133In Anthropic's testing this reduced thinking on follow-up turns and made replies start sooner without affecting quality. Leave it out where you want the model to keep re-examining its earlier work, for example in long analyses, or in agentic tasks where a later step can reveal a mistake in an earlier one. The instruction may also make the model less likely to point out a mistake in an earlier answer on its own, so if that matters for your application, test for it before adopting the instruction.
133In Anthropic's testing this reduced thinking on follow-up turns and made replies start sooner without affecting quality. Leave it out where you want the model to keep re-examining its earlier work, for example in long analyses, or in agentic tasks where a later step can reveal a mistake in an earlier one. The instruction might also make the model less likely to point out a mistake in an earlier answer on its own, so if that matters for your application, test for it before adopting the instruction.
134134 
135135## Mark pasted text in user messages
136136 
137Claude Opus 5.5 resists indirect prompt injection, meaning instructions that arrive through tool results, web pages, and on-screen or browser content, better than any earlier Opus model. With the right context it is also robust against instructions inside content a user copied into their message from elsewhere, such as an email or a web page. To get that behavior, mark which text is the user's own and which was pasted from somewhere else. Wrap each pasted block in an opening and a closing tag that both carry the same short random ID, generated by your application, with each tag on its own line:
137Claude Opus 5.5 resists indirect prompt injection, meaning instructions that arrive through tool results, webpages, and on-screen or browser content, better than any earlier Opus model. With the right context it is also robust against instructions inside content a user copied into their message from elsewhere, such as an email or a webpage. To get that behavior, mark which text is the user's own and which was pasted from somewhere else. Wrap each pasted block in an opening and a closing tag that both carry the same short random ID, generated by your application, with each tag on its own line:
138138 
139139```text wrap
140140Summarize the main complaints in this thread.
from line 154
154154 
155155## Tools for complex visual inputs
156156 
157Because Claude Opus 5.5 reads charts, diagrams, and screenshots considerably more precisely than Claude Opus 5 without tools (see [Capabilities relevant to prompting](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#capability-improvements)), re-test whether you still need scaffolding you built for visual inputs on earlier models. For the densest inputs, two things still add accuracy. Higher-resolution images help, most of all for inputs like technical drawings. So do image-processing tools: run the model as an agent with access to a container that holds the raw images and has libraries such as PIL and OpenCV installed, so that it can crop, zoom, measure, and verify its work. If a container is too much overhead, a cropping tool alone still helps; the [crop tool recipe](https://platform.claude.com/cookbook/multimodal-crop-tool) has a working definition. The model uses these tools more effectively at higher effort levels. Without tools, raising effort improves its reading of technical drawings but does little for charts.
157Because Claude Opus 5.5 reads charts, diagrams, and screenshots considerably more precisely than Claude Opus 5 without tools (see [Capabilities relevant to prompting](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#capability-improvements)), re-test whether you still need scaffolding you built for visual inputs on earlier models. For the densest inputs, two things still add accuracy. Higher-resolution images help, most of all for inputs such as technical drawings. So do image-processing tools: run the model as an agent with access to a container that holds the raw images and has libraries such as PIL and OpenCV installed, so that it can crop, zoom, measure, and verify its work. If a container is too much overhead, a cropping tool alone still helps; the [crop tool recipe](https://platform.claude.com/cookbook/multimodal-crop-tool) has a working definition. The model uses these tools more effectively at higher effort levels. Without tools, raising effort improves its reading of technical drawings but does little for charts.
158158 
159159## Frontend design defaults
160160 

build-with-claude/prompt-engineering/prompting-claude-sonnet-5 Changed · +10 / -10 lines

from line 12
1212 
1313Claude Sonnet 5 calibrates response length to the complexity of the task rather than defaulting to a fixed verbosity. This usually means shorter answers on simple lookups and longer ones on open-ended analysis.
1414 
15If your product depends on a certain style or verbosity of output, you may need to tune your prompts. As an example, to decrease verbosity, you might add:
15If your product depends on a certain style or verbosity of output, you might need to tune your prompts. As an example, to decrease verbosity, you might add:
1616 
1717```text wrap
1818Provide concise, focused responses. Skip non-essential context, and keep examples minimal.
from line 32
3232 
3333As a rough cross-model mapping when migrating: Claude Sonnet 5 at medium is comparable in intelligence to Claude Sonnet 4.6 at high, and Claude Sonnet 5 at high is comparable to Claude Sonnet 4.6 at max. When benchmarking, match by observed thinking length rather than effort name.
3434 
35Claude Sonnet 5 respects effort levels strictly, especially at the low end. At `low` and `medium`, the model scopes its work to what was asked rather than going above and beyond. This is good for latency and cost, but on moderately complex tasks running at `low` effort there is some risk of under-thinking.
35Claude Sonnet 5 respects effort levels strictly, especially at the low end. At `low` and `medium`, the model scopes its work to what was asked rather than going beyond the request. This is good for latency and cost, but on moderately complex tasks running at `low` effort there is some risk of under-thinking.
3636 
3737If you observe shallow reasoning on complex problems, raise effort to `high` or `xhigh` rather than prompting around it. If you need to keep effort at `low` for latency, add targeted guidance:
3838 
from line 42
4242 
4343On Claude Sonnet 5, [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) is on by default. Requests without a `thinking` field run with adaptive thinking. This is a change from Claude Sonnet 4.6, where the same requests ran without thinking. To turn thinking off entirely, pass `thinking: {type: "disabled"}`. Because `max_tokens` is a hard limit on total output (thinking plus response text), revisit it for workloads that ran without thinking on Claude Sonnet 4.6. If you were previously using thinking off with Claude Sonnet 4.6, try thinking on with lower effort levels for Claude Sonnet 5.
4444 
45The triggering behavior for adaptive thinking is steerable. If you find the model emitting thinking blocks more often than you'd like, which can happen with large or complex system prompts, add guidance to steer it. As always, measure the effect of any prompting changes on performance. Example:
45The triggering behavior for adaptive thinking is steerable. If you find the model emitting thinking blocks more often than you'd like, which can occur with large or complex system prompts, add guidance to steer it. As always, measure the effect of any prompting changes on performance. Example:
4646 
4747```text wrap
4848Thinking adds latency and should only be used when it will meaningfully improve answer quality, typically for problems that require multistep reasoning. When in doubt, respond directly.
from line 53
5353Manual extended thinking (`thinking: {type: "enabled", budget_tokens: N}`) is not supported on Claude Sonnet 5 and returns a 400 error. It was deprecated on Claude Sonnet 4.6 and is now removed. Use adaptive thinking with the effort parameter instead.
5454 
5555<Note>
56 If you are running Claude Sonnet 5 at `high`, `xhigh`, or `max` effort, leave headroom in `max_tokens` so the model has room for thinking and tool calls. On long tasks, adaptive thinking can use a large share of the budget; if the budget is tight, you may see a response that is almost entirely thinking followed by a truncated answer and `stop_reason: "max_tokens"`. Raising `max_tokens` or dropping to `medium` effort resolves this. Because Claude Sonnet 5 uses a new tokenizer that produces approximately 30% more tokens for the same text, `max_tokens` limits tuned for Claude Sonnet 4.6 may truncate equivalent output. The exact increase depends on the content and workload shape.
56 If you are running Claude Sonnet 5 at `high`, `xhigh`, or `max` effort, leave headroom in `max_tokens` so the model has room for thinking and tool calls. On long tasks, adaptive thinking can use a large share of the budget; if the budget is tight, you might see a response that is almost entirely thinking followed by a truncated answer and `stop_reason: "max_tokens"`. Raising `max_tokens` or dropping to `medium` effort resolves this. Because Claude Sonnet 5 uses a new tokenizer that produces approximately 30 percent more tokens for the same text, `max_tokens` limits tuned for Claude Sonnet 4.6 might truncate equivalent output. The exact increase depends on the content and workload shape.
5757</Note>
5858 
5959## Tool use triggering
6060 
61Claude Sonnet 5 is more agentic than Claude Sonnet 4.6 by default and will reach for tools and run self-verification loops more readily. With thinking disabled, the model is less likely to reach for tools or consider searching; if you rely on tool calls with thinking off, add an explicit nudge in the system prompt. Effort is also a lever for tool usage: `high` or `xhigh` effort settings show substantially more tool usage in agentic search and coding. For scenarios where you want more tool use, you can also adjust your prompt to explicitly instruct the model about when and how to properly use its tools. For instance, if you find that the model is not using your web search tools, clearly describe why and how it should.
61Claude Sonnet 5 is more agentic than Claude Sonnet 4.6 by default and reaches for tools and runs self-verification loops more readily. With thinking disabled, the model is less likely to reach for tools or consider searching; if you rely on tool calls with thinking off, add an explicit nudge in the system prompt. Effort is also a lever for tool usage: `high` or `xhigh` effort settings show substantially more tool usage in agentic search and coding. For scenarios where you want more tool use, you can also adjust your prompt to explicitly instruct the model about when and how to properly use its tools. For instance, if you find that the model is not using your web search tools, clearly describe why and how it should.
6262 
6363## User-facing progress updates
6464 
from line 70
7070 
7171## Tone and writing style
7272 
73As with any new model, prose style on long-form writing may shift. If your product relies on a specific voice, re-evaluate style prompts against the new baseline.
73As with any new model, prose style on long-form writing might shift. If your product relies on a specific voice, re-evaluate style prompts against the new baseline.
7474 
7575For instance, if your product voice is warmer or more conversational, add:
7676 
from line 82
8282 
8383## Design and frontend defaults
8484 
85Claude Sonnet 5 may settle into a consistent default visual style on open-ended frontend and design briefs. A default house style can read well for some briefs but feel off for dashboards, dev tools, fintech, healthcare, or enterprise apps.
85Claude Sonnet 5 might settle into a consistent default visual style on open-ended frontend and design briefs. A default house style can read well for some briefs but feel off for dashboards, dev tools, fintech, healthcare, or enterprise apps.
8686 
8787Generic instructions ("don't use that color," "make it clean and minimal") tend to shift the model to a different fixed palette rather than producing variety. Two approaches work reliably:
8888 
from line 127
127127 
128128## Interactive coding products
129129 
130Token usage and behavior can differ between autonomous, asynchronous coding agents with a single user turn and interactive, synchronous coding agents with multiple user turns. To maximize both performance and token efficiency in coding products, use `xhigh` or `high` effort, add autonomous features like an auto mode, and reduce the number of human interactions required from your users.
130Token usage and behavior can differ between autonomous, asynchronous coding agents with a single user turn and interactive, synchronous coding agents with multiple user turns. To maximize both performance and token efficiency in coding products, use `xhigh` or `high` effort, add autonomous features such as an auto mode, and reduce the number of human interactions required from your users.
131131 
132132When limiting the number of required user interactions, it's important to specify the task, intent, and relevant constraints upfront in the first human turn. Providing well-specified, clear, and accurate task descriptions upfront can help maximize autonomy and intelligence while minimizing extra token usage after user turns. In contrast, ambiguous or underspecified prompts conveyed progressively over multiple user turns tend to relatively reduce token efficiency and sometimes performance.
133133 
134134## Code review harnesses
135135 
136If your code-review harness was tuned for an earlier model, you may initially see lower recall on Claude Sonnet 5. This is likely a harness effect, not a capability regression. When a review prompt says things like "only report high-severity issues," "be conservative," or "don't nitpick," Claude Sonnet 5 may follow that instruction more faithfully than earlier models did: it may investigate the code just as thoroughly, identify the bugs, and then not report findings it judges to be below your stated bar. This can show up as the model doing the same depth of investigation but converting fewer investigations into reported findings, especially on lower-severity bugs. Precision typically rises, but measured recall can fall even though the model's underlying bug-finding ability has improved.
136If your code-review harness was tuned for an earlier model, you may initially see lower recall on Claude Sonnet 5. This is likely a harness effect, not a capability regression. When a review prompt says things like "only report high-severity issues," "be conservative," or "don't nitpick," Claude Sonnet 5 may follow that instruction more faithfully than earlier models did: it may investigate the code just as thoroughly, identify the bugs, and then not report findings it determines to be below your stated bar. This can show up as the model doing the same depth of investigation but converting fewer investigations into reported findings, especially on lower-severity bugs. Precision typically rises, but measured recall can fall even though the model's underlying bug-finding ability has improved.
137137 
138138Some recommended prompt language:
139139 
from line 143
143143 
144144This prompt can be used without having an actual second step, but moving confidence filtering out of the finding step often helps. If your harness has a separate verification, deduplication, or ranking stage, tell the model explicitly that its job at the finding stage is coverage rather than filtering.
145145 
146If you do want the model to self-filter in a single pass, be concrete about where the bar is rather than using qualitative terms like "important": for example, "report any bugs that could cause incorrect behavior, a test failure, or a misleading result; only omit nits like pure style or naming preferences."
146If you do want the model to self-filter in a single pass, be concrete about where the bar is rather than using qualitative terms such as "important": for example, "report any bugs that could cause incorrect behavior, a test failure, or a misleading result; only omit nits like pure style or naming preferences."
147147 
148148Iterate on prompts against a subset of your evals or test cases to validate recall or F1 score gains.
149149 

build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5 Changed · +14 / -14 lines

from line 28
2828 
2929[Effort](https://platform.claude.com/docs/en/build-with-claude/effort) is the main control for how much Claude Sonnet 5.5 thinks, and with it quality, latency, and cost. Its levels are recalibrated: a level doesn't produce the same amount of thinking as the same level on Claude Sonnet 5. Run a fresh sweep against your own evals rather than carrying over the setting you used on Claude Sonnet 5. Start at `high`, the default on the Claude API, unless your workload is agentic or latency-sensitive. For agentic coding and multistep tool use, start at `medium` for well-specified tasks and move to `high` for harder or longer ones. For chat and other latency-sensitive work, start at `medium` or `low`, because higher effort means a longer wait before the reply starts. Raise effort if quality needs it.
3030 
31Lower effort also changes how the model finishes agentic work. At `low`, it keeps its thinking short and can skip verifying a change. See [Verification on coding tasks](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#verification-on-coding-tasks). At `low` and `medium`, on long agentic tasks, it's more likely to stop and check in with the user before it finishes. See [Steer initiative and scope](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#steer-initiative-and-scope).
31Lower effort also changes how the model completes agentic work. At `low`, it keeps its thinking short and can skip verifying a change. See [Verification on coding tasks](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#verification-on-coding-tasks). At `low` and `medium`, on long agentic tasks, it's more likely to stop and check in with the user before it completes its work. See [Steer initiative and scope](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#steer-initiative-and-scope).
3232 
3333Three adjustments help:
3434 
from line 52
5252 
5353With this prompt, the model carries more of the work through at `low` and `medium` effort, so sessions at those levels run longer and cost more. The prompt doesn't replace your own rules about risky or irreversible actions. Keep those rules in your system prompt.
5454 
55**Unrequested additions when coding.** The model tends to add tests, documentation, and small supporting files that fit your repository's conventions, even when you don't ask for them. It does this at every effort level, and more at higher effort. The requested change itself stays close to what was asked. Most teams will welcome this. If you prefer changes limited to what was explicitly requested, add only the second paragraph of that prompt, which starts "When the work the user asked for is done". At `xhigh` and `max` effort, that paragraph reduces these additions and makes changes smaller overall.
55**Unrequested additions when coding.** The model tends to add tests, documentation, and small supporting files that fit your repository's conventions, even when you don't ask for them. It does this at every effort level, and more at higher effort. The requested change itself stays close to what was asked. Most teams will welcome this. If you prefer changes limited to what was explicitly requested, add only the second paragraph of that prompt, which starts "When the work the user asked for is done." At `xhigh` and `max` effort, that paragraph reduces these additions and makes changes smaller overall.
5656 
57**Thoroughness at `xhigh` and `max` effort.** At these levels the model is especially thorough. After it finishes a task, it can start its own rounds of review and verification, sometimes with subagents if your harness provides them. It can also make related fixes it noticed along the way. This takes more time and tokens, so run routine work at `high` or below, where it's rare. If you do want that extra thoroughness of these effort levels, but want to direct it to the task itself, add this to your system prompt:
57**Thoroughness at `xhigh` and `max` effort.** At these levels the model is especially thorough. After it completes a task, it can start its own rounds of review and verification, sometimes with subagents if your harness provides them. It can also make related fixes it noticed along the way. This takes more time and tokens, so run routine work at `high` or below, where it's rare. If you do want that extra thoroughness of these effort levels, but want to direct it to the task itself, add this to your system prompt:
5858 
5959```text wrap
6060When the work the user asked for is done and its checks pass, stop and report. Don't start extra rounds of review or hardening on your own, and don't launch reviewer sub-agents unless the user asked for a review. If you think a deeper review is worth doing, say so at the end.
from line 62
6262 
6363In testing on coding tasks at `max` effort, this stopped the model from launching reviewer subagents and cut session cost by about a third, with no change in quality. It makes self-started review rounds by the main agent less frequent but doesn't remove them entirely.
6464 
65**Open-ended requests.** When a request is open-ended, for example "show me what you can do with this", the model can start building a presentation, report, or video when you only wanted ideas. If you want ideas or a plan first, say so in the request, or add this to your system prompt:
65**Open-ended requests.** When a request is open-ended, for example "show me what you can do with this," the model can start building a presentation, report, or video when you only wanted ideas. If you want ideas or a plan first, say so in the request, or add this to your system prompt:
6666 
6767```text wrap
6868When the user asks for ideas, options or a plan, give them that and stop. Don't start building or changing anything until they say to go ahead.
from line 72
7272 
7373To run Claude Sonnet 5.5 without up-front thinking, send `thinking: {"type": "between_tools"}`. It's the lowest thinking setting on this model, and it's accepted at `high` effort or below. If your integration runs with thinking off today, switch it to `between_tools` and check these points:
7474 
75* **Send `between_tools` at `high` effort or below.** At `xhigh` or `max` effort, a request with `between_tools` returns a 400 error. With `between_tools`, effort also can't change mid-conversation: a per-message `output_config.effort` that differs from the level in effect returns a 400 error. To vary effort per turn, use adaptive thinking. With `between_tools`, remove any instruction that tells the model not to think. Such instructions make it more likely that the model writes internal XML tags in its visible output.
76* **Read the response by block type.** With adaptive thinking, a response can begin with a `thinking` block, whose `thinking` field is empty under the default `display: "omitted"`. With `between_tools`, a response can begin with a progress-update `thinking` block. Don't assume the first content block is text.
75* **Send `between_tools` at `high` effort or below.** At `xhigh` or `max` effort, a request with `between_tools` returns a 400 error. With `between_tools`, effort also can't change mid-conversation: a per-message `output_config.effort` that differs from the level in effect returns a 400 error. To vary effort for each turn, use adaptive thinking. With `between_tools`, remove any instruction that tells the model not to think. Such instructions make it more likely that the model writes internal XML tags in its visible output.
76* **Read the response by block type.** With adaptive thinking, a response can start with a `thinking` block, whose `thinking` field is empty under the default `display: "omitted"`. With `between_tools`, a response can start with a progress-update `thinking` block. Don't assume the first content block is text.
7777* **Pass back the `thinking` blocks unchanged.** With `between_tools`, notes the model writes between tool calls still come back as `thinking` blocks when they run longer than a sentence or two. Each block carries a summary of the note. Pass them back unchanged with the rest of the assistant turn. A block you send back gives the model the full note it wrote, not the summary.
7878* **Use adaptive thinking for reasoning tasks without tools.** In a request without tools, `between_tools` means the model answers without thinking first. For tasks that need a few steps of working out, use adaptive thinking instead. See [Reasoning tasks with JSON output](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#reasoning-tasks-with-json-output).
7979 
from line 95
9595 
9696**Use adaptive thinking rather than `between_tools`.** In a request without tools, the model doesn't think before it answers under `between_tools`. The line has no effect there, and accuracy on these tasks is lower. Use adaptive thinking for these requests, with the steps in this section. In testing, splitting the request in two, one request for the answer and one for the JSON, led to high answer accuracy and JSON compliance, but at very high cost and latency.
9797 
98With structured outputs at `low` and `medium` effort, the model occasionally keeps thinking until it reaches `max_tokens`. At `high` effort and above, this almost never happens. Treat any response whose `stop_reason` is `"max_tokens"` as failed, even if its text holds valid JSON, and retry. Set `max_tokens` high enough for the thinking and the JSON, as [Calibrate effort](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#calibrate-effort) describes, but no higher than you're willing to spend on one attempt.
98With structured outputs at `low` and `medium` effort, the model occasionally keeps thinking until it reaches `max_tokens`. At `high` effort and above, this almost never occurs. Treat any response whose `stop_reason` is `"max_tokens"` as failed, even if its text holds valid JSON, and retry. Set `max_tokens` high enough for the thinking and the JSON, as [Calibrate effort](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#calibrate-effort) describes, but no higher than you're willing to spend on one attempt.
9999 
100100If you can't use structured outputs, ask for JSON in the prompt instead. The model then often works the problem out in the response text and writes the JSON at the end. The JSON usually holds the right answer, but a parser that expects the whole response to be JSON fails. Two things help:
101101 
102* **Parse the last JSON value in the response.** Read only the `text` blocks, and treat a response whose `stop_reason` is `"max_tokens"` as failed. Starting at each `{` or `[`, try to parse a JSON value. When one parses, continue from the end of that value, so values nested inside it aren't counted on their own. Keep the last value found. Don't take everything from the first `{` to the last `}`. The model occasionally writes a draft before its final JSON, and that range would include both. If your answer is several JSON values in a row, such as one record per line, keep the last run of values separated only by spaces, commas, or line breaks. Check that the result has the fields you expect, and retry once if it doesn't. In testing, this made nearly every response usable without changing its accuracy.
102* **Parse the last JSON value in the response.** Read only the `text` blocks, and treat a response whose `stop_reason` is `"max_tokens"` as failed. Starting at each `{` or `[`, try to parse a JSON value. When one parses, continue from the end of that value, so values nested inside it aren't counted on their own. Keep the last value found. Don't take everything from the first `{` to the last `}`. The model occasionally writes a draft before its final JSON, and that range would include both. If your answer is several JSON values in a row, such as one record on each line, keep the last run of values separated only by spaces, commas, or line breaks. Check that the result has the fields you expect, and retry once if it doesn't. In testing, this made nearly every response usable without changing its accuracy.
103103* **Also consider `xhigh` effort with adaptive thinking.** The model then works the problem out in its thinking and nearly always returns the JSON alone. Total output tokens stay about the same as at `high`, because the working moves from the response text into the thinking.
104104 
105105## User-facing progress updates
from line 106
106106 
107107Between tool calls, Claude Sonnet 5.5 writes user-facing notes about what it just found and what it's doing next. Notes longer than a sentence or two come back as [progress-update `thinking` blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates). Shorter remarks stay `text`. At the default `thinking.display`, a progress-update block's text is empty, so a client that renders only `text` blocks can look silent during a long agentic turn. This matters most in chat interfaces and other products where the user follows the model's work in real time.
108108 
109To show these notes, set `display: "updates"` (beta, `thinking-display-updates-2026-08-18` header). With `between_tools`, the notes come back with their summary text, so no `display` field is needed. `between_tools` takes no other field: `display`, `budget_tokens`, or `block_binding` sent with it returns a 400 error. The [migration guide](https://platform.claude.com/docs/en/models/sonnet-5-5/migration-guide#text-between-tool-calls) shows how to render the notes. Sometimes the model needs to show the user exact text partway through a long turn, such as a code snippet or a question it needs answered. For that case, give it a simple tool for sending the user a message. Tell the model to use that tool only for such content. Declare the tool in the first request of the session, so the `tools` list doesn't change later.
109To show these notes, set `display: "updates"` (beta, `thinking-display-updates-2026-08-18` header). With `between_tools`, the notes come back with their summary text, so no `display` field is needed. `between_tools` takes no other field: `display`, `budget_tokens`, or `block_binding` sent with it returns a 400 error. The migration guide's section on [text between tool calls](https://platform.claude.com/docs/en/models/sonnet-5-5/migration-guide#text-between-tool-calls) shows how to render the notes. Sometimes the model needs to show the user exact text partway through a long turn, such as a code snippet or a question it needs answered. For that case, give it a simple tool for sending the user a message. Tell the model to use that tool only for such content. Declare the tool in the first request of the session, so the `tools` list doesn't change later.
110110 
111Next, remove older instructions such as "hold all findings for the final response". If you then want updates at predictable points, for example a line on what the model is about to do before its first tool call and a short recap at the end, say so in the system prompt. The model follows instructions like this. Updates at set points help most in human-in-the-loop work.
111Next, remove older instructions such as "hold all findings for the final response." If you then want updates at predictable points, for example a line on what the model is about to do before its first tool call and a short recap at the end, say so in the system prompt. The model follows instructions like this. Updates at set points help most in human-in-the-loop work.
112112 
113113If long tool-calling turns still go quiet for longer than you want, your harness can prompt an update. Have it count consecutive tool-calling steps that send the user no text or progress update. After several in a row, for example five, append a one-turn reminder after the latest tool results. Send it as a [turn-scoped system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#turn-scoped-system-messages) (beta), with text like this:
114114 
from line 116
116116The user hasn't heard from you in a while — say in a few words what you're doing, then continue.
117117```
118118 
119If the turn stays quiet, stop sending reminders after the second or third. Frequent harness text after tool results can make the model suspect a prompt injection, as [Mid-turn user messages](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#mid-turn-user-messages-and-task-budgets) explains. Leave each reminder in `messages` on later requests. Because the reminder is appended rather than inserted and later deleted, the prompt cache and [preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking) stay intact. At `high` effort, with a tool for sending the user a message available, the reminder leads the model to update the user more often and shortens its longest silent stretches, with no measurable change in task quality.
119If the turn stays quiet, stop sending reminders after the second or third. Frequent harness text after tool results can lead the model to treat that text as a possible prompt injection, as [Mid-turn user messages](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#mid-turn-user-messages-and-task-budgets) explains. Leave each reminder in `messages` on later requests. Because the reminder is appended rather than inserted and later deleted, the prompt cache and [preserved thinking](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking) stay intact. At `high` effort, with a tool for sending the user a message available, the reminder leads the model to update the user more often and shortens its longest silent stretches, with no measurable change in task quality.
120120 
121121## Tool use in chat and knowledge work
122122 
123123On chat and knowledge-work tasks, Claude Sonnet 5.5 sometimes answers from its training knowledge when a web search would catch details that have changed. Examples include what is allowed, required, or charged.
124124 
125First, check your prompt for language that discourages tool use, such as "only use tools when strictly necessary" or "minimize tool calls", and remove it. Then, if your product gives the model a search tool, add this to your system prompt:
125First, check your prompt for language that discourages tool use, such as "only use tools when strictly necessary" or "minimize tool calls," and remove it. Then, if your product gives the model a search tool, add this to your system prompt:
126126 
127127```text wrap
128128Use the search tool to check specifics that may have changed since your training, such as what is allowed, required or charged, even when you feel confident. For researched work such as a report or a comparison, gather current sources rather than writing from your training knowledge.
from line 134
134134 
135135Claude Sonnet 5.5 is trained to resist indirect prompt injection, meaning malicious instructions that arrive through tool results and other content it reads during a task. Sometimes it treats a genuine user message as a possible injection. Suppose a message the user typed mid-task reaches the model as a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) placed directly after a tool result, or inside a `tool_result` block. The model can then tell the user that the tool result contained text posing as a message from them, and ignore the message or ask the user to confirm it.
136136 
137A token countdown that your harness adds after every tool result can cause this. So can letting users send messages while the model is partway through a multistep turn, or having your harness add instructions or context after the tool results on every step. In each case, text arrives right after the tool results. With a countdown or per-step instructions, that can happen on every tool call. An occasional one-turn reminder, like the one in [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#user-facing-progress-updates), arrives far less often. If you see this reaction to a reminder of your own, send the reminder less often. To avoid the misread:
137A token countdown that your harness adds after every tool result can cause this. So can letting users send messages while the model is partway through a multistep turn, or having your harness add instructions or context after the tool results on every step. In each case, text arrives right after the tool results. With a countdown or per-step instructions, that can occur on every tool call. An occasional one-turn reminder, like the one in [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#user-facing-progress-updates), arrives far less often. If you see this reaction to a reminder of your own, send the reminder less often. To avoid the misread:
138138 
139139* Never put user text inside a `tool_result` block. The model misreads that placement most often.
140140* Deliver mid-turn user input as a user turn. Append the user's words as a text block in the user message that carries the `tool_result` blocks, after the last `tool_result`.
from line 168
168168 
169169* `cyber`: the request could enable cyber harm, such as malware or exploit development. Finding vulnerabilities in source code is allowed. High-risk dual-use cybersecurity work isn't allowed.
170170* `bio`: the request could enable biological harm, such as dangerous lab methods. Everyday health and educational questions aren't affected.
171* `frontier_llm`: the request could assist the development of competing AI models.
171* `frontier_llm`: the request could help with the development of competing AI models.
172172* `reasoning_extraction`: the request asks the model to reproduce its internal reasoning in the response text.
173173* `general_harms`: the request falls under another usage-policy area. Benign work can also trigger this category.
174174 

build-with-claude/refusals-and-fallback Changed · +23 / -23 lines

from line 10
1010 
1111Related pages:
1212 
13* [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons): the full list of `stop_reason` values.
14* [Fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit): how to avoid paying the prompt-cache cost twice when you build the retry yourself.
15* [SDK middleware](https://platform.claude.com/docs/en/cli-sdks-libraries/middleware): the SDK helper that wraps all of this.
16* [Fallback and billing cookbook](https://platform.claude.com/cookbook/fable-5-fallback-billing-guide): a worked end-to-end example.
13* [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons): the full list of `stop_reason` values
14* [Fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit): how to avoid paying the prompt-cache cost twice when you build the retry yourself
15* [SDK middleware](https://platform.claude.com/docs/en/cli-sdks-libraries/middleware): the SDK helper that wraps all of this
16* [Fallback and billing recipe](https://platform.claude.com/cookbook/fable-5-fallback-billing-guide): a worked end-to-end example
1717 
1818The simplest setup, in beta on the Claude API: set `fallbacks` to `"default"`, and the API retries a declined request on the fallback model Anthropic recommends for its refusal category. For categories with no recommended fallback, the refusal stands. Claude Haiku 5.5 has no server-side fallback, so for it use [client-side fallback with the SDK middleware](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#client-side-fallback) or [write the retry yourself](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#manual-retry).
1919 
from line 135
135135 client = Anthropic::Client.new
136136 
137137 response = client.beta.messages.create(
138 model: "claude-fable-5",
138 model: Anthropic::Model::CLAUDE_FABLE_5,
139139 max_tokens: 1024,
140140 messages: [{role: "user", content: "Hello, Claude"}],
141141 fallbacks: :default,
from line 451
451451 client = Anthropic::Client.new
452452 
453453 response = client.beta.messages.create(
454 model: "claude-fable-5",
454 model: Anthropic::Model::CLAUDE_FABLE_5,
455455 max_tokens: 1024,
456456 messages: [{role: "user", content: "Hello, Claude"}],
457457 fallbacks: :default,
from line 470
470470 ```
471471</CodeGroup>
472472 
473Anthropic sets safeguards for each model individually and for each policy category, in line with the model's capability: depending on the category, a flagged request may fall back to a less capable model or be declined. The `"default"` mode encodes these per-model, per-category recommendations for you, so a refused request is retried on the model Anthropic recommends for that category. Fallbacks are visible either way: the response names the model that served it, and the `fallback` content block marks the handoff.
473Anthropic sets safeguards for each model individually and for each policy category, in line with the model's capability: depending on the category, a flagged request might fall back to a less capable model or be declined. The `"default"` mode encodes these per-model, per-category recommendations for you, so a refused request is retried on the model Anthropic recommends for that category. Fallbacks are visible either way: the response names the model that served it, and the `fallback` content block marks the handoff.
474474 
475The routing is applied server-side and is not published per model on the [Models API](https://platform.claude.com/docs/en/api/models/list). To see which model served a refused request, check the response's top-level `model` field and look for a `fallback_message` entry in `usage.iterations`, as this page's samples do.
475The routing is applied server-side and is not published for each model on the [Models API](https://platform.claude.com/docs/en/api/models/list). To see which model served a refused request, check the response's top-level `model` field and look for a `fallback_message` entry in `usage.iterations`, as this page's samples do.
476476 
477477Only a safety classifier decline triggers the fallback. A rate limit, overload, or server error on the requested model is returned to you as-is.
478478 
from line 610
610610 client = Anthropic::Client.new
611611 
612612 response = client.beta.messages.create(
613 model: "claude-fable-5",
613 model: Anthropic::Model::CLAUDE_FABLE_5,
614614 max_tokens: 1024,
615615 messages: [{role: "user", content: "Hello, Claude"}],
616 fallbacks: [{model: "claude-opus-4-8"}],
616 fallbacks: [{model: Anthropic::Model::CLAUDE_OPUS_4_8}],
617617 betas: ["server-side-fallback-2026-07-01"]
618618 )
619619 
from line 624
624624A few rules apply to the `fallbacks` list:
625625 
626626* Entries are tried in order. Each must be distinct from the other entries and from the requested model.
627* Each entry must be one of the requested model's permitted targets. With the beta header set, that list is published as `allowed_fallback_models` on the model's entry in the [Models API](https://platform.claude.com/docs/en/api/beta/models/list).
627* Each entry must be one of the requested model's permitted targets. With the beta header set, that list is published as `allowed_fallback_models` on the [model's entry in the Models API](https://platform.claude.com/docs/en/api/beta/models/list).
628628* Each entry names a `model` and can override `max_tokens`, `thinking`, `output_config`, and `speed` for that attempt only.
629629* The request must be valid as a direct request to every model named. If a fallback model does not support a feature the request uses, the API rejects the request up front. Under the `2026-07-01` header, `thinking: {"type": "between_tools"}` is the exception: when a Claude Sonnet 5.5 request falls back to Claude Sonnet 5, the fallback attempt runs with `thinking: {"type": "disabled"}` and `display: "omitted"`. Under `2026-06-01`, set `thinking` on the Claude Sonnet 5 entry, or the request is rejected up front.
630630* As with the default mode, only a safety classifier decline triggers the fallback. A rate limit, overload, or server error on the requested model is returned to you as-is.
from line 711
711711 
712712### Streaming
713713 
714On a streaming request, the retry happens on the same stream, and nothing you have already received is invalidated. What you see depends on when the decline happens.
714On a streaming request, the retry occurs on the same stream, and nothing you have already received is invalidated. What you see depends on when the decline occurs.
715715 
716**When the decline happens before any output:**
716**When the decline occurs before any output:**
717717 
718718* `message_start` names the fallback model, and the `fallback` block is the first content block.
719719* Because `message_start` waits for the fallback attempt to start, time to first byte includes the declined attempt.
720720 
721**When the decline happens mid-output:**
721**When the decline occurs mid-output:**
722722 
723723* The open content block closes, and the `fallback` block (an ordinary `content_block_start` and `content_block_stop` pair with no deltas) marks the boundary.
724724* The fallback model continues from the partial output. Only the partial output's `text` blocks are passed to the fallback model as context. Other block types remain in `content`.
from line 726
726726 
727727### Non-streaming responses
728728 
729On a non-streaming request, a mid-output decline behaves differently: the response omits the declined model's partial output, and the fallback model answers from scratch. The result looks like a decline before any output, with the `fallback` block first. The declined attempt and its output tokens still appear in `usage.iterations`.
729On a non-streaming request, a mid-output decline behaves differently: the response omits the declined model's partial output, and the fallback model answers from the beginning. The result looks like a decline before any output, with the `fallback` block first. The declined attempt and its output tokens still appear in `usage.iterations`.
730730 
731731<Note>
732732 **Declines during tool use:** completed tool work does not block fallback. When a decline fires after server tools (for example, web search or code execution) have finished executing within a request, the fallback attempt proceeds: the completed tool results carry over, and the fallback model can keep invoking server tools. The one case that does not retry is a streaming decline that fires while a tool-use block of any type (a client tool, a server tool, or an MCP tool call) is still open on the stream: that refusal is returned directly, and if the `fallback-credit-2026-07-01` header is set it still carries a credit token redeemable by continuing the partial response. Non-streaming requests are unaffected; the API clears the partial work and retries before responding.
from line 1077
10771077 # Streaming: on a refusal the middleware splices the fallback model's
10781078 # events onto the still-open stream.
10791079 stream = client.beta.messages.stream(
1080 model: "claude-fable-5",
1080 model: Anthropic::Model::CLAUDE_FABLE_5,
10811081 max_tokens: 1024,
10821082 messages: [{role: "user", content: "Hello, Claude"}],
10831083 request_options: {fallback_state: state}
from line 1087
10871087 
10881088 # Non-streaming: reusing the state keeps the conversation pinned to the model that accepted.
10891089 message = client.beta.messages.create(
1090 model: "claude-fable-5",
1090 model: Anthropic::Model::CLAUDE_FABLE_5,
10911091 max_tokens: 1024,
10921092 messages: [{role: "user", content: "Hello, Claude"}],
10931093 request_options: {fallback_state: state}
from line 1129
11291129 </Step>
11301130</Steps>
11311131 
1132A manual retry writes the fallback model's prompt cache from scratch, which costs more than reading an existing cache. [Fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit) refunds that cost; redeem it on every retry you build yourself. A Claude Haiku 5.5 refusal carries no fallback credit, so a retry after one pays the full cost of writing the fallback model's prompt cache.
1132A manual retry writes the fallback model's prompt cache in full, which costs more than reading an existing cache. [Fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit) refunds that cost; redeem it on every retry you build yourself. A Claude Haiku 5.5 refusal carries no fallback credit, so a retry after one pays the full cost of writing the fallback model's prompt cache.
11331133 
11341134## Refusals in Message Batches
11351135 
from line 1145
11451145## Common pitfalls
11461146 
11471147* **Retry on a different model.** Re-sending a refused request to the same model usually earns another refusal. Point the retry at the fallback model.
1148* **Budget retries per request, not per turn or per session.** A single turn can produce several refusals, for example an agent plus its sub-agents.
1148* **Budget retries for each request, not for each turn or session.** A single turn can produce several refusals, for example an agent plus its subagents.
11491149* **Configure fallback on every request path.** Retry handlers, error-recovery branches, and background workers all need it. A handler that re-issues a request without fallback loses the protection on exactly the requests most likely to need it.
1150* **Give sub-agent calls their own fallback.** The `fallbacks` parameter does not propagate into model calls made from inside tool execution.
1150* **Give subagent calls their own fallback.** The `fallbacks` parameter does not carry over to model calls made from inside tool execution.
11511151* **Make fallback a property of the request, not of ambient state.** A shared flag, cached config value, or global toggle can drift out of sync and silently leave a request unprotected. When you cannot confirm fallback is active, configure it rather than assume it is on.
1152* **Instrument refusals as their own signal.** A refusal is an HTTP 200, so monitoring built on error rates or 5xx responses never sees it. Emit one event per refusal and one per fallback-served response (the `fallback_message` entry in `usage.iterations` marks the latter), then alert on the gap between the two counts.
1152* **Instrument refusals as their own signal.** A refusal is an HTTP 200, so monitoring built on error rates or 5xx responses never sees it. Emit one event for each refusal and one for each fallback-served response (the `fallback_message` entry in `usage.iterations` marks the latter), then alert on the gap between the two counts.
11531153* **Branch on `stop_reason` or `stop_details.type`, not on `content` or the inner `stop_details` fields.** The `stop_details` object is always present on a refusal, but its `category` and `explanation` fields can be `null`. Check for `stop_reason` equal to `"refusal"` directly.
11541154 
11551155## Next steps

build-with-claude/search-results Changed · +10 / -10 lines

from line 1
11---
22title: Search results
33url: https://platform.claude.com/docs/en/build-with-claude/search-results
4description: Enable natural citations for RAG applications by providing search results with source attribution
4description: Get natural citations for RAG applications by providing search results with source attribution
55---
66 
77<Note>
from line 16
1616 
1717Search results can be provided in two ways:
1818 
191. **From tool calls:** Your custom tools return search results, enabling dynamic RAG applications
202. **As top-level content:** You provide search results directly in user messages for pre-fetched or cached content
191. **From tool calls:** Your custom tools return search results, which lets you build dynamic RAG applications.
202. **As top-level content:** You provide search results directly in user messages for pre-fetched or cached content.
2121 
2222In both cases, Claude cites the search results automatically when citations are enabled. No special prompting is needed: ask your question, and citations appear on the text blocks that draw on your content.
2323 
from line 69
6969 
7070## Method 1: Search results from tool calls
7171 
72Returning search results from your custom tools enables dynamic RAG applications: tools fetch content at runtime, and Claude cites it in the response. The following example forces the tool call with [`tool_choice`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use), so the retrieval step runs every time.
72Returning search results from your custom tools lets you build dynamic RAG applications: tools fetch content at runtime, and Claude cites it in the response. The following example forces the tool call with [`tool_choice`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use), so the retrieval step runs every time.
7373 
7474### Example: Knowledge base tool
7575 
7676<CodeGroup exclude="shell">
7777 <CodeGroupItem language="cURL">
78 The tool-calling flow needs search logic in your application, which needs more than a single shell command. Use the Claude SDK for the full flow. For the raw request shape of a tool conversation with search results, see [Combining both methods](https://platform.claude.com/docs/en/build-with-claude/search-results#combining-both-methods). For search results as top-level content, see [Method 2](https://platform.claude.com/docs/en/build-with-claude/search-results#method-2-search-results-as-top-level-content).
78 The tool-calling flow needs search logic in your application, which needs more than a single shell command. Use the Claude SDK for the full flow. For the raw request shape of a tool conversation with search results, see [Combining both methods](https://platform.claude.com/docs/en/build-with-claude/search-results#combining-both-methods). To provide search results directly in user messages, see [Method 2: Search results as top-level content](https://platform.claude.com/docs/en/build-with-claude/search-results#method-2-search-results-as-top-level-content).
7979 </CodeGroupItem>
8080 
8181 <CodeGroupItem language="CLI">
82 The tool-calling flow needs search logic in your application, which needs more than a single shell command. Use the Claude SDK for the full flow. For the raw request shape of a tool conversation with search results, see [Combining both methods](https://platform.claude.com/docs/en/build-with-claude/search-results#combining-both-methods). For search results as top-level content, see [Method 2](https://platform.claude.com/docs/en/build-with-claude/search-results#method-2-search-results-as-top-level-content).
82 The tool-calling flow needs search logic in your application, which needs more than a single shell command. Use the Claude SDK for the full flow. For the raw request shape of a tool conversation with search results, see [Combining both methods](https://platform.claude.com/docs/en/build-with-claude/search-results#combining-both-methods). To provide search results directly in user messages, see [Method 2: Search results as top-level content](https://platform.claude.com/docs/en/build-with-claude/search-results#method-2-search-results-as-top-level-content).
8383 </CodeGroupItem>
8484 
8585 ```python Python
from line 1124
11241124 client = Anthropic::Client.new
11251125 
11261126 message = client.messages.create(
1127 model: "claude-opus-5-5",
1127 model: Anthropic::Model::CLAUDE_OPUS_5_5,
11281128 max_tokens: 1024,
11291129 messages: [
11301130 {
from line 1924
19241924 # Replay a conversation that provides search results both ways: the first
19251925 # user message carries a pre-fetched result, the tool result returns another
19261926 response = client.messages.create(
1927 model: "claude-opus-5-5",
1927 model: Anthropic::Model::CLAUDE_OPUS_5_5,
19281928 max_tokens: 1024,
19291929 tools: [knowledge_base_tool],
19301930 messages: [
from line 2095
20952095### For top-level search (Method 2)
20962096 
20972097* **Pre-fetched content:** Use when you already have search results
2098* **Batch processing:** Ideal for processing multiple search results at once
2099* **Testing:** Great for testing citation behavior with known content
2098* **Batch processing:** Use for processing multiple search results at once
2099* **Testing:** Use for testing citation behavior with known content
21002100 
21012101### General best practices
21022102 

build-with-claude/skills-guide Changed · +19 / -19 lines

from line 9
99<Note>
1010 For complete API reference including request/response schemas and all parameters, see:
1111 
12 * [Skill Management API Reference](https://platform.claude.com/docs/en/api/skills/list) - CRUD operations for Skills
13 * [Skill Versions API Reference](https://platform.claude.com/docs/en/api/skills/versions/list) - Version management
12 * [Skill management API reference](https://platform.claude.com/docs/en/api/skills/list) - CRUD operations for Skills
13 * [Skill versions API reference](https://platform.claude.com/docs/en/api/skills/versions/list) - Version management
1414</Note>
1515 
1616<Note>
from line 1237
12371237 
12381238### Long-running operations
12391239 
1240Skills may perform operations that require multiple turns. Handle `pause_turn` stop reasons:
1240Skills might perform operations that require multiple turns. Handle `pause_turn` stop reasons:
12411241 
12421242<CodeGroup exclude="shell:cURL, shell:CLI">
12431243 <CodeGroupItem language="cURL">
from line 1623
16231623</CodeGroup>
16241624 
16251625<Note>
1626 The response may include a `pause_turn` stop reason, which indicates that the API paused a long-running Skill operation. You can provide the response back as-is in a subsequent request to let Claude continue its turn, or modify the content if you want to interrupt the conversation and provide additional guidance.
1626 The response might include a `pause_turn` stop reason, which indicates that the API paused a long-running Skill operation. You can provide the response back as-is in a subsequent request to let Claude continue its turn, or modify the content if you want to interrupt the conversation and provide additional guidance.
16271627</Note>
16281628 
16291629### Using multiple Skills
from line 1952
19521952## Managing custom Skills
19531953 
19541954<Warning id="workspace-scoped-access">
1955 **Custom Skills are accessible to your entire workspace, not scoped to an end user, conversation, or session.** Any API key with access to a workspace can read, invoke, and delete every custom Skill uploaded to that workspace. Every service account, and every user whose organization role allows API access, can use the Default Workspace in addition to any workspace you add them to, so keep Skills that must stay separate in their own [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#api-keys-and-resource-scoping) and access them only with keys scoped to that workspace.
1955 **Custom Skills are accessible to your entire workspace, not scoped to an end user, conversation, or session.** Any API key with access to a workspace can read, use, and delete every custom Skill uploaded to that workspace. Every service account, and every user whose organization role allows API access, can use the Default Workspace in addition to any workspace you add them to, so keep Skills that must stay separate in their own workspace and access them only with [keys scoped to that workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#api-keys-and-resource-scoping).
19561956 
1957 If you are building a multi-tenant platform on the Skills API, create a separate [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) for each tenant. The workspace is the isolation boundary for custom Skills, so a workspace per tenant gives each tenant's Skills hard isolation from every other tenant. Each organization can have up to 100 workspaces by default (see [How workspaces work](https://platform.claude.com/docs/en/manage-claude/workspaces#how-workspaces-work)); if you need more for tenant isolation, contact your account team.
1957 If you are building a multitenant platform on the Skills API, create a separate [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) for each tenant. The workspace is the isolation boundary for custom Skills, so a workspace for each tenant gives that tenant's Skills hard isolation from every other tenant. Each organization can have up to 100 workspaces by default (see [How workspaces work](https://platform.claude.com/docs/en/manage-claude/workspaces#how-workspaces-work)); if you need more for tenant isolation, contact your account team.
19581958</Warning>
19591959 
19601960### Creating a Skill
from line 1963
19631963 
19641964Upload your custom Skill to make it available in your workspace. You can upload a zip archive or individual file objects. The Python SDK also provides a `files_from_dir` helper that accepts a directory path, and the CLI's `ant apply` uploads the directory itself.
19651965 
1966Files are identified by the filename you attach (the `;filename=` suffix in the cURL example and the filename arguments in the SDK examples). For the walkthrough's skill, create a zip with `zip -r financial_skill.zip financial_skill/` and substitute it for the `example_skill.zip` placeholder in the zip-upload options.
1966Files are identified by the file name you attach (the `;filename=` suffix in the cURL example and the file name arguments in the SDK examples). For the walkthrough's skill, create a zip with `zip -r financial_skill.zip financial_skill/` and substitute it for the `example_skill.zip` placeholder in the zip-upload options.
19671967 
19681968<CodeGroup defaultLanguage="CLI">
19691969 ```bash cURL
from line 2261
22612261* YAML frontmatter requirements:
22622262 
22632263 * `name`: Maximum 64 characters, lowercase letters/numbers/hyphens only, no XML tags, no reserved words ("anthropic", "claude")
2264 * `description`: Maximum 1024 characters, non-empty, no XML tags
2264 * `description`: Maximum 1,024 characters, non-empty, no XML tags
22652265 
2266For complete request/response schemas, see the [Create Skill API reference](https://platform.claude.com/docs/en/api/skills/create).
2266For complete request/response schemas, see the [Create Skill](https://platform.claude.com/docs/en/api/skills/create) API reference.
22672267 
22682268### Listing Skills
22692269 
from line 3116
31163116 
31173117When you specify Skills in a container:
31183118 
31191. **Metadata discovery:** Claude sees metadata for each Skill (name, description) in the system prompt.
31191. **Metadata discovery:** Claude receives metadata for each Skill (name, description) in the system prompt.
312031202. **File loading:** Skill files are copied into the container at `/skills/{skill-name}/`. The directory is the Skill's name (`pptx` for an Anthropic Skill, the `SKILL.md` `name` for a custom Skill), not its `skill_01...` ID.
312131213. **Automatic use:** Claude automatically loads and uses Skills when relevant to your request.
312231224. **Composition:** Multiple Skills compose together for complex workflows.
from line 3550
35503550* **YAML frontmatter requirements:**
35513551 
35523552 * `name`: Maximum 64 characters, lowercase letters/numbers/hyphens only, no XML tags, no reserved words ("anthropic", "claude")
3553 * `description`: Maximum 1024 characters, non-empty, no XML tags
3553 * `description`: Maximum 1,024 characters, non-empty, no XML tags
35543554 
35553555### Environment constraints
35563556 
from line 3584
35843584 
35853585The SDK tabs in this section show the `container` value to include in a Messages request. The cURL and CLI tabs show the full request.
35863586 
3587**For production:** pin a specific version, so Skill updates never change your deployed behavior. If you omit `version` or set it to `"latest"`, requests use the newest version of the Skill, so a version uploaded by anyone in the [workspace](https://platform.claude.com/docs/en/build-with-claude/skills-guide#workspace-scoped-access) immediately changes what your production agents run. The version ID comes from the create-version response in [Versioning](https://platform.claude.com/docs/en/build-with-claude/skills-guide#versioning) or from the [List Skill Versions API](https://platform.claude.com/docs/en/api/skills/versions/list). The ID is always a string, so quote it in JSON or YAML even when it looks numeric.
3587**For production:** pin a specific version, so Skill updates never change your deployed behavior. If you omit `version` or set it to `"latest"`, requests use the newest version of the Skill, so a version uploaded by [anyone in the workspace](https://platform.claude.com/docs/en/build-with-claude/skills-guide#workspace-scoped-access) immediately changes what your production agents run. The version ID comes from the create-version response in [Versioning](https://platform.claude.com/docs/en/build-with-claude/skills-guide#versioning) or from the [List Skill Versions API](https://platform.claude.com/docs/en/api/skills/versions/list). The ID is always a string, so quote it in JSON or YAML even when it looks numeric.
35883588 
35893589<CodeGroup>
35903590 ```bash cURL
from line 4522
45224522 
45234523To migrate:
45244524 
45251. **Remove the beta header.** Drop `anthropic-beta: skills-2025-10-02` from your requests. In the SDKs, call `client.skills` instead of `client.beta.skills`; keeping `client.beta.skills` works only on the [SDK releases that no longer send the header](https://platform.claude.com/docs/en/build-with-claude/skills-guide#sdk-beta-namespace). Earlier releases send it from `client.beta.skills` even with no `betas` argument.
45251. **Remove the beta header.** Drop `anthropic-beta: skills-2025-10-02` from your requests. With the SDK, call `client.skills` (csharp, go: `client.Skills`; java: `client.skills()`; php: `$client->skills`) instead of `client.beta.skills` (csharp, go: `client.Beta.Skills`; java: `client.beta().skills()`; php: `$client->beta->skills`); keeping `client.beta.skills` (csharp, go: `client.Beta.Skills`; java: `client.beta().skills()`; php: `$client->beta->skills`) works only on the [SDK releases that no longer send the header](https://platform.claude.com/docs/en/build-with-claude/skills-guide#sdk-beta-namespace). Earlier releases send it from `client.beta.skills` (csharp, go: `client.Beta.Skills`; java: `client.beta().skills()`; php: `$client->beta->skills`) even when you pass no beta names.
452645262. **Rename fields** in your code: `display_title` to `display_name`, `latest_version` to `latest_version_id`, and read `source.type` instead of comparing `source` to a string.
452745273. **Use version IDs.** Wherever you stored an epoch-microsecond version, store the version's `id` instead, or use `latest`. Skill references in Messages requests accept a version ID, `latest`, or (for Anthropic Skills) the catalog version.
45284. **Review delete calls.** `DELETE /v1/skills/{skill_id}` now removes every version with the Skill. If you relied on the beta's refusal as a safeguard, add your own check.
45284. **Review delete calls.** `DELETE /v1/skills/{skill_id}` now deletes every version with the Skill. If you relied on the beta's refusal as a safeguard, add your own check.
45294529 
45304530<Warning>
4531 After migrating, `client.skills.delete(skill_id)` and `client.beta.skills.delete(skill_id)` delete the Skill together with all of its versions in one call.
4531 After migrating, deleting a Skill through `client.skills` (csharp, go: `client.Skills`; java: `client.skills()`; php: `$client->skills`) or `client.beta.skills` (csharp, go: `client.Beta.Skills`; java: `client.beta().skills()`; php: `$client->beta->skills`) removes the Skill together with all of its versions in one call.
45324532</Warning>
45334533 
45344534A Skill whose versions were all deleted under the beta has no current version to return: `GET /v1/skills/{skill_id}` returns a 400 error and the Skill is omitted from list responses until you upload a version to it. You can still delete it.
from line 4535
45354535 
45364536### SDK beta namespace
45374537 
4538Starting with Python SDK 1.2.0, TypeScript SDK 0.122.0, Go SDK 1.68.0, Java SDK 2.59.0, Ruby SDK 1.67.0, and C# SDK 12.44.0, `client.beta.skills` no longer sends `skills-2025-10-02` and returns the same shapes as `client.skills`, with `Beta`-prefixed type names (`BetaSkill`, `BetaSkillVersion`, `BetaDeletedSkill`, `BetaDeletedSkillVersion`). It accepts a `betas` argument for Skills features that are still in beta. In the beta Messages types, the container Skill reference type is renamed from `BetaSkill` to `BetaContainerSkill` (same fields: `type`, `skill_id`, `version`); `BetaSkill` now names the Skill resource, matching `Skill` and `ContainerSkill` in the non-beta types. Earlier SDK releases are typed to the beta shapes; if you depend on those types, stay on an earlier release until you migrate.
4538Starting with Python SDK 1.2.0, TypeScript SDK 0.122.0, Go SDK 1.68.0, Java SDK 2.59.0, PHP SDK 0.45.0, Ruby SDK 1.67.0, and C# SDK 12.44.0, `client.beta.skills` (csharp, go: `client.Beta.Skills`; java: `client.beta().skills()`; php: `$client->beta->skills`) no longer sends `skills-2025-10-02` and returns the same shapes as `client.skills` (csharp, go: `client.Skills`; java: `client.skills()`; php: `$client->skills`), with beta type names (`BetaSkill`, `BetaSkillVersion` (php: `SkillVersion`), `BetaDeletedSkill`, `BetaDeletedSkillVersion` (php: `DeletedSkillVersion`)). It takes beta names through `betas` (csharp, go: `Betas`; java: `.addBeta()`) for Skills features that are in beta. In the beta Messages types, the container Skill reference type is renamed from `BetaSkill` to `BetaContainerSkill` (same fields: `type`, `skill_id`, `version`); `BetaSkill` now names the Skill resource, matching `Skill` and `ContainerSkill` in the non-beta types. Earlier SDK releases are typed to the beta shapes; if you depend on those types, stay on an earlier release until you migrate.
45394539 
45404540## Data retention
45414541 
from line 4559
45594559 </Card>
45604560 
45614561 <Card title="Code execution tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">
4562 Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
4562 Run Python and Bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
45634563 </Card>
45644564</CardGroup>
45654565 

build-with-claude/streaming Changed · +39 / -39 lines

from line 284
284284 ```
285285</CodeGroup>
286286 
287The `.stream()` (java: `.createStreaming()`; csharp: `.CreateStreaming()`; go: `.NewStreaming()`; php: `->createStream()`) call keeps the HTTP connection alive with server-sent events, then the SDK's message-accumulation helper, `stream.get_final_message()` (typescript: `stream.finalMessage()`; ruby: `stream.accumulated_message`; csharp: `.Aggregate()`; go: `message.Accumulate(event)`; java, php: `MessageAccumulator`), collects all events into the complete `Message` object.
287The `.stream()` (java: `.createStreaming()`; csharp: `.CreateStreaming()`; go: `.NewStreaming()`; php: `->createStream()`) call keeps the HTTP connection alive with server-sent events, and then the SDK's message-accumulation helper, `stream.get_final_message()` (typescript: `stream.finalMessage()`; ruby: `stream.accumulated_message`; csharp: `.Aggregate()`; go: `message.Accumulate(event)`; java, php: `MessageAccumulator`), collects all events into the complete `Message` object.
288288 
289289## Event types
290290 
from line 303
303303 
304304### Ping events
305305 
306Event streams may also include any number of `ping` events.
306Event streams might also include any number of `ping` events.
307307 
308308### Error events
309309 
310The API may occasionally send [errors](https://platform.claude.com/docs/en/api/errors) in the event stream. For example, during periods of high usage, you may receive an `overloaded_error`, which would normally correspond to an HTTP 529 in a non-streaming context:
310The API might occasionally send [errors](https://platform.claude.com/docs/en/api/errors) in the event stream. For example, during periods of high usage, you might receive an `overloaded_error`, which would normally correspond to an HTTP 529 in a non-streaming context:
311311 
312312```sse Example error
313313event: error
from line 335
335335 
336336The deltas for `tool_use` content blocks correspond to updates for the `input` field of the block. To support maximum granularity, the deltas are *partial JSON strings*, whereas the final `tool_use.input` is always an *object*.
337337 
338You can accumulate the string deltas and parse the JSON once you receive a `content_block_stop` event, by using a library like [Pydantic](https://docs.pydantic.dev/latest/concepts/json/#partial-json-parsing) to do partial JSON parsing, or by using the SDK's [streaming helpers](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks). In the Python and TypeScript SDKs, these helpers also give you access to the parsed `input` incrementally, as it streams.
338You can accumulate the string deltas and parse the JSON once you receive a `content_block_stop` event, by using a library such as [Pydantic](https://docs.pydantic.dev/latest/concepts/json/#partial-json-parsing) to do partial JSON parsing, or by using the SDK's [streaming helpers](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks). In the Python and TypeScript SDKs, these helpers also give you access to the parsed `input` incrementally, as it streams.
339339 
340340A `tool_use` content block delta looks like:
341341 
from line 344
344344data: {"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}
345345```
346346 
347Note: Current models only support emitting one complete key and value property from `input` at a time. As such, when using tools, there may be delays between streaming events while the model is working. Once an `input` key and value are accumulated, they are emitted as multiple `content_block_delta` events with chunked partial JSON so that the format can automatically support finer granularity in future models.
347Note: Current models only support emitting one complete key and value property from `input` at a time. As such, when using tools, there might be delays between streaming events while the model is working. Once an `input` key and value are accumulated, they are emitted as multiple `content_block_delta` events with chunked partial JSON so that the format can automatically support finer granularity in future models.
348348 
349349### Thinking delta
350350 
from line 386
386386 
3873874. A `message_stop` event
388388 
389There may be `ping` events dispersed throughout the response as well. See [Event types](https://platform.claude.com/docs/en/build-with-claude/streaming#event-types) for more details on the format.
389There might be `ping` events dispersed throughout the response as well. See [Event types](https://platform.claude.com/docs/en/build-with-claude/streaming#event-types) for more details on the format.
390390 
391391### Basic streaming request
392392 
from line 560
560560### Streaming request with tool use
561561 
562562<Tip>
563 Tool use supports [fine-grained streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) for parameter values. Enable it per tool with `eager_input_streaming`.
563 Tool use supports [fine-grained streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) for parameter values. Enable it on individual tools with `eager_input_streaming`.
564564</Tip>
565565 
566566This request asks Claude to use a tool to report the weather.
from line 567
567567 
568568<CodeGroup>
569569 ```bash cURL
570 curl https://api.anthropic.com/v1/messages \
571 -H "content-type: application/json" \
572 -H "x-api-key: $ANTHROPIC_API_KEY" \
573 -H "anthropic-version: 2023-06-01" \
574 -d '{
575 "model": "claude-opus-5",
576 "max_tokens": 1024,
577 "tools": [
578 {
579 "name": "get_weather",
580 "description": "Get the current weather in a given location",
581 "input_schema": {
582 "type": "object",
583 "properties": {
584 "location": {
585 "type": "string",
586 "description": "The city and state, e.g. San Francisco, CA"
587 }
588 },
589 "required": ["location"]
590 }
570 curl https://api.anthropic.com/v1/messages \
571 -H "content-type: application/json" \
572 -H "x-api-key: $ANTHROPIC_API_KEY" \
573 -H "anthropic-version: 2023-06-01" \
574 -d '{
575 "model": "claude-opus-5",
576 "max_tokens": 1024,
577 "tools": [
578 {
579 "name": "get_weather",
580 "description": "Get the current weather in a given location",
581 "input_schema": {
582 "type": "object",
583 "properties": {
584 "location": {
585 "type": "string",
586 "description": "The city and state, e.g. San Francisco, CA"
587 }
588 },
589 "required": ["location"]
591590 }
592 ],
593 "tool_choice": {"type": "any"},
594 "messages": [
595 {
596 "role": "user",
597 "content": "What is the weather like in San Francisco?"
598 }
599 ],
600 "stream": true
601 }'
591 }
592 ],
593 "tool_choice": {"type": "any"},
594 "messages": [
595 {
596 "role": "user",
597 "content": "What is the weather like in San Francisco?"
598 }
599 ],
600 "stream": true
601 }'
602602 ```
603603 
604604 ```bash CLI
from line 1503
15031503 
15041504### Error recovery best practices
15051505 
15061. **Use SDK features:** Leverage the SDK's built-in message accumulation and error handling capabilities.
15061. **Use SDK features:** Rely on the SDK's built-in message accumulation and error handling capabilities.
150715072. **Handle content types:** Be aware that messages can contain multiple content blocks (`text`, `tool_use`, `thinking`). Tool use and thinking blocks cannot be partially recovered. You can resume streaming from the most recent text block.
15081508 
15091509## Next steps

build-with-claude/structured-outputs Changed · +58 / -54 lines

from line 42
4242 
4343## Why use structured outputs
4444 
45Without structured outputs, Claude can generate malformed JSON responses or invalid tool inputs that break your applications. Even with careful prompting, you may encounter:
45Without structured outputs, Claude can generate malformed JSON responses or invalid tool inputs that break your applications. Even with careful prompting, you might encounter:
4646 
4747* Parsing errors from invalid JSON syntax
4848* Missing required fields
from line 194
194194 
195195 Pass a [Pydantic](https://docs.pydantic.dev/) model to `client.messages.parse()`, the recommended method, as `output_format`. The SDK transforms the model's schema, sends it as `output_config.format`, validates the response, and returns the parsed model in `parsed_output`.
196196 
197 The example above outputs:
197 The previous example outputs:
198198 
199199 ```text Output wrap
200200 name='John Smith' email='[email protected]' plan_interest='Enterprise' demo_requested=True
from line 236
236236 
237237 Wrap a [Zod](https://zod.dev/) schema in `zodOutputFormat()` and pass it to `client.messages.parse()` as `output_config.format`. `zodOutputFormat()` transforms the schema, and `parse()` validates the response and returns the parsed result in `parsed_output`, typed to match the schema.
238238 
239 The example above outputs:
239 The previous example outputs:
240240 
241241 ```javascript Output
242242 {
from line 283
283283 
284284 Pass a plain C# class or record to the generic `Create<T>()` overload. The SDK derives a JSON schema from the type, transforms it, and parses each text block back into it.
285285 
286 The example above outputs:
286 The previous example outputs:
287287 
288288 ```text Output wrap
289289 ContactInfo { Name = John Smith, Email = [email protected], PlanInterest = Enterprise, DemoRequested = True }
from line 331
331331 
332332 The SDK generates and transforms the JSON schema from the struct and unmarshals the response into it.
333333 
334 The example above outputs:
334 The previous example outputs:
335335 
336336 ```text Output wrap
337337 main.ContactInfo{Name:"John Smith", Email:"[email protected]", PlanInterest:"Enterprise", DemoRequested:true}
from line 369
369369 
370370 When you pass a Java class to `outputConfig()`, the SDK derives a JSON schema from it and validates the schema. The builder then produces a `StructuredMessageCreateParams<T>`. Rather than transforming the schema, the SDK's local validation rejects [constraints not supported by the API](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations). Read the parsed result with `response.content().stream().flatMap(block -> block.text().stream()).findFirst().orElseThrow().text()`.
371371 
372 The example above outputs:
372 The previous example outputs:
373373 
374374 ```text Output wrap
375375 {"name":"John Smith","email":"[email protected]","plan_interest":"Enterprise","demo_requested":true}
from line 380
380380 </Note>
381381 
382382 <Accordion title="Generic type erasure">
383 Java retains generic type information for fields in the class's metadata, but generic type erasure applies in other scopes. While a JSON schema can be derived from a `BookList.books` field with type `List<Book>`, a valid JSON schema cannot be derived from a local variable of that same type.
383 Java retains generic type information for fields in the class's metadata, but generic type erasure applies in other scopes. Although a JSON schema can be derived from a `BookList.books` field with type `List<Book>`, a valid JSON schema cannot be derived from a local variable of that same type.
384384 
385 If an error occurs while converting a JSON response to a Java class instance, the error message includes the JSON response to assist in diagnosis. If your JSON response may contain sensitive information, avoid logging it directly, or ensure that you redact any sensitive details from the error message.
385 If an error occurs while converting a JSON response to a Java class instance, the error message includes the JSON response to help with diagnosis. If your JSON response might contain sensitive information, avoid logging it directly, or ensure that you redact any sensitive details from the error message.
386386 </Accordion>
387387 
388388 <Accordion title="Local schema validation">
from line 392
392392 
393393 * **Local validation** occurs without sending requests to the remote AI model.
394394 * **Remote validation** is also performed by the AI model upon receiving the JSON schema.
395 * **Version compatibility:** Local validation may fail while remote validation succeeds if the SDK version is outdated.
395 * **Version compatibility:** Local validation might fail while remote validation succeeds if the SDK version is outdated.
396396 * **Disabling local validation:** Pass `JsonSchemaLocalValidation.NO` if you encounter compatibility issues:
397397 
398398 ```java
from line 425
425425 
426426 You can control visibility with annotations:
427427 
428 * `@JsonIgnore` excludes a `public` field or getter method
429 * `@JsonProperty` includes a non-`public` field or getter method
428 * `@JsonIgnore` excludes a `public` field or getter method.
429 * `@JsonProperty` includes a non-`public` field or getter method.
430430 
431431 If you define `private` fields with `public` getter methods, the SDK derives the property name from the getter (for example, `private` field `myValue` with `public` method `getMyValue()` produces a `"myValue"` property). To use a non-conventional getter name, annotate the method with `@JsonProperty`.
432432 
from line 555
555555 }
556556 ```
557557 
558 Local validation checks that you haven't used any unsupported constraint keywords, but constraint values aren't validated locally. For example, an unsupported `"format"` value may pass local validation but cause a remote error.
558 Local validation checks that you haven't used any unsupported constraint keywords, but constraint values aren't validated locally. For example, an unsupported `"format"` value might pass local validation but cause a remote error.
559559 
560560 If you use both Jackson and Swagger annotations to set the same schema field, the Jackson annotation takes precedence.
561561 </Accordion>
from line 602
602602 
603603 `parsedOutput()` returns your model instance on success, or `null` (or an error array) if parsing fails. Use `instanceof` to narrow the type before accessing fields.
604604 
605 The example above outputs:
605 The previous example outputs:
606606 
607607 ```text Output wrap
608608 object(ContactInfo)#42 (4) {
from line 695
695695 
696696 Define a class that extends `Anthropic::BaseModel` and pass it to `messages.create()` as `output_config: {format: Model}`. The SDK derives a JSON schema from the class, transforms it, and assigns the parsed result to the response's `parsed_output` attribute as a typed Ruby object.
697697 
698 The example above outputs:
698 The previous example outputs:
699699 
700700 ```text Output wrap
701701 {name: "John Smith", email: "[email protected]", plan_interest: "Enterprise", demo_requested: true}
from line 740
7407401. **Remove unsupported constraints** (for example, `minimum`, `maximum`, `minLength`, `maxLength`)
7417412. **Update descriptions** by adding each unsupported constraint to the field's description (for example, `{minimum: 100}`)
7427423. **Add `additionalProperties: false`** to all objects
7434. **Filter string formats** to supported list only
7434. **Filter string formats** to the supported list only
7447445. **Validate responses** against your original schema and all its constraints, if the helper validates responses
745745 
746746Claude receives a simplified schema, but a helper that validates responses still enforces every constraint in your code.
from line 875
875875 print(contact)
876876 ```
877877 
878 The example above outputs:
878 The previous example outputs:
879879 
880880 ```text Output wrap
881881 {'name': 'John Smith', 'email': '[email protected]', 'plan_interest': 'Enterprise', 'demo_requested': True}
from line 917
917917 console.log(response.parsed_output);
918918 ```
919919 
920 Use `jsonSchemaOutputFormat()` to pass a plain JSON schema to `parse()`, without installing Zod. The API returns a response that conforms to the schema, and if you declare the schema with `as const`, the type for `parsed_output` is automatically inferred by TypeScript according to your schema. For an imported or generated schema, `parsed_output` is typed as `unknown`.
920 Use `jsonSchemaOutputFormat()` to pass a plain JSON schema to `parse()`, without installing Zod. The API returns a response that conforms to the schema, and if you declare the schema with `as const`, TypeScript automatically infers the type for `parsed_output` according to your schema. For an imported or generated schema, `parsed_output` is typed as `unknown`.
921921 
922 By default, the helper [transforms the schema](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#how-sdk-transformation-works) the same way `zodOutputFormat()` does. Pass `{ transform: false }` as the second argument to send it unchanged. Unlike `zodOutputFormat()`, it doesn't validate the response, so it won't catch violations of [constraints not supported by the API](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations), such as `minimum`.
922 By default, the helper [transforms the schema](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#how-sdk-transformation-works) the same way `zodOutputFormat()` does. Pass `{ transform: false }` as the second argument to send it unchanged. Unlike `zodOutputFormat()`, it doesn't validate the response, so it doesn't catch violations of [constraints not supported by the API](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations), such as `minimum`.
923923 
924 The example above outputs:
924 The previous example outputs:
925925 
926926 ```javascript Output
927927 { name: 'John Smith', email: '[email protected]', planInterest: 'Pro' }
from line 1032
10321032 }
10331033 ```
10341034 
1035 The example above outputs:
1035 The previous example outputs:
10361036 
10371037 ```text Output wrap
10381038 main.ContactInfo{Name:"John Smith", Email:"[email protected]", PlanInterest:"Enterprise", DemoRequested:true}
from line 1087
10871087 }
10881088 ```
10891089 
1090 The example above outputs:
1090 The previous example outputs:
10911091 
10921092 ```text Output wrap
10931093 {"name":"John Smith","email":"[email protected]","plan_interest":"Enterprise"}
from line 1132
11321132 
11331133 Pass the schema as an associative array to `OutputConfig::with()`, and decode the response with `json_decode()`.
11341134 
1135 The example above outputs:
1135 The previous example outputs:
11361136 
11371137 ```text Output wrap
11381138 array(3) {
from line 1184
11841184 p contact
11851185 ```
11861186 
1187 The example above outputs:
1187 The previous example outputs:
11881188 
11891189 ```text Output wrap
11901190 {"name" => "John Smith", "email" => "[email protected]", "plan_interest" => "Enterprise", "demo_requested" => true}
from line 2160
21602160 
21612161JSON outputs and strict tool use solve different problems and work together:
21622162 
2163* **JSON outputs** control Claude's response format (what Claude says)
2164* **Strict tool use** validates tool parameters (how Claude calls your functions)
2163* **JSON outputs** control Claude's response format (what Claude says).
2164* **Strict tool use** validates tool parameters (how Claude calls your functions).
21652165 
21662166When combined, Claude can call tools with guaranteed-valid parameters AND return structured JSON responses. This is useful for agentic workflows where you need both reliable tool calls and structured final outputs.
21672167 
from line 2252
22522252 ```
22532253 
22542254 ```python Python
2255 client = anthropic.Anthropic()
2256 
22552257 response = client.messages.create(
22562258 model="claude-opus-5-5",
22572259 max_tokens=1024,
from line 2300
22982300 ```
22992301 
23002302 ```typescript TypeScript
2303 const client = new Anthropic();
2304 
23012305 const response = await client.messages.create({
23022306 model: "claude-opus-5-5",
23032307 max_tokens: 1024,
from line 2593
25892593 
25902594Structured outputs use constrained sampling with compiled grammar artifacts. This introduces some performance characteristics to be aware of:
25912595 
2592* **First request latency:** The first time you use a specific schema, there is additional latency while the grammar compiles
2596* **First request latency:** The first time you use a specific schema, there is additional latency while the grammar compiles.
25932597 
2594* **Automatic caching:** Compiled grammars are cached for 24 hours from last use, making subsequent requests much faster
2598* **Automatic caching:** Compiled grammars are cached for 24 hours from last use, making subsequent requests much faster.
25952599 
25962600* **Cache invalidation:** The cache is invalidated if you change:
25972601 
from line 2607
26032607 
26042608When using structured outputs, Claude automatically receives an additional system prompt explaining the expected output format. This means:
26052609 
2606* Your input token count is slightly higher
2607* The injected prompt costs you tokens like any other system prompt
2608* Changing the `output_config.format` parameter will invalidate any [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for that conversation thread
2610* Your input token count is slightly higher.
2611* The injected prompt costs you tokens like any other system prompt.
2612* Changing the `output_config.format` parameter will invalidate any [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for that conversation thread.
26092613 
26102614### JSON Schema limitations
26112615 
from line 2617
26132617 
26142618<Accordion title="Supported features">
26152619 * All basic types: object, array, string, integer, number, boolean, null
2616 * `enum` (strings, numbers, bools, or nulls only - no complex types). For a capitalization caveat, see [Invalid outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#invalid-outputs).
2620 * `enum` (strings, numbers, Booleans, or nulls only, no complex types). For a capitalization caveat, see [Invalid outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#invalid-outputs).
26172621 * `const`
2618 * `anyOf` and `allOf` (with limitations - `allOf` with `$ref` not supported)
2622 * `anyOf` and `allOf` (with limitations: `allOf` with `$ref` not supported)
26192623 * `$ref`, `$def`, and `definitions` (external `$ref` not supported)
26202624 * `default` property for all supported types
26212625 * `required` and `additionalProperties` (must be set to `false` for objects)
from line 2654
26502654 * Word boundaries: `\b`, `\B`
26512655 * Complex `{n,m}` quantifiers with large ranges
26522656 
2653 Simple regex patterns work well. Complex patterns may result in 400 errors.
2657 Simple regex patterns work well. Complex patterns might result in 400 errors.
26542658</Accordion>
26552659 
26562660<Tip>
from line 2703
26992703 
27002704### Invalid outputs
27012705 
2702While structured outputs guarantee schema compliance in most cases, there are scenarios where the output may not match your schema:
2706Although structured outputs guarantee schema compliance in most cases, there are scenarios where the output might not match your schema:
27032707 
27042708**Refusals** (`stop_reason: "refusal"`)
27052709 
from line 2712
27082712* The response has `stop_reason: "refusal"`
27092713* You'll receive a 200 status code
27102714* You'll be billed for the tokens generated
2711* The output may not match your schema because the refusal message takes precedence over schema constraints
2715* The output might not match your schema because the refusal message takes precedence over schema constraints
27122716 
2713A property that asks for the model's thinking or step-by-step reasoning may lead to a `reasoning_extraction` refusal. Ask for a short explanation instead. See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
2717A property that asks for the model's thinking or step-by-step reasoning might lead to a `reasoning_extraction` refusal. Ask for a short explanation instead. See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
27142718 
27152719**Token limit reached** (`stop_reason: "max_tokens"`)
27162720 
2717If the response is cut off due to reaching the `max_tokens` limit:
2721If the response is cut off because it reached the `max_tokens` limit:
27182722 
27192723* The response has `stop_reason: "max_tokens"`
2720* The output may be incomplete and not match your schema
2724* The output might be incomplete and not match your schema
27212725* Retry with a higher `max_tokens` value to get the complete structured output
27222726 
27232727**Enum value casing**
27242728 
2725Structured outputs don't guarantee the capitalization of string `enum` and `const` values: Claude may return a value that differs from your schema only in capitalization, typically in the first letter of a word following a space. For example, given this schema:
2729Structured outputs don't guarantee the capitalization of string `enum` and `const` values: Claude might return a value that differs from your schema only in capitalization, typically in the first letter of a word following a space. For example, given this schema:
27262730 
27272731```json
27282732{
from line 2735
27312735}
27322736```
27332737 
2734The output may contain `"Conversation Topic 3"` (capital "T") even though that exact value isn't in the enum. The response completes normally, with no error and no special `stop_reason`. This applies to both JSON outputs and strict tool use. Compare enum values case-insensitively, and avoid enum values that differ only in capitalization.
2738The output might contain `"Conversation Topic 3"` (capital "T") even though that exact value isn't in the enum. The response completes normally, with no error and no special `stop_reason`. This applies to both JSON outputs and strict tool use. Compare enum values case-insensitively, and avoid enum values that differ only in capitalization.
27352739 
27362740### Schema complexity limits
27372741 
from line 2757
27532757 
27542758#### Additional internal limits
27552759 
2756Beyond the explicit limits in the preceding table, there are additional internal limits on the compiled grammar size. These limits exist because schema complexity doesn't reduce to a single dimension: features like optional parameters, union types, nested objects, and number of tools interact with each other in ways that can make the compiled grammar disproportionately large.
2760Beyond the explicit limits in the preceding table, there are additional internal limits on the compiled grammar size. These limits exist because schema complexity doesn't reduce to a single dimension: features such as optional parameters, union types, nested objects, and number of tools interact with each other in ways that can make the compiled grammar disproportionately large.
27572761 
2758When these limits are exceeded, you'll receive a 400 error with the message "Schema is too complex for compilation." These errors mean the combined complexity of your schemas exceeds what can be efficiently compiled, even if each individual limit in the preceding table is satisfied. As a final stop-gap, the API also enforces a **compilation timeout of 180 seconds**. Schemas that pass all explicit checks but produce very large compiled grammars may hit this timeout.
2762When these limits are exceeded, you'll receive a 400 error with the message "Schema is too complex for compilation." These errors mean the combined complexity of your schemas exceeds what can be efficiently compiled, even if each individual limit in the preceding table is satisfied. As a final stop-gap, the API also enforces a **compilation timeout of 180 seconds**. Schemas that pass all explicit checks but produce very large compiled grammars might hit this timeout.
27592763 
27602764#### Tips for reducing schema complexity
27612765 
27622766If you're hitting complexity limits, try these strategies in order:
27632767 
27641. **Mark only critical tools as strict.** If you have many tools, reserve it for tools where schema violations cause real problems, and rely on Claude's natural adherence for simpler tools.
27681. **Mark only critical tools as strict.** If you have many tools, reserve strict tool use for those where schema violations cause real problems, and rely on Claude's natural adherence for simpler tools.
27652769 
276627702. **Reduce optional parameters.** Make parameters `required` where possible. Each optional parameter roughly doubles a portion of the grammar's state space. If a parameter always has a reasonable default, consider making it required and having Claude provide that default explicitly.
27672771 
276827723. **Simplify nested structures.** Deeply nested objects with optional fields compound the complexity. Flatten structures where possible.
27692773 
27704. **Split into multiple requests.** If you have many strict tools, consider splitting them across separate requests or sub-agents.
27744. **Split into multiple requests.** If you have many strict tools, consider splitting them across separate requests or subagents.
27712775 
27722776For persistent issues with valid schemas, [contact support](https://support.claude.com/en/articles/9015913-how-to-get-support) with your schema definition.
27732777 
27742778## Migrating from the beta
27752779 
2776The `output_format` parameter has moved to `output_config.format`, and beta headers are no longer required. The `output_format` parameter is deprecated and will be removed in the future. To use it anyway, add the `structured-outputs-2025-11-13` beta header. Without it, the API returns a 400 error.
2780The `output_format` parameter has moved to `output_config.format`, and beta headers are no longer required. The `output_format` parameter is deprecated. To use it anyway, add the `structured-outputs-2025-11-13` beta header. Without it, the API returns a 400 error.
27772781 
27782782The Python SDK (v1.0 and later) does not accept `output_format={...}` on `client.beta.messages.create()` or `count_tokens()` and raises a `TypeError`. Use `output_config` instead. See [Using a raw JSON schema](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#using-a-raw-json-schema) for the updated API shape.
27792783 
from line 2793
27892793 
27902794**Works with:**
27912795 
2792* **[Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing):** Process structured outputs at scale with 50% discount
2796* **[Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing):** Process structured outputs at scale with a 50 percent discount
27932797* **[Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting):** Count tokens without compilation
27942798* **[Streaming](https://platform.claude.com/docs/en/build-with-claude/streaming):** Stream structured outputs like normal responses
27952799* **[Combined usage](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#using-both-features-together):** Use JSON outputs (`output_config.format`) and strict tool use (`strict: true`) together in the same request
from line 2801
27972801**Incompatible with:**
27982802 
27992803* **[Citations](https://platform.claude.com/docs/en/build-with-claude/citations):** Citations require interleaving citation blocks with text, which conflicts with strict JSON schema constraints. Returns 400 error if citations enabled with `output_config.format`.
2800* **Message Prefilling:** Incompatible with JSON outputs
2804* **Message prefilling:** Incompatible with JSON outputs
28012805 
28022806<Tip>
28032807 **Grammar scope:** Grammars apply only to Claude's direct output, not to tool use calls, tool results, or thinking tags (when using [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking)). Grammar state resets between sections, allowing Claude to think freely while still producing structured output in the final response.
from line 2819
28152819 </Card>
28162820 
28172821 <Card title="Tool use with Claude" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">
2818 Connect Claude to external tools and APIs. Learn where tools execute and how the agentic loop works.
2822 Connect Claude to external tools and APIs. Learn where tools run and how the agentic loop works.
28192823 </Card>
28202824 
28212825 <Card title="Pricing" icon="calculator" href="https://platform.claude.com/docs/en/about-claude/pricing">

build-with-claude/task-budgets Changed · +13 / -13 lines

from line 18
1818 - claude-haiku-5-5
1919---
2020 
21Task budgets let you tell Claude how many tokens it has for a full agentic loop, including thinking, tool calls, tool results, and output. The model sees a running countdown and uses it to prioritize work and finish gracefully as the budget is consumed.
21Task budgets let you tell Claude how many tokens it has for a full agentic loop, including thinking, tool calls, tool results, and output. The model receives a running countdown and uses it to prioritize work and finish gracefully as the budget is consumed.
2222 
2323## When to use task budgets
2424 
from line 28
2828* You have a predictable per-task cost or latency ceiling to enforce.
2929* You want the model to finish gracefully (summarize findings, report progress) as it approaches the budget rather than cutting off mid-action.
3030 
31Task budgets complement the [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort): effort controls how thoroughly Claude reasons about each step, while task budgets cap the total work Claude can do across an agentic loop.
31Task budgets complement the [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort): effort controls how thoroughly Claude reasons about each step, whereas task budgets cap the total work Claude can do across an agentic loop.
3232 
3333## Setting a task budget
3434 
from line 250
250250 
251251## How the budget countdown works
252252 
253Claude sees a budget-countdown marker injected server-side throughout the conversation. The marker shows how many tokens remain in the current agentic loop and updates as the model generates thinking, tool calls, and output, and as it processes tool results. Claude uses this signal to pace itself and finish gracefully as the budget is consumed.
253Claude receives a budget-countdown marker injected server-side throughout the conversation. The marker shows how many tokens remain in the current agentic loop and updates as the model generates thinking, tool calls, and output, and as it processes tool results. Claude uses this signal to pace itself and finish gracefully as the budget is consumed.
254254 
255255<Note>
256256 **The countdown is visible only to the model.** API responses do not include a remaining-budget field: there is no `task_budget` information in the response `usage` object, and the SDK has no accessor for it. To track spend client-side, sum token usage across the requests in your loop as shown in [Measure your current usage](https://platform.claude.com/docs/en/build-with-claude/task-budgets#measure-your-current-usage), or pass your own figure forward with `remaining` when [carrying a budget across compaction](https://platform.claude.com/docs/en/build-with-claude/task-budgets#carrying-a-budget-across-compaction-with-remaining).
from line 257
257257</Note>
258258 
259259<Warning>
260 **The countdown reflects tokens Claude has processed in the current agentic loop, not tokens you resend between requests.** If your client sends the full conversation history on every follow-up request, your client-side token count might differ from the budget Claude is tracking. If you also decrement `remaining` while resending full history, the model sees an under-reported budget and the countdown drops faster than it should, causing Claude to wrap up earlier than the budget actually allows. Set a generous budget and let the model self-regulate against the countdown rather than trying to mirror it client-side.
260 **The countdown reflects tokens Claude has processed in the current agentic loop, not tokens you resend between requests.** If your client sends the full conversation history on every follow-up request, your client-side token count might differ from the budget Claude is tracking. If you also decrement `remaining` while resending full history, the model receives an under-reported budget and the countdown drops faster than it should, causing Claude to finish earlier than the budget actually allows. Set a generous budget and let the model self-regulate against the countdown rather than trying to mirror it client-side.
261261</Warning>
262262 
263263### What counts as a turn
from line 293
293293}
294294```
295295 
296Server-side [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold) during a turn does not reset the budget: tokens the turn consumed before the compaction still count against it. Tokens from before the turn began do not count, even when a compaction at the start of a turn summarizes them. Today, that exclusion applies only to the budget carried across a server-side compaction; earlier turns' history still counts while it remains in the context.
296Server-side [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold) during a turn does not reset the budget: tokens the turn consumed before the compaction still count against it. Tokens from before the turn do not count, even when a compaction at the start of a turn summarizes them. Today, that exclusion applies only to the budget carried across a server-side compaction; earlier turns' history still counts while it remains in the context.
297297 
298298### Worked example: budget counting across requests
299299 
from line 331
331331}
332332```
333333 
334Suppose this assistant message (thinking plus the tool call) totals 5,000 generated tokens. The countdown Claude saw during generation ended near `remaining` ≈ 95,000.
334Suppose this assistant message (thinking plus the tool call) totals 5,000 generated tokens. The countdown Claude received during generation ended near `remaining` ≈ 95,000.
335335 
336336**Request 2.** Your client runs the tool, then resends the full history with the tool result appended:
337337 
from line 483
483483 ```
484484</CodeGroup>
485485 
486In this example, the tokens spent before compaction are the usage of all the messages you have removed from the history so far, measured as in [Measure your current usage](https://platform.claude.com/docs/en/build-with-claude/task-budgets#measure-your-current-usage). Leave out anything still present in the messages you send, including any summary you added, because the server counts those tokens itself. Update this figure only when you replace the history this way; don't decrement it per request. Pass the resulting `remaining` on every request, not only the one that compacts.
486In this example, the tokens spent before compaction are the usage of all the messages you have removed from the history so far, measured as in [Measure your current usage](https://platform.claude.com/docs/en/build-with-claude/task-budgets#measure-your-current-usage). Leave out anything still present in the messages you send, including any summary you added, because the server counts those tokens itself. Update this figure only when you replace the history this way; don't decrement it on each request. Pass the resulting `remaining` on every request, not only the one that compacts.
487487 
488488For loops that resend the full uncompacted history on every request, omit `remaining` and let the server track the countdown.
489489 
from line 493
493493 
494494## Task budgets are advisory, not enforced
495495 
496Task budgets are a **soft hint, not a hard cap**. Claude may occasionally exceed the budget if it is in the middle of an action that would be more disruptive to interrupt than to finish. The enforced limit on total output tokens is still `max_tokens`, which truncates the response with `stop_reason: "max_tokens"` when reached.
496Task budgets are a **soft hint, not a hard cap**. Claude might occasionally exceed the budget if it is in the middle of an action that would be more disruptive to interrupt than to complete. The enforced limit on total output tokens is still `max_tokens`, which truncates the response with `stop_reason: "max_tokens"` when reached.
497497 
498498For a hard cap on cost or latency, combine task budgets with a reasonable `max_tokens` value:
499499 
from line 500
500500* Use `task_budget` to give Claude a target to pace against.
501501* Use `max_tokens` as the absolute ceiling that prevents runaway generation.
502502 
503Because `task_budget` spans the full agentic loop (potentially many requests) while `max_tokens` caps each individual request, the two values are independent; one is not required to be at or below the other.
503Because `task_budget` spans the full agentic loop (potentially many requests) whereas `max_tokens` caps each individual request, the two values are independent; one is not required to be at or below the other.
504504 
505505<Warning>
506 **A budget that is too small for the task can cause refusal-like behavior.** When Claude sees a budget that is clearly insufficient for the work being asked (for example, a 20,000-token budget for a multihour agentic coding task), it may decline to attempt the task at all, scope it down aggressively, or stop early with a partial result rather than start work it cannot finish. If you observe unexpected refusals or premature stops after setting a budget, raise the budget before debugging other parameters. Size budgets against your actual task-length distribution rather than a fixed default; see [Choosing a budget](https://platform.claude.com/docs/en/build-with-claude/task-budgets#choosing-a-budget).
506 **A budget that is too small for the task can cause refusal-like behavior.** When Claude sees a budget that is clearly insufficient for the work being asked (for example, a 20,000-token budget for a multihour agentic coding task), it might decline to attempt the task at all, scope it down aggressively, or stop early with a partial result rather than start work it cannot complete. If you observe unexpected refusals or premature stops after setting a budget, raise the budget before debugging other parameters. Size budgets against your actual task-length distribution rather than a fixed default; see [Choosing a budget](https://platform.claude.com/docs/en/build-with-claude/task-budgets#choosing-a-budget).
507507</Warning>
508508 
509509## Choosing a budget
from line 512
512512 
513513### Measure your current usage
514514 
515Run a representative sample of tasks **without** `task_budget` set and record the total tokens Claude spends per task. For an agentic loop, sum `usage.output_tokens` across every request in the loop, plus the tokens of the tool results you append between requests:
515Run a representative sample of tasks **without** `task_budget` set and record the total tokens Claude spends for each task. For an agentic loop, sum `usage.output_tokens` across every request in the loop, plus the tokens of the tool results you append between requests:
516516 
517517<CodeGroup>
518518 ```bash cURL
from line 652
652652 
653653## Interaction with other parameters
654654 
655* **`max_tokens`:** Orthogonal to task budgets. `max_tokens` is a hard per-request cap on generated tokens, while `task_budget` is an advisory cap across the full agentic loop (potentially spanning many requests). At `xhigh` or `max` effort, set `max_tokens` to at least 64k to give Claude room to think and act on each request.
656* **[Effort](https://platform.claude.com/docs/en/build-with-claude/effort):** Effort controls how deeply Claude reasons per step. Task budgets control how much total work Claude does across an agentic loop. The two are complementary: effort tunes depth, task budgets tune breadth.
655* **`max_tokens`:** Orthogonal to task budgets. `max_tokens` is a hard per-request cap on generated tokens, whereas `task_budget` is an advisory cap across the full agentic loop (potentially spanning many requests). At `xhigh` or `max` effort, set `max_tokens` to at least 64k to give Claude room to think and act on each request.
656* **[Effort](https://platform.claude.com/docs/en/build-with-claude/effort):** Effort controls how deeply Claude reasons about each step. Task budgets control how much total work Claude does across an agentic loop. The two are complementary: effort tunes depth, and task budgets tune breadth.
657657* **[Adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking):** Task budgets include thinking tokens in the count, so adaptive thinking scales down as the budget depletes.
658658* **[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching):** The budget-countdown marker is injected server-side on each request, so it does not match across requests. If your client decrements `task_budget.remaining` on each follow-up request, the changed value invalidates any cache prefix that contains it. To preserve caching, set the budget once on the initial request and let the model self-regulate against the server-side countdown rather than mutating the budget client-side.
659659 

build-with-claude/thinking Changed · +31 / -31 lines

from line 8
88 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).
99</Note>
1010 
11A 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.
11A model that answers in a single pass has to get everything right on the first try: no scratch work, no checking, no changing approach halfway through. For a proof, a tricky bug, or a long agentic task, the first approach is often not the best one.
1212 
13Thinking 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 up-front thinking 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.
13Thinking 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 up-front thinking 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 such as 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.
1414 
1515Thinking 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.
1616 
from line 17
1717## How thinking works
1818 
1919<Frame>
20 ![Diagram: Claude determines whether to think up front, may think between tool calls, and returns thinking blocks before text](https://platform.claude.com/docs/images/how-thinking-works.svg)
20 ![Diagram: Claude determines whether to think up front, might think between tool calls, and returns thinking blocks before text](https://platform.claude.com/docs/images/how-thinking-works.svg)
2121</Frame>
2222 
2323Whether Claude thinks on a given request, and how deeply, depends on your thinking configuration and the complexity of the request.
from line 40
4040}
4141```
4242 
43You 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.
43You 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, whereas `"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.
4444 
4545If 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).
4646 
4747## Configuring thinking
4848 
49On most models, thinking is on by default or one parameter away. The following table shows what each model does with each `thinking` value a request can send. A 400 error means the API rejects the request, and [Troubleshooting thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting) has each error and its fix.
49On most models, thinking is on by default or needs only one parameter. The following table shows what each model does with each `thinking` value a request can send. A 400 error means the API rejects the request, and [Troubleshooting thinking](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting) has each error and its fix.
5050 
5151| Model | No `thinking` field | `"adaptive"` | `"enabled"` with `budget_tokens` | `"between_tools"` | `"disabled"` |
5252| --------------------- | ------------------- | ----------------- | -------------------------------- | ----------------------------------------------- | -------------------------------------- |
from line 72
7272 
7373On Claude Opus 5.5, Claude Opus 5, Claude Sonnet 5.5, Claude Sonnet 5, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, Claude Mythos Preview, and Claude Haiku 5.5, 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"}`, as the following examples do.
7474 
75On 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 determine when and how deeply to think based on the request. The same request, with the [model string](https://platform.claude.com/docs/en/models/overview) swapped, turns it on there. The following examples set `display: "summarized"` so the thinking text is visible, and use a roomy `max_tokens`:
75On 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 determine when and how deeply to think based on the request. The same request, with the [model string](https://platform.claude.com/docs/en/models/overview) swapped, turns it on there. The following examples set `display: "summarized"` so the thinking text is visible, and use a large `max_tokens`:
7676 
7777<CodeGroup>
7878 ```bash cURL
from line 276
276276 client = Anthropic::Client.new
277277 
278278 message = client.messages.create(
279 model: "claude-opus-5-5",
279 model: Anthropic::Model::CLAUDE_OPUS_5_5,
280280 max_tokens: 16000,
281281 thinking: {
282282 type: "adaptive",
from line 442
442442 client = Anthropic::Client.new
443443 
444444 message = client.messages.create(
445 model: "claude-sonnet-5",
445 model: Anthropic::Model::CLAUDE_SONNET_5,
446446 max_tokens: 4096,
447447 thinking: { type: "disabled" },
448448 messages: [
from line 477
477477* `"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.5, Claude Opus 5, Claude Sonnet 5.5, Claude Sonnet 5, Claude Opus 4.8, Claude Opus 4.7, [Claude Mythos Preview](https://anthropic.com/glasswing), and Claude Haiku 5.5.
478478* `"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`.
479479 
480Set `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.
480Set `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 starts streaming sooner.
481481 
482482With `display: "omitted"`, the response contains `thinking` blocks with an empty `thinking` field:
483483 
from line 502
502502* You're still charged for the full thinking tokens. Omitting reduces latency, not cost.
503503* 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.
504504* `display` is invalid with `thinking.type: "disabled"` (there is nothing to display) and with `thinking.type: "between_tools"` (Claude Sonnet 5.5 only), which accepts no other field. With `between_tools`, progress updates still come back with summary text, as they do under `display: "updates"` (see [Progress updates](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates)).
505* When using `thinking.type: "adaptive"` and the model skips thinking for a simple request, no thinking block is produced regardless of `display`.
505* When you use `thinking.type: "adaptive"` and the model skips thinking for a simple request, no thinking block is produced regardless of `display`.
506506* 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.
507507 
508508<Note>
from line 518
518518* 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.
519519* 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.
520520* Summarization preserves the key ideas of Claude's thinking process with minimal added latency, so summaries can stream as they arrive.
521* Summarization is processed by a different model from the one you target in your requests. The thinking model does not see the summarized output.
521* Summarization is processed by a different model from the one you target in your requests. The thinking model does not receive the summarized output.
522522* As Anthropic seeks to improve the thinking feature, summarization behavior is subject to change.
523523 
524524<Note>
from line 532
532532Thinking 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.
533533 
534534<Frame>
535 ![Diagram of the streaming event sequence with thinking: the thinking block opens, thinking deltas carry text only when the display setting returns text (summarized, or updates for progress-update blocks), a single signature delta closes the block, then text deltas stream](https://platform.claude.com/docs/images/how-thinking-streams.svg)
535 ![Streaming with thinking: thinking deltas (text only if the display setting returns it), a signature delta, then text deltas](https://platform.claude.com/docs/images/how-thinking-streams.svg)
536536</Frame>
537537 
538538The following examples stream a response with adaptive thinking, printing thinking and text deltas as they arrive:
from line 773
773773 client = Anthropic::Client.new
774774 
775775 stream = client.messages.stream(
776 model: "claude-opus-5-5",
776 model: Anthropic::Model::CLAUDE_OPUS_5_5,
777777 max_tokens: 16000,
778778 # A plain hash like this one takes display:. The typed ThinkingConfigAdaptive class
779779 # spells it display_ (trailing underscore) to avoid shadowing Ruby's Kernel#display.
from line 838
838838 ```
839839</Accordion>
840840 
841When `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:
841When `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 starts immediately after:
842842 
843843```sse Output
844844event: content_block_start
from line 884
884884 The streaming system processes content in batches, which can delay and group streaming events into this "chunky" delivery pattern.
885885</Note>
886886 
887For general streaming mechanics, see [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming).
887For general streaming mechanics, see [Streaming messages](https://platform.claude.com/docs/en/build-with-claude/streaming).
888888 
889889## Thinking and effort
890890 
from line 906
9069061. **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 Opus 5.5, Claude Sonnet 5.5, 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)). Where forced tool use is accepted, the response starts with the tool call and has no `thinking` block.
9079072. **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).
908908 
909**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:
909**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 might include multiple tool calls and results. This whole sequence is a single assistant turn:
910910 
911911```text wrap
912912User: "What's the weather in Paris?"
from line 915
915915Assistant: [text: "The weather in Paris is 20°C and sunny"]
916916```
917917 
918The 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.
918The 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 starts with a thinking block. Adaptive mode relaxes this: no assistant turn needs to start with one.
919919 
920**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.
920**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 might 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.
921921 
922922**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:
923923 
from line 934
934934 
935935### Preserving thinking blocks
936936 
937When 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:
937When Claude calls 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:
938938 
9399391. **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.
9409402. **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.
from line 1047
10471047* Pass progress-update blocks back unchanged with the rest of the assistant turn, like any other `thinking` block.
10481048* 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.
10491049* 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.
1050* 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).
1050* 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 completed. 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).
10511051* 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).
10521052* 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) or, for Claude Opus 5.5, [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#user-facing-progress-updates). For Claude Sonnet 5.5, see [User-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#user-facing-progress-updates).
10531053 
from line 1060
10601060 
10611061Preservation brings two benefits:
10621062 
1063* **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.
1063* **Cache optimization:** preserved thinking blocks allow 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.
10641064* **No intelligence impact:** preserving thinking blocks has no negative effect on model performance.
10651065 
10661066The 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).
from line 1081
10811081To 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:
10821082 
10831083* [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).
1084* [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.
1084* 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.
10851085* [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.
1086* [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 a `block_binding.prefix_mismatch_behavior` field (`"error"` or `"drop_block"`) to the thinking configuration and an `input_transformations` array to every response. The array lists each thinking block that the API dropped, or that failed the prefix check and was let through.
1086* 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 a `block_binding.prefix_mismatch_behavior` field (`"error"` or `"drop_block"`) to the thinking configuration and an `input_transformations` array to every response. The array lists each thinking block that the API dropped, or that failed the prefix check and was let through.
10871087 
10881088## Thinking and prompt caching
10891089 
from line 1138
11381138The 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.
11391139 
11401140<Frame>
1141 ![Diagram of thinking on a model that strips previous thinking blocks: each turn's thinking block is generated in the output and not carried into later turns' input](https://platform.claude.com/docs/images/context-window-thinking.svg)
1141 ![Thinking on a model that strips previous thinking: each turn's thinking is generated but not carried into later turns' input](https://platform.claude.com/docs/images/context-window-thinking.svg)
11421142</Frame>
11431143 
11441144The 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.
11451145 
11461146<Frame>
1147 ![Diagram of thinking with tool use on a model that strips previous thinking blocks: thinking is kept with its tool result, then dropped on the next user turn](https://platform.claude.com/docs/images/context-window-thinking-tools.svg)
1147 ![Thinking with tools on a model that strips previous thinking: thinking stays with its tool result until the next user turn](https://platform.claude.com/docs/images/context-window-thinking-tools.svg)
11481148</Frame>
11491149 
11501150Use 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.
from line 1164
11641164 
11651165## Redacted thinking blocks
11661166 
1167In 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:
1167In addition to regular `thinking` blocks, the API might 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:
11681168 
11691169```json
11701170{
from line 1173
11731173}
11741174```
11751175 
1176The `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).
1176The `data` field is opaque and encrypted. As with 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).
11771177 
11781178<Tip>
11791179 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).
from line 1221
12211221 
12221222### Long requests
12231223 
1224The SDK requires 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()` (java: `.createStreaming()`; csharp: `.CreateStreaming()`; go: `.NewStreaming()`; php: `->createStream()`) with `.get_final_message()` (typescript: `.finalMessage()`; ruby: `.accumulated_message`; csharp: `.Aggregate()`; go: `message.Accumulate(event)`; java, php: `MessageAccumulator`) to get the complete `Message` object without assembling it from individual events yourself. 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.
1224The SDK requires 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()` (java: `.createStreaming()`; csharp: `.CreateStreaming()`; go: `.NewStreaming()`; php: `->createStream()`) with `.get_final_message()` (typescript: `.finalMessage()`; ruby: `.accumulated_message`; csharp: `.Aggregate()`; go: `message.Accumulate(event)`; java, php: `MessageAccumulator`) to get the complete `Message` object without assembling it from individual events yourself. 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.
12251225 
12261226## Next steps
12271227 
from line 1239
12391239 </Card>
12401240 
12411241 <Card title="Troubleshooting thinking" icon="hammer" href="https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting">
1242 Diagnose and fix the most common thinking failures: configuration 400 errors, empty or missing thinking blocks, max\_tokens stops, and cache misses.
1242 Diagnose and fix the most common thinking failures: configuration 400 errors, empty or missing thinking blocks, `max_tokens` stops, and cache misses.
12431243 </Card>
12441244 
12451245 <Card title="Effort" icon="sliders" href="https://platform.claude.com/docs/en/build-with-claude/effort">

build-with-claude/thinking-steering-and-cost Changed · +25 / -25 lines

from line 8
88 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).
99</Note>
1010 
11Claude's thinking is adaptive: the model evaluates each request and determines whether to think and how much. You set an intent, optionally specify the effort, and the model allocates reasoning where it judges reasoning will help.
11Claude's thinking is adaptive: the model evaluates each request and determines whether to think and how much. You set an intent, optionally specify the effort, and the model allocates reasoning where reasoning is likely to help.
1212 
1313This makes thinking a strong fit for workloads that mix trivial and complex requests, and for long-horizon agentic workflows where the right amount of reasoning varies from step to step.
1414 
15To learn how to turn thinking on, how to read thinking output, and about [thinking output on Claude Fable 5 and Claude Mythos 5](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-output-on-claude-fable-5-and-claude-mythos-5), see the [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) overview. This page covers how Claude determines when to think, how to steer thinking, and the caching, cost, and pricing mechanics that follow from it.
15To learn how to turn thinking on and how to read thinking output, see the [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) overview. This page covers how Claude determines when to think, how to steer thinking, and the caching, cost, and pricing mechanics that follow from it.
1616 
1717## How Claude determines when to think
1818 
19Thinking is optional for the model. On each request, Claude weighs the complexity of the input and determines whether deeper reasoning would improve the answer. A simple factual question may get a direct response with no thinking block at all; a multistep math problem or a tricky debugging task triggers deeper reasoning.
19Thinking is optional for the model. On each request, Claude evaluates the complexity of the input and determines whether deeper reasoning would improve the answer. A simple factual question may get a direct response with no thinking block at all; a multistep math problem or a tricky debugging task triggers deeper reasoning.
2020 
21The decision happens per request. The same conversation can contain turns with and without thinking, and a turn where Claude chose not to think contains no thinking block. Don't build application logic that assumes every assistant turn starts with one.
21This determination happens per request. The same conversation can contain turns with and without thinking, and a turn where Claude skips thinking contains no thinking block. Don't build application logic that assumes every assistant turn starts with one.
2222 
23The primary control over this decision is the [effort](https://platform.claude.com/docs/en/build-with-claude/effort) parameter, which acts as soft guidance for how willing Claude should be to think and how deeply; see [Effort levels](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#effort-levels) on this page for what each level does.
23The primary control over this determination is the [effort](https://platform.claude.com/docs/en/build-with-claude/effort) parameter, which acts as soft guidance for how often and how deeply Claude uses thinking; see [Effort levels](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#effort-levels) on this page for what each level does.
2424 
2525If you want Claude to think less often, lower the effort level before reaching for prompt-based steering.
2626 
27Thinking also interleaves with tool use automatically: Claude can think between tool calls, reflecting on each tool result before determining what to do next ([interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking)). You don't need a beta header or any additional configuration for this.
27Thinking also interleaves with tool use automatically: Claude can think between tool calls, evaluating each tool result before determining what to do next ([interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking)). You don't need a beta header or any additional configuration for this.
2828 
29For the full picture of how the thinking configuration and the effort parameter interact, see [Thinking and effort](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-effort).
29For full details on how the thinking configuration and the effort parameter interact, see [Thinking and effort](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-effort).
3030 
3131## Steering how often Claude thinks
3232 
33Whether Claude thinks on a given turn is promptable. Effort sets the overall posture, but you can also shape the decision directly with natural-language guidance, either globally in the system prompt or per message from the user turn.
33Whether Claude thinks on a given turn is promptable. Effort sets the overall posture, but you can also shape that behavior directly with natural-language guidance, either globally in the system prompt or per message from the user turn.
3434 
3535Use the two levers together in this order:
3636 
from line 52
5252| `max` | Claude thinks the most readily and at the greatest depth, with no constraint on thinking length. |
5353| `xhigh` | Claude thinks more readily and at greater depth than at `high`, suited to extended exploration. |
5454| `high` (default on most models) | Claude thinks on most requests that benefit from it. Provides deep reasoning on complex tasks. |
55| `medium` (default on Claude Opus 5.5 and Claude Haiku 5.5) | Claude uses moderate thinking. May skip thinking for simple queries. |
55| `medium` (default on Claude Opus 5.5 and Claude Haiku 5.5) | Claude uses moderate thinking. Might skip thinking for simple queries. |
5656| `low` | Claude minimizes thinking. Skips thinking for simple tasks where speed matters most. |
5757 
58At every level, Claude determines per request whether to think. In a tool-use loop, the first request after new user input typically carries most of the reasoning, and follow-up requests that only process tool results can skip thinking, including at `xhigh` and `max`. Thinking per request also tends to decrease as a conversation grows longer. No level guarantees a thinking block on every request.
58At every level, Claude determines for each request whether to think. In a tool-use loop, the first request after new user input typically carries most of the reasoning, and follow-up requests that only process tool results can skip thinking, including at `xhigh` and `max`. Thinking per request also tends to decrease as a conversation grows longer. No level guarantees a thinking block on every request.
5959 
6060This table describes how each level changes thinking behavior. For guidance on which level to choose for a given workload, including per-model recommendations, see [When to adjust the effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort#when-to-adjust-the-effort-parameter) on the effort page.
6161 
62Effort is set at `output_config.effort`, not inside the `thinking` object; for full per-language examples, see [Effort](https://platform.claude.com/docs/en/build-with-claude/effort#basic-usage).
62Effort is set at `output_config.effort`, not inside the `thinking` object; for full per-language examples, see [Set the effort level](https://platform.claude.com/docs/en/build-with-claude/effort#basic-usage).
6363 
6464```json
6565{
from line 82
8282that require multistep reasoning. When in doubt, respond directly.
8383```
8484 
85To encourage thinking instead, use a phrase like:
85To encourage thinking instead, use a phrase such as:
8686 
8787```text wrap
8888This task involves multistep reasoning. Think carefully before responding.
from line 103
103103Prompt-based steering changes model behavior, so treat it like any other prompt change: measure before you ship. Run a representative sample of your traffic with and without the guidance, and compare how often thinking triggers (the presence of thinking blocks in responses), output token usage, latency, and answer quality on the cases that matter to you.
104104 
105105<Warning>
106 Steering Claude to think less often may reduce quality on tasks that benefit from reasoning. Lowering the [effort](https://platform.claude.com/docs/en/build-with-claude/effort) level is usually the better first lever, since it is a calibrated control rather than a wording-sensitive instruction. Measure the impact on your specific workloads before deploying prompt-based tuning to production.
106 Steering Claude to think less often might reduce quality on tasks that benefit from reasoning. Lowering the [effort](https://platform.claude.com/docs/en/build-with-claude/effort) level is usually the better first lever, because it is a calibrated control rather than a wording-sensitive instruction. Measure the impact on your specific workloads before deploying prompt-based tuning to production.
107107</Warning>
108108 
109109## Mechanics
from line 112
112112 
113113### Turn validation
114114 
115Assistant turns don't need to start with a thinking block. (Models using a legacy manual thinking budget enforce that the final assistant turn of a thinking-enabled request begins with one; see [Turn structure in manual mode](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#turn-structure-in-manual-mode).)
115Assistant turns don't need to start with a thinking block. (Models using a legacy manual thinking budget enforce that the final assistant turn of a thinking-enabled request starts with one; see [Turn structure in manual mode](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#turn-structure-in-manual-mode).)
116116 
117117For multi-turn applications, this means you can pass back conversation history in whatever shape you have it:
118118 
119* Assistant turns where Claude chose not to think are valid history as-is.
119* Assistant turns without thinking are valid history as-is.
120120* You can resume a conversation that began without thinking, or that used a different thinking configuration, without rewriting its history.
121121* History assembled from mixed sources doesn't need thinking blocks reinserted at the start of each assistant turn to pass validation.
122122 
from line 126
126126 
127127Consecutive requests that keep the same thinking configuration and effort level preserve prompt caching; see [Thinking and prompt caching](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching) for the full rules. The resolved effort value is rendered into the prompt, so changing it between requests invalidates cache breakpoints, just as changing the legacy [`budget_tokens`](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#extended-thinking-with-prompt-caching) parameter does on models that use it. Setting `effort` explicitly to the model's default is equivalent to omitting it and does not break the cache.
128128 
129The practical consequence: pick a thinking configuration and a top-level effort level per conversation and keep them. If some turns need more or less thinking, use a [per-message effort change](https://platform.claude.com/docs/en/build-with-claude/effort#change-effort-mid-conversation-beta) (beta) on models that support it, or steer with [per-message prompting](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#tuning-thinking-behavior). Both leave earlier cache breakpoints intact, where a change to the thinking configuration or the top-level effort level does not.
129The practical consequence: pick a thinking configuration and a top-level effort level for each conversation and keep them. If some turns need more or less thinking, use a [per-message effort change](https://platform.claude.com/docs/en/build-with-claude/effort#change-effort-mid-conversation-beta) (beta) on models that support it, or steer with [per-message prompting](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#tuning-thinking-behavior). Both leave earlier cache breakpoints intact, where a change to the thinking configuration or the top-level effort level does not.
130130 
131131The following example demonstrates the invalidation with a multi-turn script you can run yourself:
132132 
from line 134
134134 <Tabs>
135135 <Tab title="cURL">
136136 <Note>
137 This workflow doesn't translate well to a one-off shell command. See the SDK tabs for the multi-turn pattern; per-turn HTTP requests follow the examples on the [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) page.
137 This workflow doesn't translate well to a one-off shell command. Use the Claude SDK to run it; per-turn HTTP requests follow the examples on the [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) page.
138138 </Note>
139139 </Tab>
140140 
141141 <Tab title="CLI">
142142 <Note>
143 This workflow doesn't translate well to a one-off shell command. See the SDK tabs for the multi-turn pattern; per-turn CLI invocations follow the examples on the [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) page.
143 This workflow doesn't translate well to a one-off shell command. Use the Claude SDK to run it; per-turn CLI commands follow the examples on the [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) page.
144144 </Note>
145145 </Tab>
146146 
from line 847
847847 </Tab>
848848 </Tabs>
849849 
850 Here is the output of the script (you may see slightly different numbers):
850 Here is the output of the script (you might see slightly different numbers):
851851 
852852 ```text Output wrap
853853 First request - establishing cache
from line 872
872872 
873873Because thinking counts toward `max_tokens`, set it high enough to leave room for both the reasoning and the answer. A `max_tokens` sized for a response with no thinking is often too small once Claude starts thinking on hard requests.
874874 
875At `high` effort and above, Claude may think extensively and is more likely to exhaust the budget. If you see [`stop_reason: "max_tokens"`](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#stopped-at-max-tokens) in responses, you have two remedies:
875At `high` effort and above, Claude might think extensively and is more likely to exhaust the budget. If you see [`stop_reason: "max_tokens"`](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#stopped-at-max-tokens) in responses, you have two remedies:
876876 
877877* Raise `max_tokens` to give the model more room for thinking plus the answer.
878878* Lower the effort level so Claude thinks less and leaves more of the budget for response text.
from line 884
884884Thinking incurs charges for:
885885 
886886* Tokens Claude uses while thinking (billed as output tokens)
887* Thinking blocks from prior assistant turns that remain in context, per the [preservation default](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model): all turns by default on keep-all models, only the last turn elsewhere (billed as input tokens)
887* Thinking blocks from prior assistant turns that remain in context, according to the [preservation default](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model): all turns by default on keep-all models, only the last turn elsewhere (billed as input tokens)
888888* Standard text output tokens
889889 
890890<Note>
from line 932
932932 </Card>
933933 
934934 <Card title="Effort" icon="sliders" href="https://platform.claude.com/docs/en/build-with-claude/effort">
935 Control how much thinking and output Claude allocates per request.
935 Control how much thinking and output Claude allocates for each request.
936936 </Card>
937937</CardGroup>
938938 

build-with-claude/thinking-tool-workflows Changed · +8 / -8 lines

from line 265
265265 }
266266 
267267 message = client.messages.create(
268 model: "claude-opus-5-5",
268 model: Anthropic::Model::CLAUDE_OPUS_5_5,
269269 max_tokens: 16000,
270270 thinking: {
271271 type: "adaptive"
from line 281
281281 </Step>
282282 
283283 <Step title="Capture the content array to echo back">
284 You should see `thinking` and `tool_use` blocks in the response content on a run where Claude chose to think (on simpler requests, adaptive mode may skip the thinking block). A note Claude writes before the tool call comes back as a `text` block or, on models that write [progress updates](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates), as another `thinking` block. Keep this content array intact: the next step sends it back verbatim.
284 You should see `thinking` and `tool_use` blocks in the response content on a run that includes thinking (on simpler requests, adaptive mode may skip the thinking block). A note Claude writes before the tool call comes back as a `text` block or, on models that write [progress updates](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates), as another `thinking` block. Keep this content array intact: the next step sends it back verbatim.
285285 
286286 <Note>
287287 To see thinking text like this output, add `display: "summarized"` to the request. On models where display defaults to omitted, including Claude Opus 5.5, the `thinking` field otherwise comes back as an empty string with only the `signature` populated. Either way, echo the content array back unchanged; see [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display).
from line 344
344344 # Extract the tool use block to get its ID for the tool result
345345 tool_use_block = next(block for block in response.content if block.type == "tool_use")
346346 
347 # Call your actual weather API, here is where your actual API call would go
348 # Let's pretend this is what we get back
347 # This is where your actual weather API call would go
348 # Pretend this is what the weather API returns
349349 weather_data = {"temperature": 88}
350350 
351351 # Second request - Include the assistant turn and the tool result
from line 402
402402 // Extract the tool use block to get its ID for the tool result
403403 const toolUseBlock = response.content.find((block) => block.type === "tool_use");
404404 
405 // Call your actual weather API, here is where your actual API call would go
406 // Let's pretend this is what we get back
405 // This is where your actual weather API call would go
406 // Pretend this is what the weather API returns
407407 const weatherData = { temperature: 88 };
408408 
409409 if (toolUseBlock) {
from line 705
705705 }
706706 
707707 response = client.messages.create(
708 model: "claude-opus-5-5",
708 model: Anthropic::Model::CLAUDE_OPUS_5_5,
709709 max_tokens: 16000,
710710 thinking: {
711711 type: "adaptive"
from line 723
723723 weather_data = { temperature: 88 }
724724 
725725 continuation = client.messages.create(
726 model: "claude-opus-5-5",
726 model: Anthropic::Model::CLAUDE_OPUS_5_5,
727727 max_tokens: 16000,
728728 thinking: {
729729 type: "adaptive"

build-with-claude/thinking-troubleshooting Changed · +18 / -18 lines

from line 54
5454"thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.
5555```
5656 
57This happens because the model you requested has removed extended thinking (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
57This occurs because the model you requested has removed extended thinking (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
5858 
5959Switch the request to `thinking: {type: "adaptive"}` and steer thinking depth with `effort` instead of `budget_tokens`. [Migrating to adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#migrating-to-adaptive-thinking) walks through the conversion.
6060 
from line 72
7272"thinking.type.disabled" is not supported for this model. Thinking defaults to adaptive mode when not specified; use "thinking.type.enabled" with "budget_tokens" for extended thinking.
7373```
7474 
75This happens because thinking is always on for all of these models (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
75This occurs because thinking is always on for all of these models (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
7676 
7777Omit the `thinking` parameter; these models think without any configuration. If your goal was to keep thinking text out of responses, use `display: "omitted"` instead of disabling thinking; see [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display).
7878 
from line 94
9494"thinking.type.between_tools" is not supported for this model.
9595```
9696 
97This happens because only Claude Sonnet 5.5 accepts `thinking: {type: "between_tools"}` (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
97This occurs because only Claude Sonnet 5.5 accepts `thinking: {type: "between_tools"}` (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
9898 
9999Send `between_tools` only to Claude Sonnet 5.5. On other models, omit `thinking` or use a `thinking.type` value the table doesn't list as rejected.
100100 
from line 106
106106output_config.effort 'xhigh' is not supported when thinking is disabled on this model. Use effort 'high' or below, or enable thinking.
107107```
108108 
109This happens because Claude Sonnet 5.5 accepts `between_tools` only at [effort](https://platform.claude.com/docs/en/build-with-claude/effort) `high` or below. The message says thinking is disabled because `between_tools` has no up-front thinking, even though the request didn't send `"disabled"`. The message names the level the request sent.
109This occurs because Claude Sonnet 5.5 accepts `between_tools` only at [effort](https://platform.claude.com/docs/en/build-with-claude/effort) `high` or below. The message says thinking is disabled because `between_tools` has no up-front thinking, even though the request didn't send `"disabled"`. The message names the level the request sent.
110110 
111Lower the effort to `high` or below. To run at `xhigh` or `max`, use adaptive thinking: omit the `thinking` field or send `thinking: {"type": "adaptive"}`. That's what the message means by "enable thinking". Claude Sonnet 5.5 rejects `"enabled"` with a 400 error.
111Lower the effort to `high` or below. To run at `xhigh` or `max`, use adaptive thinking: omit the `thinking` field or send `thinking: {"type": "adaptive"}`. That's what the message means by "enable thinking." Claude Sonnet 5.5 rejects `"enabled"` with a 400 error.
112112 
113113Claude Haiku 5.5 returns the same message when a request sends `thinking: {type: "disabled"}` at effort `xhigh` or `max`. It accepts `"disabled"` only at `high` or below. Lower the effort, or set `thinking` to `{"type": "adaptive"}`.
114114 
from line 122
122122 
123123The message says thinking is disabled because `between_tools` has no up-front thinking. With `between_tools`, effort can't change mid-conversation: a per-message `output_config.effort` that differs from the level in effect returns a 400 error. `messages.N` is the position of the message that set the new level.
124124 
125Remove that per-message effort, or set it to the level in effect. To vary effort per turn, use adaptive thinking: omit the `thinking` field or send `thinking: {"type": "adaptive"}`. That's what the message means by "enable thinking".
125Remove that per-message effort, or set it to the level in effect. To vary effort for each turn, use adaptive thinking: omit the `thinking` field or send `thinking: {"type": "adaptive"}`. That's what the message means by "enable thinking."
126126 
127Claude Haiku 5.5 returns the same message when a request with `thinking: {type: "disabled"}` sets a per-message effort that differs from the level in effect. Remove that per-message effort, or set `thinking` to `{"type": "adaptive"}` to vary effort per turn.
127Claude Haiku 5.5 returns the same message when a request with `thinking: {type: "disabled"}` sets a per-message effort that differs from the level in effect. Remove that per-message effort, or set `thinking` to `{"type": "adaptive"}` to vary effort for each turn.
128128 
129129## A 400 error says adaptive thinking is not supported
130130 
from line 134
134134adaptive thinking is not supported on this model
135135```
136136 
137This happens because the model supports only extended thinking (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
137This occurs because the model supports only extended thinking (see the [per-model configuration table](https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#rejected-configurations)).
138138 
139139Use `thinking: {type: "enabled", budget_tokens: N}` instead; see [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) for the configuration.
140140 
from line 146
146146`thinking` or `redacted_thinking` blocks in the latest assistant message cannot be modified
147147```
148148 
149In multi-turn and tool-use conversations you send previous assistant messages, including their `thinking` and `redacted_thinking` blocks, back to the API, and the API verifies they arrive unmodified. This error happens when the assistant message you send back differs from the one the API returned, most often because your code filters content blocks by type and drops `redacted_thinking` blocks, or rebuilds the assistant message instead of echoing it.
149In multi-turn and tool-use conversations you send previous assistant messages, including their `thinking` and `redacted_thinking` blocks, back to the API, and the API verifies they arrive unmodified. This error occurs when the assistant message you send back differs from the one the API returned, most often because your code filters content blocks by type and drops `redacted_thinking` blocks, or rebuilds the assistant message instead of echoing it.
150150 
151151Echo the assistant turn back verbatim, thinking blocks included. See [Preserving thinking blocks](https://platform.claude.com/docs/en/build-with-claude/thinking#preserving-thinking-blocks) for the rules, and the worked round trip in [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) for correct code in every SDK.
152152 
from line 174
174174 
175175The response contains `thinking` blocks, but their `thinking` field is an empty string and only the `signature` field is populated.
176176 
177This happens because `display` defaults to `"omitted"` on newer models, which returns thinking blocks without their text.
177This occurs because `display` defaults to `"omitted"` on newer models, which returns thinking blocks without their text.
178178 
179Set `display: "summarized"` in your thinking configuration to receive the summarized thinking text. See [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) for the defaults per model. If you only want the short status lines some models write between tool calls, and not the reasoning, set `display: "updates"` (beta) instead. See [Progress updates between tool calls](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates).
179Set `display: "summarized"` in your thinking configuration to receive the summarized thinking text. See [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) for each model's default. If you only want the short status lines some models write between tool calls, and not the reasoning, set `display: "updates"` (beta) instead. See [Progress updates between tool calls](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates).
180180 
181181A block whose `thinking` field is empty is still complete: the `signature` holds the reasoning. Send it back with the turn like any other. See [Send assistant turns back exactly as returned](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#append-assistant-turns-exactly-as-returned).
182182 
from line 184
184184 
185185Some responses contain no `thinking` block at all, even though thinking is configured.
186186 
187This is normal in adaptive mode: Claude skips thinking on requests it judges simple enough to answer directly.
187This is normal in adaptive mode: Claude skips thinking on requests it determines are simple enough to answer directly.
188188 
189189If you want thinking more often or more deeply, raise `effort` or steer with prompting; see [Steering how often Claude thinks](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#tuning-thinking-behavior).
190190 
from line 194
194194 
195195A response occasionally writes a tool call into its text instead of emitting a `tool_use` block, or includes `<thinking>` or other internal XML tags in its visible text. A leaked tool call never runs, and in agentic loops the leaked text stays in the conversation history, so later turns are affected as well.
196196 
197This happens on Claude Opus 5 when thinking is disabled, most commonly on tool-heavy workloads such as search. System-prompt rules instructing the model not to think or not to reason increase the tag leakage.
197This occurs on Claude Opus 5 when thinking is disabled, most commonly on tool-heavy workloads such as search. System-prompt rules instructing the model not to think or not to reason increase the tag leakage.
198198 
199199Re-enable thinking (the default) and use lower `effort` levels to control token cost instead. If your integration must keep thinking disabled, apply the prompting mitigations in [Running with thinking disabled](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#running-with-thinking-disabled).
200200 
from line 202
202202 
203203The response ends with `stop_reason: "max_tokens"`, often with a truncated or missing text block.
204204 
205This happens because thinking tokens count toward `max_tokens`, so a long thinking pass can consume the budget before the text response completes.
205This occurs because thinking tokens count toward `max_tokens`, so a long thinking pass can consume the budget before the text response completes.
206206 
207207Raise `max_tokens` to leave room for both thinking and text, or lower `effort` so Claude spends less on thinking; see [Cost control](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#cost-control) and [Thinking and the context window](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-the-context-window).
208208 
from line 218
218218 
219219You change `effort` but thinking frequency or depth stays the same.
220220 
221This happens because effort is the primary thinking lever only in adaptive mode. On extended-thinking-only models, thinking depth is set by `budget_tokens` instead.
221This occurs because effort is the primary thinking lever only in adaptive mode. On extended-thinking-only models, thinking depth is set by `budget_tokens` instead.
222222 
223223Adjust `budget_tokens` on those models, or check which mode your model runs in; see [Thinking and effort](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-effort). On Claude Opus 4.5, the one extended-thinking-only model that supports effort, effort composes with the budget; see [Budget rules and tuning](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#budget-rules-and-tuning).
224224 

build-with-claude/token-counting Changed · +3 / -3 lines

from line 32
3232<Note>
3333 The token count is an **estimate**. In some cases, the actual number of input tokens used when creating a message might differ by a small amount.
3434 
35 Token counts may include tokens added automatically by Anthropic for system optimizations. **You are not billed for system-added tokens**. Billing reflects only your content.
35 Token counts might include tokens added automatically by Anthropic for system optimizations. **You are not billed for system-added tokens**. Billing reflects only your content.
3636</Note>
3737 
3838### Supported models
from line 784
784784<Note>
785785 See [Thinking and the context window](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-the-context-window) for more details.
786786 
787 * Thinking blocks from **previous** assistant turns count toward your input tokens on models that [keep all prior turns](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model); on models that keep only the last turn, the API strips them and they do **not** count
788 * **Current** assistant turn thinking **does** count toward your input tokens
787 * Thinking blocks from **previous** assistant turns count toward your input tokens on models that [keep all prior turns](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-block-preservation-by-model); on models that keep only the last turn, the API strips them and they do **not** count.
788 * **Current** assistant turn thinking **does** count toward your input tokens.
789789</Note>
790790 
791791<CodeGroup>
Feedback