Rubric
Contents — domains, guide and mocks

Context windows and token budgets

CCAR-P 2.412 min read · checked 21 September 2026

Task statementOptimize context windows and manage token usage

What fills the context window on each request

Top: fixed per deployment → bottom: grows with every turn

  1. System promptrole, rules, format — stable
  2. Tool definitionsevery schema you send, used or not
  3. Retrieved documentsRAG chunks, files, uploads
  4. Conversation historyevery earlier user and assistant turn
  5. Tool resultssearch hits, file reads, API payloads
  6. Thinking and outputbilled as output; may return as history
The first five layers are sent — and counted — as input on every request; each response then joins the history for the next one. In a long agent run the bottom layers grow fastest, which is why most token management targets history and tool results.

Why a bigger window is not the answer

Current flagship models offer a 1M-token context window at standard pricing, and Haiku 4.5 offers 200K. It is tempting to read that as “we no longer need to manage context”. Anthropic’s guidance says the opposite, for three reasons an architect should be able to state.

  • Cost scales with volume. The whole context is input on every request. A 300K-token history re-sent across forty agent turns is twelve million input tokens, even if each turn asks a one-line question. Caching lowers the rate but not the volume (caching is covered in 2.5).
  • Attention degrades. The context-engineering post describes “context rot”: as the token count grows, the model’s ability to recall information from context falls. It treats context as a finite resource with diminishing marginal returns — an attention budget, not just a size limit.
  • Latency rises. More input means more to process before the first output token, on every call.

The post’s guiding principle is to find the smallest set of high-signal tokens that maximise the chance of the outcome you want. That turns token management into a design discipline with four moves: measure what is in context, curate what goes in, trim what has gone stale, and offload what must be kept but need not be read every turn.

Measure before you optimise

Every Messages API response reports a usage object with input and output tokens, so you can log exactly what each turn cost. Before sending, the token counting endpoint (client.messages.count_tokens) accepts the same system prompt, messages, tools, images and PDFs as a real request and returns an estimate. It is free, though rate-limited separately from message creation. Use it to reject or trim an oversized request before it fails, and to decide when to summarise.

Know the two overflow behaviours. If the input alone exceeds the window, the API returns a 400 “prompt is too long” error. If the input fits but input plus max_tokens does not, Claude 4.5 and later models accept the request and stop generation with stop_reason: "model_context_window_exceeded" — a truncated answer your code must not treat as complete.

Curate what goes in

The cheapest token is one you never send. Curation happens at design time. Keep the system prompt at the “right altitude” (covered in 2.2). Send only the tools a workflow needs: the manage-tool-context page suggests tool search once a toolset passes about twenty tools, so definitions load on demand. Prefer just-in-time retrieval — keeping lightweight identifiers such as file paths, record IDs or URLs in context and loading content only when needed — over pasting every possibly relevant document up front (the full trade-off is covered in 3.8). And preprocess noisy inputs in code: the Claude Code cost guide’s example is a hook that greps a 10,000-line log for errors, cutting tens of thousands of tokens to hundreds.

Trim and summarise: context editing and compaction

Long-running agents accumulate material that was useful once. Anthropic’s engineering post calls clearing old tool results the “lightest touch” form of compaction: once a tool call is deep in history, the agent rarely needs to see the raw result again. The API offers this server-side as context editing, and a heavier option, compaction, that summarises instead of deleting.

MechanismWhat it doesKey settingsUse when
Tool result clearing (clear_tool_uses_20250919)Replaces old tool results with a placeholder once a trigger is reachedtrigger (default 100K input tokens), keep (default 3 recent uses), clear_at_least, exclude_toolsAgents whose early tool output stops mattering
Thinking clearing (clear_thinking_20251015)Drops thinking blocks from earlier turnskeep a number of thinking turns, or "all"Thinking-heavy runs where old reasoning is dead weight
Compaction (compact_20260112)Summarises earlier conversation into a compaction block that replaces ittrigger (default 150K, minimum 50K), instructions, pause_after_compactionLong chats and agent runs that must keep continuity past the window
Memory tool / notesClaude writes key facts to files it can read back laterA memory tool or your own storeState that must survive clearing, compaction or a new session
SubagentsVerbose work runs in a separate context; only a summary returnsYour orchestration designSearches, test runs and document sweeps that produce bulk
Count first, then let the API clear stale tool resultspython
count = client.messages.count_tokens(
    model="claude-opus-5", system=SYSTEM, tools=TOOLS, messages=messages,
)
if count.input_tokens > 900_000:        # near the 1M window
    raise ContextTooLarge(count.input_tokens)   # trim or summarise first

response = client.beta.messages.create(
    model="claude-opus-5",
    max_tokens=8000,
    system=SYSTEM,
    tools=TOOLS + [{"type": "memory_20250818", "name": "memory"}],
    messages=messages,
    betas=["context-management-2025-06-27"],
    context_management={"edits": [{
        "type": "clear_tool_uses_20250919",
        "trigger": {"type": "input_tokens", "value": 60000},
        "keep": {"type": "tool_uses", "value": 4},     # recent results stay
        "clear_at_least": {"type": "input_tokens", "value": 20000},
        "exclude_tools": ["memory"],                   # never clear notes
    }]},
)
# Log what was cleared, for cost and debugging
print(response.context_management)

Three design details carry the marks. First, context editing is applied on the server before the prompt reaches Claude, so your client keeps the full history and does not have to sync an edited copy. Second, clearing invalidates the prompt cache from the point of the edit, which is why clear_at_least exists: clear a meaningful amount at once rather than a little every turn. Third, pair clearing with the memory tool, so Claude can record what matters before old results disappear and look it up later.

Clear, compact or offload?

What is filling the window?
  • Old tool results
    Clear tool resultskeep recent, exclude key tools
  • Old reasoning
    Clear thinkingkeep last few turns
  • Long dialogue to continue
    Compactionsummary replaces early turns
  • Bulky side tasks
    Subagent or memorysummary back, details stored
Pick the lightest mechanism that solves the problem. Clearing deletes; compaction rewrites; offloading moves material out of the window but keeps it retrievable.

Compaction is for continuity. When input tokens reach the trigger, the API generates a summary, returns it as a compaction block, and on the next request drops everything before that block. Custom instructions replace — not supplement — the default summarisation prompt, so write them to preserve what your domain needs: decisions, identifiers, open questions. pause_after_compaction stops the response with stop_reason: "compaction" so you can inject context or enforce an overall token budget. The summary itself is an extra, billed sampling step, reported in usage.iterations; top-level usage covers only the non-compaction work, so cost dashboards must sum the iterations.

Traps the wrong answers are built from

Tempting but wrongDo this instead
Treating a 1M-token window as permission to send everythingSend the smallest high-signal context; load the rest just in time.
Guessing at token counts or reusing counts from an older modelLog usage per turn and use the token counting endpoint on the target model.
Clearing a few tokens of tool results on every turnSet a sensible trigger and clear_at_least so each cache break is worth it.
Compacting without domain instructions or a backup storeTell compaction what to keep and write critical facts to memory.
Reporting only top-level usage when compaction is onSum usage.iterations so the summarisation cost is visible.

You should now be able to

  • Identify what consumes the context window and measure it with usage and token counting.
  • Explain why larger contexts raise cost and latency and can lower accuracy (context rot).
  • Choose between tool-result clearing, thinking clearing, compaction, memory and subagents.
  • Configure server-side context editing and compaction with appropriate triggers and instructions.
  • Handle context overflow correctly, including model_context_window_exceeded.
  • Curate inputs by trimming tools, preprocessing results and retrieving just in time.

Practice questions

Original questions written for this lesson, in the exam’s style. Answer first, then open the reasoning — every option is explained, including why the wrong ones are tempting.

  1. Question 1

    A consultancy’s research agent calls a web-search tool dozens of times per task. By the end of a run, input exceeds 500K tokens, most of it old search results, and answers start mixing up sources. Earlier findings are already reflected in the agent’s notes.

    Which change most directly addresses the problem?

    1. AEnable tool-result clearing, keeping the few most recent results.
    2. BMove the agent to a model with a larger context window.
    3. CAdd an instruction asking Claude to ignore older search results.
    4. DLower max_tokens so each answer uses fewer tokens.
    Show answer and reasoning
    1. ACorrect. Old search results are stale bulk; clearing them is the lightest mechanism and the notes already hold what matters.
    2. BIncorrect. The window is not the constraint — attention and cost are, and a larger window makes both worse.
    3. CIncorrect. The tokens are still sent, billed and competing for attention; a prompt cannot remove them.
    4. DIncorrect. Output length is not what is filling the window; input history is.
  2. Question 2

    An architect is designing a customer-success copilot where account managers keep a single conversation per client for months. Continuity with early decisions matters, and cost must be reported accurately.

    Which two design choices are most appropriate? (Select 2.)

    1. AServer-side compaction with instructions that preserve decisions, dates and commitments.
    2. BCost reporting that sums usage.iterations, not just top-level usage.
    3. CTool-result clearing with keep set to zero, so nothing old remains.
    4. DStart a fresh conversation whenever the context limit is reached.
    5. EA larger max_tokens so responses can include the full history.
    Show answer and reasoning
    1. ACorrect. Compaction keeps continuity past the window, and custom instructions make the summary keep what the domain needs.
    2. BCorrect. Top-level usage excludes the compaction step; summing iterations captures the real cost.
    3. CIncorrect. Clearing deletes rather than summarises, which loses the continuity the scenario requires.
    4. DIncorrect. That discards the history the account managers rely on.
    5. EIncorrect. Output size does nothing to manage input history.
  3. Question 3

    A request’s input fits in the context window, but input plus max_tokens exceeds it. On a current Claude model, what should the application expect?

    1. AA 400 “prompt is too long” error before any output is generated.
    2. BThe API quietly lowers max_tokens and returns a complete answer.
    3. COutput until the window fills, then model_context_window_exceeded.
    4. DAutomatic compaction of earlier history to make room for output.
    Show answer and reasoning
    1. AIncorrect. That happens only when the input alone exceeds the window.
    2. BIncorrect. Nothing guarantees completeness; the response can be cut off.
    3. CCorrect. Claude 4.5 and later accept the request and signal truncation with this stop reason, which must be handled.
    4. DIncorrect. Compaction runs only when you configure it; it is not an overflow fallback.
  4. Question 4

    A team migrated a document-review agent from an older Claude model to Opus 5. Their per-request token alarms, calibrated on the old model, now fire constantly on the same documents.

    What is the most likely cause and correct response?

    1. AOpus 5 adds a long-context surcharge; move to a smaller model.
    2. BThe documents changed; ask the business to send shorter files.
    3. CCompaction is on by default in Opus 5; disable it to restore counts.
    4. DThe newer tokenizer yields more tokens; re-count and recalibrate on Opus 5.
    Show answer and reasoning
    1. AIncorrect. Current pricing has no long-context surcharge, and the alarms count tokens, not dollars.
    2. BIncorrect. The documents are the same; the change is in how they are counted.
    3. CIncorrect. Compaction is opt-in and would reduce, not inflate, input.
    4. DCorrect. The docs note roughly 30% more tokens on Claude 4.7 and later, so baselines from older models must be re-measured.

Sources

Drafted with AI assistance and checked against the sources above; expert review is in progress. Spotted an error? Tell us and it gets fixed, dated and listed on how this is written.