What you will be able to do
- List every component of a request that counts toward Claude's context window and budget them as one total
- Predict how the API responds when input alone, or input plus max_tokens, exceeds the window
- Explain how thinking blocks from earlier turns affect later context and billing on different models
- Measure context use before a request with the token counting endpoint and after it with the usage fields
- Match a tool-heavy agent's context cost to the technique that reduces it
Key concept
Context window as one shared budget — The context window is a single token budget. The system prompt, tool definitions, the whole message history with its tool results, and the turn's output and thinking all draw on it. Caching changes what those tokens cost you, but they still take up space in the window.
1.What fills the context window
The context window is the model's working memory for a single request. Everything Claude can refer to while it answers sits inside it, and so does the answer it is writing. The request side holds the system prompt, every message in messages (tool results, images and documents included) and your tool definitions. The output Claude generates for the turn counts as well, and that includes its extended thinking. Treat these as one budget: a 30,000-token tool catalogue leaves 30,000 fewer tokens for conversation, whether or not any tool gets called.
| Component | Counts toward the window? | Note |
|---|---|---|
| System prompt | Yes | Sent on every request |
| Tool definitions | Yes | Present even on turns where no tool is called |
| Messages, including tool results, images and documents | Yes | Grow with every turn, because previous turns are kept in full |
| Output for the turn, including extended thinking | Yes | Capped by max_tokens, up to 128k on 1M-window models |
| Cached prefix (cache_read_input_tokens, cache_creation_input_tokens) | Yes | Caching changes the price of these tokens, not whether they count |
Window sizes are large now. Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.1 and several others have a 1M-token window and can produce up to 128k output tokens in one request. Older models, such as the deprecated Claude Sonnet 4.5, have 200k. On 1M-window models the full window is the default and is billed at standard pricing. The exception is Claude Haiku 5.5, where prompts over 100,000 tokens cost more.
A bigger window doesn't mean you should fill it. Accuracy and recall get worse as the token count grows, so a sensible budget stays well under the ceiling. Context limits and context rot explains that degradation. In this lesson it matters because it is the reason to measure context and trim it long before the hard limit.
Checkpoint 1 of 8· Check yourself
An agent caches its 40,000-token system prompt and tool catalogue. On the next turn, the response's usage field shows cache_read_input_tokens: 40,000 and input_tokens: 5,000, and no tool was called. How many tokens of the context window does that turn's input take up?
Caching lowers what you pay for the prefix, but it doesn't remove those tokens from the window. Tool definitions also count on turns where no tool is called, so the input takes up 40,000 + 5,000 = 45,000 tokens.
“Cached prompt prefixes still occupy the context window: prompt caching changes what you pay for those tokens, not whether they count.”Source: platform.claude.com
Sources1
2.What happens at the limit
The API handles two overflow cases differently.
- Input alone is larger than the window. Every model rejects the request with a
400 invalid_request_error("prompt is too long"). Generation never begins. - **Input fits, but input plus
max_tokensdoesn't.** On Claude 4.5 models and newer (Opus 4.8 included), the request is accepted. If generation then reaches the window limit, it stops withstop_reason: "model_context_window_exceeded". Earlier models return a validation error unless you opt in with themodel-context-window-exceeded-2025-08-26beta header.
In neither case does the API rescue the request for you. It doesn't drop old turns and it doesn't enlarge the window for one call. Some chat interfaces such as claude.ai manage the window on a rolling first-in, first-out basis, but a plain API request keeps every previous turn in full. If your code doesn't check stop_reason, it will treat a truncated answer as a finished one.
Checkpoint 2 of 8· Check yourself
A team moves its long-running support chat from claude.ai to direct Messages API calls. The team assumes that, as on claude.ai, the oldest turns will fall out of the window on their own once the conversation gets long. On the plain API, what actually happens to earlier turns?
Rolling first-in, first-out trimming is something chat interfaces such as claude.ai do. A plain API request keeps every previous turn in full and never drops turns or enlarges the window for you. Keeping the conversation within the window is the application's job.
“each user message and assistant response accumulates within the context window, and previous turns are preserved completely.”Source: platform.claude.com
Checkpoint 3 of 8· Exam question
A developer calling Claude Opus 4.8 sends a request where the input tokens alone fit comfortably within the model's context window, but input tokens plus the requested max_tokens together exceed it. What should they expect from the API?
Correct answer: A — The API accepts the request, and if generation reaches the context window limit it stops early with stop_reason set to model_context_window_exceeded
- A. Correct. On Claude 4.5 models and newer, a request where input plus max_tokens exceeds the window is still accepted. If generation actually reaches the limit, the response stops with stop_reason model_context_window_exceeded rather than failing upfront.
- B. Incorrect. The 400 invalid_request_error for a prompt being too long is reserved for cases where the input alone already exceeds the context window, not when only input-plus-max_tokens would exceed it.
- C. Incorrect. The Claude API does not perform rolling first-in-first-out trimming of conversation history on your behalf; that behavior is associated with some chat interfaces, not standard API requests.
- D. Incorrect. Context window size is fixed per model and is not dynamically expanded for an individual request based on the max_tokens value requested.
Sources1
3.Thinking tokens across turns
Thinking draws on two budgets at once. In the turn where it's generated, thinking is part of max_tokens, is billed as output and counts toward rate limits. With adaptive thinking, Claude decides how much to think, so thinking usage changes from request to request. What happens to those blocks on later turns depends on the model.
| Model family | Earlier thinking blocks on later turns | Effect on later requests |
|---|---|---|
| Opus 4.5 and later, Sonnet 4.6 and later, Haiku 5.5, Fable and Mythos models | Kept by default | Count toward the window and are billed as input tokens, like any other history |
| Earlier Opus and Sonnet models, all Haiku models through Haiku 4.5 | Stripped automatically by the API when you pass them back | Don't count toward the window; you don't need to strip them yourself |
So on a model that keeps thinking, a block is paid for twice in different ways. It is billed once as output when it's generated, and then billed as input on every later request that carries it. Over a 40-turn session that adds up. Thinking block clearing (taught in the context editing lesson) lets you override the default in either direction.
Tool use adds one hard rule. When you send back a tool result, you must include the thinking block from that assistant turn, complete and unmodified, with its signature. This is the only case where returning thinking is required. The API checks the cryptographic signature and returns an error if the block has been changed. Once the tool cycle ends and a new user turn starts, that block no longer has to stay in context.
Some models also see their own budget. Claude Sonnet 5, Sonnet 4.6, Sonnet 4.5 and Haiku 4.5 have context awareness. The API puts the total window in a <budget:token_budget> tag and sends a remaining-capacity warning after each tool call, so the model can pace a long task. Opus 4.7 and later, Sonnet 5.5, Haiku 5.5 and the Fable and Mythos models don't get these tags. On those models you can set an explicit budget with task budgets, which are in beta.
Checkpoint 4 of 8· Check yourself
A team moves a multi-turn agent from Claude Haiku 4.5 to Claude Haiku 5.5 and changes no code. The client has always sent earlier assistant turns back with their thinking blocks included. On later turns, input_tokens now grow much faster than before. What explains this?
On Haiku 5.5, the API keeps earlier thinking blocks by default. They take up window space and are billed as input on every later request, just like other history. Haiku models through Haiku 4.5 had them stripped automatically. Thinking is billed as output only once, in the turn where it is generated, and Haiku 5.5 doesn't receive the context-awareness tags.
“the API keeps previous thinking blocks by default, and they count toward the context window like any other input tokens.”Source: platform.claude.com
Sources1
4.Measuring tokens before and after a request
Measure in two places. Before a call, the token counting endpoint takes the same structured input as a message request (system prompt, tools, images, PDFs) and returns the input token count. After a call, the response's usage field reports what the request actually consumed. With prompt caching, the input is split across input_tokens, cache_read_input_tokens and cache_creation_input_tokens, and all three count toward the window. A dashboard that adds up only input_tokens will underreport context use badly once caching is on.
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-opus-5-5",
system="You are a scientist",
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(response.json())Pre-counting has a few limits worth knowing.
- It returns
invalid_request_errorfor server tools such as web search and code execution, for the MCP connector, and for image or document blocks given as aurlor file source. Send images and PDFs as base64 to count them. For server-tool requests, use theusageobject on the real response. - It gives an estimate without caching logic.
cache_controlis accepted but has no effect. - It counts with the tokenizer of the model you pass. The Fable and Mythos models use the tokenizer introduced with Opus 4.7, which counts roughly 30 percent more tokens than models before Opus 4.7. Before a migration, count the same request on both models and compare.
The endpoint is free, but it has its own requests-per-minute limits by usage tier (5,000 at Start).
Checkpoint 5 of 8· Fill the gap
Which method on client.messages returns the input token count for this request without sending it to the model?
client = anthropic.Anthropic()
response = client.messages. ? (
model="claude-opus-5-5",
system="You are a scientist",
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(response.json())messages.count_tokens is the token counting endpoint. It takes the same structured input as a message request and returns { "input_tokens": ... } without generating anything. messages.create sends the real request, and you only learn its usage after the call.
Source: platform.claude.comCheckpoint 6 of 8· Check yourself
Your research agent sends every request with the web search server tool enabled. You want to log how many input tokens each request uses so you can track context growth. Which approach works?
The token counting endpoint returns invalid_request_error for server tools such as web search, so these requests have to be measured from the response's usage object. With caching on, all three input fields count toward the window, and cache_control has no effect on a count request.
“For requests that use server tools or MCP servers, the Messages API response reports the tokens used in its usage object.”Source: platform.claude.com
5.Cutting what tools cost in context
In agents, most of the window goes to tools. Tool definitions are sent on every request, and each call leaves a tool_result in the history. Each of the four techniques below targets a different source of that pressure, so start by finding out where your tokens are going.
| Technique | What it reduces | When it fits |
|---|---|---|
| Tool search | Tool definitions loaded upfront | Large toolsets (20+ tools) where most tools aren't needed every turn |
| Programmatic tool calling | tool_result roundtrips | Chains of tool calls that can execute as a single script |
| Prompt caching | Token cost of repeated tool definitions | Stable toolsets across many requests |
| Context editing | Old tool_result blocks in history | Long conversations where early results are no longer relevant |
Take an agent with 45 tools. Instead of sending every schema upfront, tool search sends a single tool_search tool and Claude finds the others when it needs them. That costs one extra turn of latency and removes most of the baseline definition load. A run of small sequential calls is better handled by programmatic tool calling: Claude writes the chain as one code block that runs in a sandbox, so the intermediate results never come back into the conversation. The definitions you still send can be cached, so repeat requests pay the cache-read rate. Caching only makes the definitions cheaper. They still take up window space.
Some fixes sound good and miss these cost sources. Moving to a 1M-token model, raising max_tokens, or shortening tool names leaves the definition load, the roundtrips and the repeated pricing where they were, and a larger window filled with the same tools still suffers context rot. Another fix is structural: hand verbose exploration to a subagent with its own window, so only its condensed answer reaches the main thread. Coordinator pattern and isolated subagent context covers how that pattern works.
Checkpoint 7 of 8· Match them up
Match each tool-context technique to the source of context pressure it actually reduces.
Tap a term, then the definition that fits it.
Each technique targets a different source of pressure. Tool search defers tool definitions until they're needed. Programmatic tool calling runs a chain as one script, so intermediate results stay out of the conversation. Caching only lowers what repeated definitions cost and doesn't free window space. Context editing clears old tool results from the history.
“To reduce the context consumed by the tool definitions themselves, see Manage tool context, or defer tool definitions with the tool search tool.”Source: platform.claude.com
Checkpoint 8 of 8· Exam question
A production agent uses 45 different tools across long-running conversations. The team identifies three separate cost sources: tool schema definitions consuming context on every request even when most tools go unused that turn, many small sequential tool calls each leaving a tool_result in history, and the same stable tool definitions being resent and re-priced identically on every request. Which changes directly address these three sources?(Select 3)
Correct answers: A, B, C — Enable the tool search tool so schemas load on demand instead of being sent upfront; Use programmatic tool calling so chains of tool calls run as a single script instead of many roundtrips; Apply prompt caching to the stable tool definitions so repeated requests pay the discounted cache-read rate
- A. Correct. Tool search keeps tool definitions out of the context window until Claude requests them, directly reducing the baseline cost of unused schemas loaded upfront.
- B. Correct. Programmatic tool calling collapses chains of tool calls into a single executed script, so intermediate tool_result blocks never enter the conversation history.
- C. Correct. Prompt caching does not shrink the token count of tool definitions but cuts what repeated, stable definitions cost on subsequent requests via the discounted cache-read rate.
- D. Incorrect. max_tokens controls the ceiling on generated output length and has no effect on how much context tool definitions or tool_result history consume.
- E. Incorrect. A larger context window gives more headroom but does not reduce the underlying token cost of the toolset or address any of the three described cost sources.
- F. Incorrect. Shortening tool names yields negligible savings and is not a documented strategy for managing tool-related context cost compared to the other approaches.
Sources3
Sources
(3)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Everything in the request counts toward the context window: the system prompt, every message in messages”
↩︎ What fills the context window“The output Claude generates for the turn, including its extended thinking, counts too.”
↩︎ What fills the context window“A single request to any of them can generate up to 128k output tokens (max_tokens).”
↩︎ What fills the context window“more context isn't automatically better”
↩︎ What fills the context window“If the input alone already exceeds the model's context window, the API returns a 400 invalid_request_error”
↩︎ What happens at the limit“On Claude 4.5 models and newer, if input tokens plus max_tokens exceeds the context window size, the API accepts the request.”
↩︎ What happens at the limit“If generation then reaches the context window limit, it stops with stop_reason”
↩︎ What happens at the limit“Thinking tokens are a subset of your max_tokens parameter, are billed as output tokens, and count toward rate limits.”
↩︎ Thinking tokens across turns“the API keeps previous thinking blocks by default, and they count toward the context window like any other input tokens”
↩︎ Thinking tokens across turns“the API automatically strips previous thinking blocks from the conversation history when you pass them back”
↩︎ Thinking tokens across turns“Thinking tokens are billed as output tokens once, when they are generated.”
↩︎ Thinking tokens across turns“You must return the thinking block with the corresponding tool results. This is the only case where you have to return thinking blocks.”
↩︎ Thinking tokens across turns“these models track their remaining context window”
↩︎ Thinking tokens across turns“the input count is split across input_tokens, cache_read_input_tokens, and cache_creation_input_tokens, and all three count toward the window”
↩︎ Measuring tokens before and after a request“Everything in the request counts toward the context window: the system prompt, every message in messages”
↩︎ Key concept“Cached prompt prefixes still occupy the context window: prompt caching changes what you pay for those tokens, not whether they count.”
↩︎ Exam trap 1“If the input alone already exceeds the model's context window, the API returns a 400 invalid_request_error”
↩︎ Exam trap 2“Cached prompt prefixes still occupy the context window: prompt caching changes what you pay for those tokens, not whether they count.”
↩︎ Checkpoint“each user message and assistant response accumulates within the context window, and previous turns are preserved completely.”
↩︎ Checkpoint“the API keeps previous thinking blocks by default, and they count toward the context window like any other input tokens.”
↩︎ Checkpoint“To reduce the context consumed by the tool definitions themselves, see Manage tool context, or defer tool definitions with the tool search tool.”
↩︎ Checkpoint - 2.
“The token counting endpoint accepts the same structured list of inputs for creating a message, including support for system prompts, tools, images, and PDFs.”
↩︎ Measuring tokens before and after a request“For requests that use server tools or MCP servers, the Messages API response reports the tokens used in its usage object.”
↩︎ Measuring tokens before and after a request“token counting provides an estimate without using caching logic”
↩︎ Measuring tokens before and after a request“roughly 30 percent higher than on models before Claude Opus 4.7”
↩︎ Measuring tokens before and after a request“Token counting is free to use but subject to requests per minute rate limits based on your usage tier.”
↩︎ Measuring tokens before and after a request - 3.
“Tool definitions and accumulated tool_result blocks consume your context window.”
↩︎ Cutting what tools cost in context“Tool search keeps tool definitions out of the context window until Claude asks for them.”
↩︎ Cutting what tools cost in context“Programmatic tool calling collapses a sequence of tool calls into a single code block”
↩︎ Cutting what tools cost in context“Token cost of repeated tool definitions”
↩︎ Cutting what tools cost in context