CertSafari
    Anthropic Claude Certified Architect – Professional (CCAR-P)· Lessons

    Domain 2 · Lesson 10/38

    Context window budgeting: what counts and how to measure it

    Optimize context windows and manage token usage

    13 min read
    2.6% of exam
    3 sources
    Published 19 Oct 2026
    Docs as of 14 Oct 2026

    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.

    Where a request's tokens come from
    ComponentCounts toward the window?Note
    System promptYesSent on every request
    Tool definitionsYesPresent even on turns where no tool is called
    Messages, including tool results, images and documentsYesGrow with every turn, because previous turns are kept in full
    Output for the turn, including extended thinkingYesCapped by max_tokens, up to 128k on 1M-window models
    Cached prefix (cache_read_input_tokens, cache_creation_input_tokens)YesCaching 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?

    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_tokens doesn'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 with stop_reason: "model_context_window_exceeded". Earlier models return a validation error unless you opt in with the model-context-window-exceeded-2025-08-26 beta 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?

    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?

    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.

    How earlier thinking blocks are handled on later turns
    Model familyEarlier thinking blocks on later turnsEffect on later requests
    Opus 4.5 and later, Sonnet 4.6 and later, Haiku 5.5, Fable and Mythos modelsKept by defaultCount toward the window and are billed as input tokens, like any other history
    Earlier Opus and Sonnet models, all Haiku models through Haiku 4.5Stripped automatically by the API when you pass them backDon'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?

    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.

    Counting input tokens before sending; the response is { "input_tokens": 14 }python
    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_error for server tools such as web search and code execution, for the MCP connector, and for image or document blocks given as a url or file source. Send images and PDFs as base64 to count them. For server-tool requests, use the usage object on the real response.
    • It gives an estimate without caching logic. cache_control is 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())

    Checkpoint 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?

    Sources21

    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.

    Which technique addresses which source of tool context pressure
    TechniqueWhat it reducesWhen it fits
    Tool searchTool definitions loaded upfrontLarge toolsets (20+ tools) where most tools aren't needed every turn
    Programmatic tool callingtool_result roundtripsChains of tool calls that can execute as a single script
    Prompt cachingToken cost of repeated tool definitionsStable toolsets across many requests
    Context editingOld tool_result blocks in historyLong 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.

    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)

    0 of 3 selected

    Sources3

    Sources

    (3)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 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. 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

    Continue to part 2 of 2

    Compaction and context editing for long Claude sessions

    Spotted a mistake, or was something unclear? Tell us.