What you will be able to do
- Explain why every API turn resends the full conversation and what that costs as tool results pile up
- Recognise how progressive summarization loses amounts, dates and customer-stated expectations, and keep those facts in a persistent case-facts block
- Trim verbose tool results to the relevant fields before they enter the history
- Structure aggregated inputs so findings in the middle are not lost
- Specify structured, metadata-rich outputs for upstream agents that feed a context-limited synthesizer
Key concept
Context rot — As a conversation or input grows, the model's accuracy and recall over that context decline, so a bigger window does not solve the problem. Choosing what goes into context, in what form and in what position, matters as much as how much room there is.
1.Every turn resends the whole conversation
A support agent built on the Messages API remembers nothing between requests. The API is stateless, so coherence across turns depends on your application sending the complete history (every user message, every assistant reply, every tool result) with each new request. Leave out an earlier turn and the model has never seen it. The customer's order number from turn three exists only if turn three is in the request.
That requirement has a cost. All of the request counts toward the context window: the system prompt, tool definitions, and every message, including tool results, images and documents. Each turn's input is all prior history plus the new message, and each response joins the input for the next turn. A forty-turn billing conversation therefore carries the full weight of its first thirty-nine turns on every call. The mechanics of how tool results are fed back are covered under Appending tool results to conversation history. What matters here is that whatever enters the history once is paid for, and competes for attention, on every later turn.
Running out of space is the obvious risk, but it is not the only one. As token count grows, accuracy and recall degrade, a phenomenon called context rot. More context is not automatically better, so the job is curation: deciding which facts must survive verbatim, which content can be trimmed, and where each piece sits in the prompt. The rest of this lesson covers those three decisions.
The model sees only that one message. The Messages API keeps no conversation state, so anything not in the current request, such as an order number or a promise made earlier, is unavailable. Coherence requires sending the full history every time.
Checkpoint 1 of 9· Check yourself
A support bot built on the Messages API sends the system prompt, its tool definitions and the customer's newest message on each request. By turn 12 it no longer knows the order number the customer gave in turn 3. Which change fixes this?
The Messages API keeps no state between requests, so the model sees only what is in the current request. A bigger window, a session ID or a higher max_tokens doesn't bring back turns your application never sent. Coherence comes from resending the full history every turn.
“The Messages API is stateless, which means that you always send the full conversational history to the API.”Source: platform.claude.com
2.Progressive summarization blurs the specifics
The usual answer to a growing history is to summarize it: condense older turns into a running summary and drop the originals. Server-side compaction and client-side SDK compaction both work this way. The SDK version has Claude write a structured summary and then replaces the full history with that summary. It keeps the conversation inside the window and keeps active context small. Summarization is also lossy by design, and what it loses first is the material a transactional conversation depends on.
Here is what a repeatedly summarized billing chat looks like after a few passes. The customer gave an exact order number, a refund amount of $214.88 and a deadline of the 15th. Each pass condenses the previous summary again, and three passes later it says "the customer wants a refund soon and mentioned an order from last month." Every number became an approximation and the stated expectation became "soon". Nothing went wrong with the model. Summarizing means trading precision for brevity, and amounts, percentages, dates and what the customer was promised are precise by nature.
Aggressive compaction can lose subtle but critical context whose importance only shows up later. A refund deadline is a good example. It looks like a detail until the day the customer says "you told me by the 15th." Neither of the obvious tweaks helps. Shortening the interval between passes means the oldest facts are re-summarized more often, not less. A bigger window with a later threshold postpones the first pass, but response quality degrades as the conversation grows, so the agent is working from a long and degrading context in the meantime. Asking the customer to repeat their details at every refresh hands your context problem to the customer.
Checkpoint 2 of 9· Check yourself
Turn 30 of a billing chat: the customer says, "You promised my $214.88 refund by the 15th." The agent's context contains the full system prompt and a running summary that has been condensed several times. The summary says only "customer wants a refund soon." What is the most likely cause?
Summarization is lossy by design. Each pass condenses the one before it, and exact amounts, dates and stated expectations are the first things to become approximations. The API drops nothing by itself: the application chose to replace the history with a summary, and no choice of summarizer model makes repeated condensing lossless.
“overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later”Source: www.anthropic.com
Checkpoint 3 of 9· Exam question
A billing support agent has been summarizing a lengthy chat every few turns to keep the prompt short. After the third summarization pass, the running summary reads "the customer wants a refund soon and mentioned an order from last month," even though the original messages contained an exact order number, a refund amount of $214.88, and a customer-stated deadline of the 15th. Which practice best addresses this failure mode going forward?
Correct answer: A — Store the order number, refund amount, and deadline in a structured record that is passed along with each summary
- A. Correct. Exact identifiers, amounts, and dates are kept in a structured record outside the narrative text, so condensing the conversation cannot blur them. The record goes to the model unchanged with each summary.
- B. Each extra pass condenses the earlier summary again, and that re-compression is how the order number, amount, and deadline were already lost. Shorter intervals add more passes, so precise values degrade faster, not more slowly.
- C. The customer already gave these details, and the loss happens in how the agent handles its own context. Re-sent values still go into the next summary, where they can be blurred again. The customer is also asked for information they already supplied.
- D. A larger window and a higher threshold only postpone summarization. In a lengthy chat the history will still be condensed at some point, and exact values can be dropped then. This also leaves the failure already observed unaddressed.
3.Keep transactional facts in a case-facts block
The fix is to separate the facts from the narrative. Extract transactional facts (order numbers, amounts, dates, statuses, customer-stated deadlines) into a structured case-facts block. Include that block in every prompt, and keep it outside the history that gets summarized. The summary still compresses the conversational flow, while the block carries the exact values untouched alongside it. This is structured note-taking applied to a support conversation: the agent persists notes outside the context window and pulls them back in when needed.
The built-in SDK summary prompt already shows that certain material needs special handling. Its final section, Context to Preserve, explicitly asks for domain-specific details and any promises made to the user. A case-facts block goes further by pulling that material out of the summary altogether, so no summarization pass can paraphrase it. Long-running agents show the same principle at scale. An agent playing Pokémon kept precise tallies across thousands of game steps in its own notes and carried on after context resets, and production research agents store essential information in external memory before moving to new tasks.
Multi-issue sessions need one more layer. When a customer raises a billing dispute on invoice #4821 for an $89.00 overcharge and then reports a workspace outage that started at 2:15 PM and is still unresolved, a single blended narrative eventually produces a reply about "the amount" that could refer to either issue. The fix is a separate context layer holding one structured record per issue:
- an identifier per issue (invoice #4821; the outage incident)
- the amount or value tied to that issue ($89.00 overcharge)
- the issue's own status and key timestamps (unresolved, started 2:15 PM)
Each issue keeps its own record, so every follow-up can be resolved against the right ID, amount and status, regardless of how the surrounding narrative was summarized.
Checkpoint 4 of 9· Check yourself
You are redesigning a billing agent whose running summary keeps paraphrasing refund amounts, invoice numbers and promised deadlines. Summarization has to stay, because the chats run long. Which design keeps those values exact on every turn?
Any value left inside the summary can still be paraphrased by a later pass, even when the summary prompt asks for it to be kept. A case-facts block held outside the summarized history, like notes kept outside the context window, carries the exact values unchanged into every prompt. A huge window only lets context rot set in, and asking the customer to repeat the details pushes your context problem onto them.
“Structured note-taking, or agentic memory, is a technique where the agent regularly writes notes persisted to memory outside of the context window.”Source: www.anthropic.com
4.Trim tool results before they accumulate
Tool results are the fastest-growing part of most agent histories, and their size has little to do with their relevance. Accumulated tool_result blocks consume the context window and, because the API is stateless, they are resent on every turn. A returns agent whose order-lookup tool returns 40+ fields per order (carrier metadata, warehouse codes, marketing tags) needs only about five of them to decide eligibility: status, purchase date, item, amount and return-window deadline. After a dozen lookups, the raw payloads dominate the window even though most of their tokens never matter.
Trim each result in code before it enters the history. Parse the response and pass the model only the fields the task needs. Tools should return information that is token efficient, and when you don't control the tool, the interception layer can enforce that. The hook point described in PostToolUse result normalization is a natural place to cut a 40-field order record down to its five return-relevant fields. The trimming has to be selective, field by field, which rules out two shortcuts:
- Truncating to the first N characters keeps whatever happens to come first, which may be carrier metadata, and can cut off the deadline entirely.
- Asking a second model call to summarize the payload brings back the blurring from progressive summarization, at the cost of an extra call.
- Caching full responses for reuse saves repeated tool calls but does nothing to shrink what has already entered the context.
Trimming at entry is complemented by clearing old results later. Server-side context editing with the clear_tool_uses_20250919 strategy removes the oldest tool results once context passes a threshold and replaces each with placeholder text. It is meant for results that are no longer needed once Claude has processed them. It runs before the prompt reaches Claude, and your client keeps the full, unmodified history. Use clearing for stale results and field-level trimming for fresh ones.
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
messages=[{"role": "user", "content": "Search for recent developments in AI"}],
tools=[{"type": "web_search_20250305", "name": "web_search"}],
betas=["context-management-2025-06-27"],
context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
)Checkpoint 5 of 9· Fill the gap
An agent built on web search keeps resending old search results it has already processed, and those results now take up most of each request. You want the API to replace the oldest tool results with placeholders once context passes a threshold, while your client keeps the full history. Which strategy type completes this request?
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
messages=[{"role": "user", "content": "Search for recent developments in AI"}],
tools=[{"type": "web_search_20250305", "name": "web_search"}],
betas=["context-management-2025-06-27"],
context_management={"edits": [{"type": " ? "}]},
)clear_tool_uses_20250919 is the server-side strategy that clears the oldest tool results past a threshold and puts placeholder text in their place. It handles stale results. Fresh results still need to be cut down to their relevant fields in code. Truncating or summarizing results are the shortcuts the lesson rules out, and clear_thinking applies to thinking blocks, not tool results.
Checkpoint 6 of 9· Exam question
A returns-processing agent calls an order-lookup tool that returns a JSON payload with 40+ fields (shipping carrier metadata, internal warehouse codes, marketing tags, etc.) for every order it checks, and after a dozen lookups the raw payloads dominate the context window even though only 5 fields (order status, purchase date, item, amount, return-window deadline) matter for return eligibility. What should the agent do before adding each lookup result to context?
Correct answer: A — Parse each lookup response in code and hand the model only status, purchase date, item, amount and return deadline
- A. Correct. Parsing the response deterministically and passing on only the five fields needed for the return decision keeps those values exact. What the model carries then depends on the fields it needs, not on how large the tool's payload is.
- B. A session cache only helps when the same order is looked up again. The agent still receives the full 40+ field payload for each new order it checks, so the bulky raw responses keep filling the window. Avoiding repeat calls does nothing about what each first lookup adds.
- C. A second model call adds cost and latency to every lookup, and a generated summary can reword or drop exact values such as the amount or return-window deadline. Those values must stay precise for the eligibility decision, so a deterministic field filter is the safer choice.
- D. A fixed character cutoff has no link to which fields matter. Depending on field order, it can keep carrier metadata and warehouse codes while cutting off the return-window deadline or amount. The result is unreliable for deciding eligibility.
5.Lost in the middle: structure aggregated inputs
Where a fact sits in a long input changes how likely it is to be used. In a 2023 study that placed a key fact at different positions in a long context, accuracy was highest when the fact was at the very beginning or very end and dropped by more than 30% when it was in the middle. This is the lost-in-the-middle effect, and it hits aggregated inputs hardest: five subagent reports concatenated into one document put three of them in the dead zone.
Two structural moves address the effect. First, open the aggregated input with a short key-findings summary covering every source: one or two lines each for market sizing, competitor pricing, regulatory risk, customer sentiment and distribution. Every finding then appears at the start, where recall is strongest, whatever its position in the detail. Second, organize the detailed results under explicit section headers. Delimiting sections with XML tags or Markdown headers, and wrapping each document's content and metadata in its own tags, makes every section easy to locate.
The fixes that look cheaper don't change positions. Moving the missed section to the end helps that one section and demotes whichever section takes its place in the middle. Splitting the input into two parts gives each part its own middle. Telling the synthesizer to re-read and check its draft adds a step but leaves the regulatory section exactly where the model is least likely to use it.
Checkpoint 7 of 9· Match them up
Your synthesis agent combines five subagent reports into one long input, and findings from the middle reports keep getting dropped. Match each proposed change to what it actually does to the lost-in-the-middle problem.
Tap a term, then the definition that fits it.
Moving, splitting or re-checking leaves some finding in the middle, where accuracy drops. Only a key-findings summary at the start plus clearly marked sections protect every finding, whatever its place in the detail.
“using techniques like XML tagging or Markdown headers to delineate these sections”Source: www.anthropic.com
Checkpoint 8 of 9· Exam question
A research assistant aggregates outputs from five subagents (market sizing, competitor pricing, regulatory risk, customer sentiment, distribution channels) into one long combined document that is then passed to a synthesis step. The synthesis step's final memo omits the regulatory risk finding, which appeared in the third of five sections in the middle of the document. What is the best way to structure the aggregated input to prevent this in future runs?
Correct answer: A — Open the combined input with a short summary of each subagent's key findings, and give each section its own clear heading
- A. Correct. A short summary up front puts the main findings in the high-attention opening of the input, and clear headings make each section easy to locate. Findings from the middle are therefore less likely to be dropped, whichever subagent produced them.
- B. This protects only the regulatory risk finding. In later runs a different section may fall in the middle, so the four remaining sections keep the same weakness. It leaves the long unstructured input unchanged.
- C. This changes only the prompt and leaves the input unstructured. Re-reading does not reliably offset the loss of mid-input content, and the long, flat document is still what the synthesis step has to work through. The question asks for a structural fix to the input.
- D. Splitting adds no summary or headings, so each part is still plain text with its own middle where findings can be lost. The synthesis step must also combine two separate inputs, which gives no reliable way to surface the key findings.
6.Upstream agents return structured facts, not reasoning
In a multi-agent pipeline, the synthesizer's context budget is shared by every upstream output, so the shape of those outputs determines what survives. A subagent may use tens of thousands of tokens exploring, but it should return only a condensed, distilled summary, often 1,000 to 2,000 tokens. Search detail stays isolated in the subagent, and the lead agent works on synthesis. When the downstream budget is tight, change the upstream agents to return structured data (key facts, citations, relevance scores) instead of verbose prose and the reasoning chain that produced it. The reasoning was useful to the subagent while it worked, but it is of no use to the synthesizer.
Compression only helps if the result can still be synthesized accurately, and that depends on metadata. Require every structured finding to carry its source location, the date of the information and the methodology behind it. Consider three pricing subagents that each return a plain paragraph of conclusions. When two of them disagree, the orchestrator cannot tell which price is current. If each finding carries its source and collection date, the conflict can be resolved, or at least reported accurately. Structured document metadata such as a <source> tag per document serves the same purpose in a prompt. Keeping claims tied to sources through synthesis is covered in Claim-source mappings. The rule for this lesson is that a compressed output without that metadata cannot support accurate downstream synthesis.
For large outputs there is a further step: subagents write their work to an external store and pass lightweight references back to the coordinator. This avoids the information loss of relaying everything through a chain of agents and saves the tokens spent copying large outputs through conversation history.
| Approach | What it does | Fits best when |
|---|---|---|
| Compaction | Summarizes a conversation near the limit and restarts with the summary | Tasks requiring extensive back-and-forth |
| Structured note-taking | Agent persists notes outside the context window and pulls them back in | Iterative development with clear milestones |
| Sub-agent architectures | Subagents explore in clean windows and return condensed summaries | Complex research where parallel exploration pays dividends |
Checkpoint 9 of 9· Match them up
Three pricing subagents feed a synthesizer that has a tight context budget. For each way the subagents could return their results, pick what it does for downstream synthesis.
Tap a term, then the definition that fits it.
A subagent should explore in its own context and return only a condensed result. That result supports accurate synthesis only if each finding carries metadata such as source, date and method. Very large outputs belong in an external store, with only a reference passed back to the coordinator.
“Each subagent might explore extensively, using tens of thousands of tokens or more, but returns only a condensed, distilled summary of its work”Source: www.anthropic.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“The Messages API is stateless, which means that you always send the full conversational history to the API.”
↩︎ Every turn resends the whole conversation“The Messages API is stateless, which means that you always send the full conversational history to the API.”
↩︎ Exam trap 4 - 2.
“every message in messages (including tool results, images, and documents)”
↩︎ Every turn resends the whole conversation“This makes curating what's in context just as important as how much space is available.”
↩︎ Every turn resends the whole conversation“As token count grows, accuracy and recall degrade, a phenomenon known as context rot.”
↩︎ Key concept“A larger context window allows the model to handle more complex and lengthy prompts, but more context isn't automatically better.”
↩︎ Exam trap 1 - 3.
“it keeps the active context small, because response quality degrades as a conversation grows.”
↩︎ Progressive summarization blurs the specifics - 4.
“replaces the full history with that summary”
↩︎ Progressive summarization blurs the specifics“Context to Preserve: User preferences, domain-specific details, and commitments made.”
↩︎ Keep transactional facts in a case-facts block“Older tool results (like file contents or search results) are no longer needed once Claude has processed them.”
↩︎ Trim tool results before they accumulate“Your client application maintains the full, unmodified conversation history.”
↩︎ Trim tool results before they accumulate - 5.
“overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later”
↩︎ Progressive summarization blurs the specifics“Structured note-taking, or agentic memory, is a technique where the agent regularly writes notes persisted to memory outside of the context window.”
↩︎ Keep transactional facts in a case-facts block“maintains precise tallies across thousands of game steps”
↩︎ Keep transactional facts in a case-facts block“it's extremely important that tools promote efficiency, both by returning information that is token efficient”
↩︎ Trim tool results before they accumulate“using techniques like XML tagging or Markdown headers to delineate these sections”
↩︎ Lost in the middle: structure aggregated inputs“returns only a condensed, distilled summary of its work (often 1,000-2,000 tokens)”
↩︎ Upstream agents return structured facts, not reasoning“the detailed search context remains isolated within sub-agents, while the lead agent focuses on synthesizing and analyzing the results”
↩︎ Upstream agents return structured facts, not reasoning“it's extremely important that tools promote efficiency, both by returning information that is token efficient”
↩︎ Exam trap 2“Each subagent might explore extensively, using tens of thousands of tokens or more, but returns only a condensed, distilled summary of its work”
↩︎ Checkpoint - 6.
“store essential information in external memory before proceeding to new tasks”
↩︎ Keep transactional facts in a case-facts block“This prevents information loss during multi-stage processing and reduces token overhead from copying large outputs through conversation history.”
↩︎ Upstream agents return structured facts, not reasoning - 7.
“Tool definitions and accumulated tool_result blocks consume your context window.”
↩︎ Trim tool results before they accumulate - 8.https://academy.claude.com/courses/ai-capabilities-and-limitations/try-it-out-q7hdjm9twcbtOfficial docs
“Accuracy was highest when the fact appeared at the very beginning or very end”
↩︎ Lost in the middle: structure aggregated inputs“dropped by more than 30% when it was buried in the middle”
↩︎ Lost in the middle: structure aggregated inputs“dropped by more than 30% when it was buried in the middle”
↩︎ Exam trap 3“Every piece of context you add pushes other pieces further into the middle — the attention dead zone.”
↩︎ Prediction - 9.https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practicesOfficial docs
“Structure document content and metadata with XML tags”
↩︎ Lost in the middle: structure aggregated inputs“wrap each document in <document> tags with <document_content> and <source> (and other metadata) subtags for clarity”
↩︎ Upstream agents return structured facts, not reasoning