
Context Compaction: Run Claude Agents Past 200K Tokens
Summary
Use Anthropic's compact-2026-01-12 beta so long agentic loops survive past the 200K context window.
When Anthropic corrected its Claude Sonnet 5 launch numbers on July 1, 2026, the interesting detail was not the higher BrowseComp score. It was how they got it: a 10-million-token run with context compaction and programmatic tool calling. A single agent chewed through 50x the model's context window and still finished the task. That one line sent a lot of developers looking for the same trick, because most long agent loops die well before they get interesting.
The failure mode is boring and universal. Every turn of an agent resends the whole transcript. Tool results pile up, input tokens climb linearly, cost climbs with them, and somewhere around 200K tokens the request stops fitting. Anthropic calls the quality side of this context rot: even when it fits, a bloated transcript makes the model slower and less accurate. Compaction is the fix, and as of the compact-2026-01-12 beta it runs server-side in a couple of lines.
This guide shows you how to turn it on, tune when it fires, cap a total token budget, keep the summary from wrecking your prompt cache, and avoid the two gotchas that bite people on day one. Every snippet is written against the live Messages API so you can paste and run it.
Prerequisites
- Python 3.10+ and an Anthropic API key set as
ANTHROPIC_API_KEY. - The Anthropic SDK:
pip install -U anthropic(0.74.1 or newer for the SDKcompaction_controlpath). - A model that supports compaction: Sonnet 5, Fable 5, Mythos 5, or Opus 4.6/4.7/4.8. This guide uses
claude-sonnet-5. - Basic familiarity with the tool-use loop (assistant returns
tool_use, you returntool_result).
Compaction is a beta feature. You opt in per request with the beta header compact-2026-01-12 (passed as betas=["compact-2026-01-12"] in the Python SDK) and by adding the compact_20260112 strategy to context_management.edits.
Step 1: See the problem before you fix it
Take a mundane agentic job: process a queue of support tickets, where each ticket needs a classify, a knowledge-base search, a priority, a route, and a drafted reply. Anthropic's own cookbook ran exactly this over five tickets with no compaction. Input tokens grew in a straight line because every tool result stayed in the transcript:
Turn 1: Input= 1,537 | Messages= 1 | Cumulative In= 1,537
Turn 16: Input= 4,894 | Messages=31 | Cumulative In= 50,911
Turn 27: Input= 7,196 | Messages=53 | Cumulative In= 118,752
Turn 37: Input= 9,475 | Messages=73 | Cumulative In= 204,416
BASELINE (NO COMPACTION): input 204,416 | output 4,422 | total 208,838
Five tickets, 37 turns, and you have already blown past 200K input tokens, most of it ticket #1's data still riding along while you work ticket #5. Turn the same run into a compacting run and total tokens drop by roughly 59% while the task still completes. That is the number worth chasing.
Step 2: Turn on server-side compaction
Server-side is the recommended path. You do not write any summarization code. When input tokens cross a threshold, the API pauses, writes a <summary> of the conversation into a special compaction block, and continues from there. On the next request it silently drops every block before the latest compaction block. Here is the whole thing:
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Help me build a Python web scraper"}]
resp = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-sonnet-5",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
# Append the full response. Any compaction block is included automatically,
# and you MUST pass it back so the API can continue from the summary.
messages.append({"role": "assistant", "content": resp.content})
That is the contract: append resp.content verbatim every turn. When a compaction block is present, the API ignores everything before it. You can leave the old messages in your list (the API drops them) or trim them yourself, keeping the compaction block onward. Either works.
A compaction block looks like this in the response content, sitting in front of the normal text and tool blocks:
{
"content": [
{"type": "compaction",
"content": "Summary of the conversation: The user requested a web scraper..."},
{"type": "text", "text": "Based on our conversation so far..."}
]
}
Step 3: Control when it fires
The default trigger is 150,000 input tokens. Override it with the trigger parameter. The only supported trigger type is input_tokens, and the value must be at least 50,000:
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 100000},
}
]
}
Pick the threshold to match your workload. Lower thresholds compact more often and keep the active context tiny, which suits sequential item-by-item processing where each item is independent. Higher thresholds preserve more raw detail between compactions, which suits tasks that reference earlier context. Rough guide:
| Threshold | Best for | Trade-off |
|---|---|---|
| 50K-80K | Sequential item processing (tickets, rows, files) | Frequent summaries, minimal context carried |
| 100K (near default) | General long-running agents | Balanced retention vs. cost |
| 120K-150K | Tasks needing lots of prior detail | Fewer compactions, higher per-call cost |
One trap: do not set the trigger so low that the summary itself immediately re-triggers compaction. The floor of 50,000 exists partly to prevent that.
Step 4: A real tool-using agent that never runs out of room
Compaction earns its keep inside a tool loop, where results accumulate fast. Below is a complete client-side agent loop. Notice there is nothing compaction-specific in the loop body beyond the two config lines: the API handles the summarizing, and because you always append resp.content, the compaction block flows back on the next call.
import anthropic
client = anthropic.Anthropic()
def search_runbook(query: str) -> str:
# Replace with real retrieval. Returns a long-ish string per call,
# which is exactly what makes context balloon over many steps.
return f"[runbook excerpt matching '{query}': ...800 tokens of text...]"
TOOLS = [{
"name": "search_runbook",
"description": "Search internal runbooks and return the most relevant excerpt.",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
}]
messages = [{
"role": "user",
"content": "Audit all 40 of our runbooks for steps that reference the "
"deprecated v1 API. Check each runbook and list every stale step.",
}]
while True:
resp = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-sonnet-5",
max_tokens=4096,
tools=TOOLS,
messages=messages,
context_management={"edits": [{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 60000},
}]},
)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
break
tool_results = []
for block in resp.content:
if block.type == "tool_use":
output = search_runbook(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
})
messages.append({"role": "user", "content": tool_results})
# Final answer
print(next(b.text for b in resp.content if b.type == "text"))
Run this over 40 runbooks and input tokens sawtooth instead of climbing forever: they rise until the 60K trigger, snap back to the size of the summary, then rise again. The agent walks through all 40 without hitting the context ceiling. Here is what the sawtooth looks like in practice, from a compacting run of the same ticket workflow above:
Turn 16: Input= 4,934 | Messages=31 | Cumulative In= 51,087
== Compaction occurred! Messages: 31 -> 1 ==
Turn 17: Input= 1,774 | Messages= 1 | Cumulative In= 52,861 <- context reset
Turn 24: Input= 4,914 | Messages=15 | Cumulative In= 77,152
== Compaction occurred! Messages: 15 -> 1 ==
Turn 26: Input= 2,942 | Messages= 3 | Cumulative In= 82,171
WITH COMPACTION: total 86,446 tokens (vs 208,838 baseline -> 58.6% saved)
Step 5: Cap the total token budget
Compaction lets an agent run effectively forever, which is also the danger: a stuck agent can burn money indefinitely. Combine pause_after_compaction with a compaction counter to enforce a hard ceiling. With the pause flag set, the API stops right after writing the summary and returns stop_reason == "compaction", handing control back to you before it continues.
TRIGGER = 100_000
TOTAL_BUDGET = 3_000_000
n_compactions = 0
resp = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-sonnet-5",
max_tokens=4096,
messages=messages,
context_management={"edits": [{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": TRIGGER},
"pause_after_compaction": True,
}]},
)
if resp.stop_reason == "compaction":
n_compactions += 1
messages.append({"role": "assistant", "content": resp.content})
# Each compaction roughly means TRIGGER tokens were consumed.
if n_compactions * TRIGGER >= TOTAL_BUDGET:
messages.append({
"role": "user",
"content": "You are over budget. Wrap up and summarize the final state.",
})
The pause is also where you preserve recent turns verbatim instead of letting them get summarized. Grab the compaction block, then re-insert the last few real messages after it, so the model keeps its freshest context in full detail while everything older collapses into the summary:
if resp.stop_reason == "compaction":
compaction_block = resp.content[0]
preserved = messages[-3:] if len(messages) >= 3 else messages
messages = [{"role": "assistant", "content": [compaction_block]}] + preserved
# Continue the turn with compacted context + preserved recent messages
resp = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-sonnet-5",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
Step 6: Keep the prompt cache alive
Compaction and prompt caching are complementary, but a naive setup makes them fight. When a summary is written it becomes new content that has to be cached, and without a separate breakpoint it invalidates your cached system prompt too, forcing a full re-cache. Put a cache_control breakpoint at the end of your system prompt so it stays cached independently of the churning conversation:
resp = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-sonnet-5",
max_tokens=4096,
system=[{
"type": "text",
"text": "You are a meticulous runbook auditor...",
"cache_control": {"type": "ephemeral"}, # cached separately
}],
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
You can also cache the summary itself by attaching cache_control to the compaction block when you pass it back. Now a compaction event writes only the new summary to cache and reads the system prompt from cache, instead of re-billing both.
Custom summary instructions
The default summary prompt tells Claude to write everything needed to resume the task inside <summary> tags. You can replace it entirely with the instructions field to preserve exactly what your task cares about (code, IDs, decisions). Note that custom instructions replace the default, they do not add to it:
"edits": [{
"type": "compact_20260112",
"instructions": (
"Summarize the transcript inside <summary></summary> tags. Preserve every "
"runbook name, each stale step found, and file paths. Do not call any tools "
"while writing this summary; respond with text only."
),
}]
Step 7: Fix your cost tracking
Compaction quietly breaks naive billing math. The summarization step is an extra sampling pass with its own tokens, and the top-level usage.input_tokens and usage.output_tokens no longer include it. With the beta enabled, every response carries a usage.iterations array; a compaction entry appears only when a new compaction fired that turn. To get true total cost, sum across iterations:
def billed_tokens(resp):
iters = getattr(resp.usage, "iterations", None)
if not iters:
return resp.usage.input_tokens + resp.usage.output_tokens
return sum(i.input_tokens + i.output_tokens for i in iters)
# usage.iterations example when a compaction fired this turn:
# [
# {"type": "compaction", "input_tokens": 180000, "output_tokens": 3500},
# {"type": "message", "input_tokens": 23000, "output_tokens": 1000},
# ]
Re-applying a compaction block you already have costs nothing extra; only a brand-new compaction adds the summarization pass. Also useful: count_tokens applies existing compaction blocks so you can see your effective context size, and it returns context_management.original_input_tokens to show what it was before.
Alternative: SDK compaction with a cheaper summarizer
Server-side compaction always summarizes with the same model you are running. If you want Sonnet 5 to do the work but a cheap model to write summaries, use the SDK's tool_runner with compaction_control instead. It runs the summary client-side, so you can point it at Haiku:
runner = client.beta.messages.tool_runner(
model="claude-sonnet-5",
max_tokens=4096,
tools=tools,
messages=messages,
compaction_control={
"enabled": True,
"context_token_threshold": 60000, # default is 100000
"model": "claude-haiku-4-5", # cheap summaries
# "summary_prompt": "..." # optional custom prompt
},
)
for message in runner:
... # runner drives the tool loop and compacts automatically
Use server-side when you want the least code and the most accurate token accounting. Use the SDK path when you need an older model or a cheaper summarizer. Both implement the same idea: summarize, discard the raw history, resume from the summary.
Common pitfalls
- Server-side web search and extended thinking do not play well with compaction. Cache tokens accumulate across server-side sampling loops and can trip the trigger on cached content rather than real conversation. Compaction shines with client-side tools; be cautious mixing it with server tools.
- Compaction can fail when tools are defined. Occasionally the model calls a tool during the summary step instead of writing text, and you get a compaction block with
content: null. Prevent it with an explicit instruction: do not call any tools while writing the summary, respond with text only. - You will lose detail on purpose. Summaries keep IDs, categories, decisions, and next steps; they drop full tool-result text and reasoning. If a task needs a complete audit trail of every raw result, do not compact it, or raise the threshold.
- Custom instructions replace, not extend, the default. If you pass
instructions, you own the whole prompt, including the reminder to wrap output in summary tags. - Trigger value has a floor of 50,000. Anything lower is rejected, and setting it near the floor risks the summary re-triggering compaction.
- Always append the compaction block back. Drop it and the API loses the summary, restarting the conversation from a truncated, broken state.
Quick reference
| Item | Value / meaning |
|---|---|
| Beta header | compact-2026-01-12 |
| Strategy type | compact_20260112 (in context_management.edits) |
| Default trigger | 150,000 input tokens (min allowed: 50,000) |
| pause_after_compaction | Stop after summary; stop_reason == 'compaction' |
| instructions | Custom summary prompt; replaces the default entirely |
| Supported models | Sonnet 5, Fable 5, Mythos 5, Opus 4.6/4.7/4.8 |
| True cost | Sum resp.usage.iterations, not top-level usage |
| Summarizer model | Same model (server-side) or any model (SDK compaction_control) |
Next steps
- Wrap the Step 4 loop with the Step 5 budget cap and run it against a real backlog of items to watch the sawtooth in your own logs.
- Pair compaction with programmatic tool calling (returning tool output as data the model queries, not raw text) to push effective runs toward the 10M-token range Anthropic demonstrated.
- Add a
cache_controlbreakpoint on both the system prompt and the compaction block, then compare billed tokens with and without it. - For chat apps without tools, port the same pattern by hand: track tokens, request a summary at your threshold, replace history with the summary, continue.
Compaction is not a clever prompt trick. It is the boring infrastructure that turns a demo agent into one that can grind through forty runbooks, a hundred tickets, or a ten-million-token research task without falling over at the context wall.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.