A long-running agent fills its context window with tool results, and it gets worse well before it runs out. So treat the window as a budget, not a limit. Measure what each request puts in it, keep tool results small when they arrive, drop old ones once they have been used, summarize the history when it gets long, and keep anything the agent must not forget in notes outside the window. This post covers each of those steps, with the settings the Claude API offers for them and code you can use in any loop.
Why a bigger window doesn't solve it
Context windows are large now. Anthropic's docs list a 1M-token window for its current models. That does not make it safe to fill one.
Anthropic's engineering post Effective context engineering for AI agents describes context as a finite resource with diminishing returns. It uses the term "context rot": as the number of tokens grows, the model's ability to recall information from that context decreases. The reason it gives is architectural. Every token attends to every other token, which makes n² pairwise relationships for n tokens, so the model's "attention budget" gets stretched as the context grows. The post's goal for context engineering is to find "the smallest possible set of high-signal tokens" that gets the result you want.
Chroma's research report Context Rot tested 18 models, including GPT-4.1, Claude 4, Gemini 2.5 and Qwen3, and found that performance changes with input length even on simple tasks. Two results matter for agents. A single distractor, text that is related to the question but doesn't answer it, reduced performance compared with the needle alone. And on LongMemEval, models did much better with focused prompts of about 300 tokens than with full prompts of about 113,000 tokens that included irrelevant history.
An agent's history is mostly distractors by the middle of a task: search results it has already read, files it has already edited, errors it has already fixed. That is what the budget is for.
Step 1: Measure what is in the window
Everything in a request counts toward the window: the system prompt, tool definitions, every message including tool results, and the output the model generates, thinking included. Each Claude response reports its input in usage. With prompt caching, that input is split across input_tokens, cache_read_input_tokens and cache_creation_input_tokens, and Anthropic's docs say all three count toward the window. Caching changes what you pay, not how much room you use.
That catches people out. With caching on, input_tokens alone can look tiny while the window is nearly full. Add all three:
def context_used(usage) -> int:
"""Input tokens the last request put in the window, cached or not."""
return (
usage["input_tokens"]
+ usage.get("cache_read_input_tokens", 0)
+ usage.get("cache_creation_input_tokens", 0)
)
To check a request before you send it, the token counting endpoint, client.messages.count_tokens() in the Python SDK, takes the same model, system, tools and messages and returns input_tokens. It is free, has its own rate limits, and the docs call the result an estimate. It does not support server tools such as web search. Count against the model you will actually call: the docs say Claude 4.7 and later models use a newer tokenizer that produces roughly 30 percent more tokens for the same text.
Two things to know about the edges. If the input alone is bigger than the window, the API returns a 400 error; prompt is too long shows how to catch it and trim the history safely. On Claude 4.5 and newer models, if input plus max_tokens is bigger than the window, the request is accepted, and a response that reaches the limit stops with stop_reason: "model_context_window_exceeded". Handle that stop reason in your loop like max_tokens: it means the response was cut off, not that the model finished. The infinite loop post has a loop that treats every stop reason other than tool_use as an exit to handle.
Step 2: Set thresholds and act on them
A budget needs rules for what happens as it fills. Here is a small policy object. The thresholds are a starting point, not a recommendation from any vendor; tune them with your own evals.
from dataclasses import dataclass
@dataclass
class ContextBudget:
window: int = 200_000 # the model's context window
reserve_output: int = 16_000 # room kept for the next response
clear_at: float = 0.50 # start dropping old tool results
compact_at: float = 0.75 # summarize the history
def action(self, usage) -> str:
usable = self.window - self.reserve_output
share = context_used(usage) / usable
if share >= self.compact_at:
return "compact"
if share >= self.clear_at:
return "clear_tool_results"
return "ok"
With the defaults, a response whose usage was 2,000 uncached plus 95,000 cached input tokens returns "clear_tool_results", because 97,000 is more than half of the 184,000 usable tokens. One with 138,000 in total returns "compact". Notice the first case: input_tokens alone was 2,000.
Why these two stages? Anthropic's post calls tool result clearing "one of the safest lightest touch forms of compaction": once a tool was called deep in the history, the agent rarely needs to see the raw result again. Summarizing is heavier, because a summary can lose details. So clear first and compact later.
Step 3: Keep tool results small when they arrive
The cheapest token is one that never enters the window. Most context growth in an agent comes from tool results, and many tools return far more than the model needs.
Anthropic's post recommends "just in time" retrieval: the agent keeps lightweight identifiers such as file paths, stored queries and links, and loads data with tools when it needs it, instead of loading everything up front. For your own tools, that means returning IDs and summaries first and full records on request, paginating, and capping the size of any single result. When you cap, say what was left out, so the model can ask for more instead of guessing:
def trim_tool_result(text: str, max_chars: int = 8_000) -> str:
"""Keep the start of a large result and say how much was left out."""
if len(text) <= max_chars:
return text
dropped = len(text) - max_chars
return (
text[:max_chars]
+ f"\n[{dropped} more characters left out. "
"Ask for a narrower query or the next page.]"
)
A 20,000-character result comes back as the first 8,000 characters plus a note that 12,000 were left out. Tool design affects more than size, too. Why your agent calls the wrong tool covers overlapping tools and vague descriptions, which also cost context: every tool definition is sent on every request.
Step 4: Clear old tool results
On the Claude API you don't have to rewrite history yourself to clear old results. Context editing does it on the server, before the prompt reaches the model, and your client keeps the full history. It is in beta under the context-management-2025-06-27 header, and the strategy is clear_tool_uses_20250919:
response = client.beta.messages.create(
model=MODEL, # a current Claude model
max_tokens=4096,
messages=messages,
tools=tools,
betas=["context-management-2025-06-27"],
context_management={
"edits": [
{
"type": "clear_tool_uses_20250919",
"trigger": {"type": "input_tokens", "value": 30000},
"keep": {"type": "tool_uses", "value": 3},
"clear_at_least": {"type": "input_tokens", "value": 5000},
"exclude_tools": ["web_search"],
}
]
},
)
The defaults, if you leave the options out, are a trigger at 100,000 input tokens and keeping the 3 most recent tool uses. exclude_tools protects tools whose results must stay, and clear_tool_inputs (off by default) clears the call parameters too. The response's context_management.applied_edits reports how many tool uses and input tokens were cleared.
Clearing has a cost if you use prompt caching. The docs say clearing invalidates cached prompt prefixes, so you pay a cache write after each clear, though later requests can reuse the new prefix. That is what clear_at_least is for: it skips the clear unless it frees enough tokens to be worth breaking the cache.
There is a matching strategy for reasoning, clear_thinking_20251015, which keeps the most recent thinking turns. The context windows docs say newer models keep earlier thinking blocks in context by default, and those blocks count toward the window.
Step 5: Compact the history
Compaction replaces older turns with a summary the model writes. Anthropic's post describes how Claude Code does it: the model keeps architectural decisions, unresolved bugs and implementation details, discards redundant tool outputs, and continues with the summary plus the five most recently accessed files.
The Claude API offers this on the server. Threshold compaction is in beta under the compact-2026-01-12 header, with the edit type compact_20260112:
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model=MODEL,
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
messages.append({"role": "assistant", "content": response.content})
The default trigger is 150,000 input tokens, and the minimum is 50,000. When the request reaches it, the response starts with a compaction block, and the API ignores everything before that block on later requests. You must pass the block back; appending all of response.content, as above, does that.
A few details from the docs that affect agents:
- Custom instructions replace the default prompt. If you set
instructions, say everything the summary must keep. - Tools can break the summary. With tools defined, the model occasionally calls one during summarization, which gives a compaction block with
content: null. The docs suggest instructions telling the model to respond with text only. - Billing. Compaction is an extra sampling step. The top-level
usageexcludes it, so sumusage.iterationsto get the real total. - Caching. Put a
cache_controlbreakpoint at the end of the system prompt so it stays cached separately from the summary. - Thinking. Thinking blocks from before the compaction block are not carried forward. The summary is all the model has of that earlier work.
If you write your own summarizer instead, the same rules apply: decide what the summary must keep, and test it. Anthropic's post suggests tuning a compaction prompt on complex agent traces, first for recall, then for precision.
Step 6: Keep what matters outside the window
Clearing and compaction both lose detail. Anything the agent must not lose belongs somewhere the window can't touch.
Anthropic's post calls this structured note-taking: the agent writes notes to a file outside the context window, such as a NOTES.md, and reads them back later. Its example is Claude playing Pokémon, keeping tallies across thousands of game steps and reading its own notes after a context reset. On the Claude API, the memory tool (memory_20250818) does this, and the context editing docs say that when it is enabled, Claude gets a warning to save important information to memory as the context nears the clearing threshold. AI agent memory covers what to store and what to forget.
The same post describes a third technique: sub-agents. A sub-agent explores in its own clean window, possibly using tens of thousands of tokens, and returns a condensed summary, often 1,000 to 2,000 tokens. The main agent's window only pays for the summary.
Tell the model about the budget
Some Claude models track the budget themselves. The docs say Sonnet 5, Sonnet 4.6, Sonnet 4.5 and Haiku 4.5 receive their total budget in the system prompt and a remaining-token count after each tool call, injected by the API. Newer models don't get those tags. For them, task budgets (beta header task-budgets-2026-03-13) set an advisory token budget for a whole agentic turn under output_config.task_budget, with a minimum of 20,000 tokens. It is advisory: max_tokens is still the hard limit. If your code compacts history itself, the docs say to pass remaining on every request so the countdown doesn't reset.
Checklist
- Count all three input fields in
usage, not justinput_tokens. - Count tokens against the model you will call.
- Handle
model_context_window_exceededas a cut-off response. - Cap tool results and say what was left out.
- Return IDs and summaries first; load full records on request.
- Clear old tool results before summarizing anything.
- Use
clear_at_leastso a clear is worth the cache write. - Compact with instructions that list what must be kept, and test them.
- Keep plans, decisions and progress in notes outside the window.
- Track context size per task in your evals.
FAQ
What is context engineering for agents?
Anthropic's engineering team describes it as the set of strategies for curating and maintaining the best set of tokens during inference. For an agent, that means deciding what goes into the window on each turn: instructions, tools, history, retrieved data and tool results.
What is context rot?
It is the drop in a model's ability to recall information as its context grows. Chroma's report found performance changes with input length across 18 models, even on simple tasks.
Does prompt caching save context window space?
No. Anthropic's docs say cached and uncached input tokens all count toward the window. Caching lowers the cost of resending them, not their size.
Should I clear tool results or compact the history?
Start with clearing, which removes old raw results and keeps everything else as written. Compact when the history itself is too long, and keep critical facts in notes so a summary can't drop them.
What is the default compaction trigger on the Claude API?
For threshold compaction, the default trigger is 150,000 input tokens, and the lowest you can set is 50,000.
Sources
- Anthropic, Effective context engineering for AI agents (engineering blog, September 29, 2025)
- Hong, Troynikov and Huber, Context Rot: How Increasing Input Tokens Impacts LLM Performance (Chroma research, July 14, 2025)
- Anthropic, Context windows (Claude API documentation)
- Anthropic, Token counting (Claude API documentation)
- Anthropic, Context editing (Claude API documentation)
- Anthropic, Compaction (Claude API documentation)
- Anthropic, Compaction at a token threshold (Claude API documentation)
- Anthropic, Task budgets (Claude API documentation)