Skip to content

5.1 Context Window Management

The context window is everything Claude reads on one request: instructions, the conversation so far, tool results and documents. Context window management means choosing what to put in the context window. Multi-turn conversations, multi-agent pipelines and long-document extraction all depend on context window management. Any reliable Claude-based system also depends on it. When context window management fails, support agents forget refund amounts, research pipelines drop citations, and extraction systems lose precision on the fields that matter most.

This lesson uses one made-up example throughout: a travel agency that runs its booking assistant on Claude. Over a long session, a customer gives a deposit amount, departure dates, a booking reference and the hotel’s promise of a sea view. Three research subagents check flights, hotels and transfers for a synthesis agent, which combines their results.

Progressive summarisation is a common strategy in long conversations. It replaces earlier turns with a shorter summary to free token budget. Progressive summarisation systematically destroys the most critical information in customer-facing and data-processing systems: numerical values, dates, percentages and customer-stated expectations. By default, a summary of transactional data keeps the general meaning and drops the specific details.

Consider turn 3 of a refund conversation.

Turn 3: "I'd like a refund of $247.83 for order #8891 placed on March 3rd"

After summarisation, the turn becomes this summary.

Summary: "Customer wants a refund for a recent order"

The summary has lost the amount, the order number and the date. The agent needs all three to process the refund. A summary of the agency’s session would also lose the deposit, dates, reference and sea view.

The fix is a persistent case facts block. Extract transactional facts (amounts, dates, order numbers, statuses) into a structured block included in every prompt, outside the summarised history. The block is never summarised, so it persists across every turn whatever happens to the history. For the agency, the block would hold the deposit, dates, reference and status. This example shows the structure of the block.

{
"caseFactsBlock": {
"customerId": "C-4421",
"issues": [
{
"orderId": "#8891",
"orderDate": "2024-03-03",
"refundAmount": "$247.83",
"status": "pending_refund",
"itemDescription": "Wireless headphones — defective"
}
]
}
}

When a customer raises several problems in one session, extract and persist structured issue data into a separate context layer, a part of the prompt kept apart from the summarised history. Each issue gets its own entry with order IDs, amounts and statuses. Separate entries prevent the data of one issue from mixing with the data of another issue during summarisation. A second agency booking with a misspelt name gets its own entry.

Models process information at the beginning and end of long inputs reliably. A model may miss findings in the middle of a long context, or may give them less weight. This effect is well documented in large language models. It guides how you structure aggregated inputs, which combine results from several sources.

The fix is a change to the structure of the input, not an instruction in the prompt. Put a summary of the main findings at the start of the aggregated input. Put the detailed results under explicit section headers. A reminder to read everything leaves each finding in the same position. The agency’s synthesis agent should get a “Key Findings Summary” first, then each supplier report under its own header. This layout shows the pattern.

## Key Findings Summary
- Source A: 12% market growth in renewable sector (2023)
- Source B: Patent filings increased 34% year-on-year
- Source C: Regulatory framework delayed until Q3 2025
## Detailed Findings
### Source A: Market Analysis Report
[Full details here...]
### Source B: Patent Database Analysis
[Full details here...]
### Source C: Regulatory Review
[Full details here...]

Tool results use context budget unnoticed. An order lookup might return 40+ fields, such as internal audit timestamps, warehouse codes, shipping carrier IDs and fulfilment centre identifiers. Most of these fields are irrelevant to a refund request. You need 5. The other 35 consume tokens in every subsequent turn as the history grows. The agency’s booking lookup has the same problem.

Trim verbose tool outputs to only the relevant fields before they accumulate in context. Trimming is required. Otherwise, output that is no longer needed accumulates turn after turn. This function keeps the relevant fields for a refund workflow.

def trim_order_result(raw_result, relevant_fields=None):
if relevant_fields is None:
relevant_fields = [
"order_id", "order_date", "total_amount",
"return_eligible", "item_description"
]
return {k: v for k, v in raw_result.items() if k in relevant_fields}

Trim the result in a PostToolUse hook or in the tool implementation itself, before the result enters the conversation history. Once verbose data is in the context, it stays there for every subsequent turn.

The Claude API is stateless. There is no server-side session state, so each request must include the complete conversation history. When you omit earlier messages, the model loses conversational coherence. The agency’s assistant resends the whole planning session each time.

This need for the full history conflicts with context limits. Coherence needs the full history, and the history grows every turn. The persistent case facts block resolves this conflict. It separates critical facts from the rest of the conversation, which can be summarised. So the agency can summarise the planning and keep every transactional detail.

In multi-agent systems, upstream agents often return verbose reasoning chains and raw content that downstream agents do not need. Suppose a synthesis agent with a limited context budget receives the full thought process of a research subagent. The synthesis agent then wastes tokens on reasoning that it cannot use.

Modify upstream agents to return structured data (main facts, citations, relevance scores) instead. Require metadata such as dates, source locations and methodological context in those outputs, to support accurate downstream synthesis. The agency’s hotel subagent returns findings with source and date, without its search steps.

{
"findings": [
{
"claim": "Renewable energy investment grew 12% in 2023",
"source": "IEA World Energy Report 2024",
"sourceUrl": "https://example.com/report",
"relevanceScore": 0.92,
"publicationDate": "2024-01-15"
}
]
}

Structured outputs also let downstream agents process findings without re-parsing verbose prose.

Prompt caching is the other way to control the cost of context. Trimming changes what the model sees. Caching instead lets you avoid paying to reprocess the parts that do not change. Mark a stable prefix (the start of the prompt that does not change) with a cache_control breakpoint. The API stores the processed prefix and reuses it on the next request. For cached tokens, the API charges a fraction of the input cost.

The cache matches the prompt from its start, prefix by prefix. So the layout of the prompt decides whether you get a cache hit, which is a match with a stored prefix. Put constant content first: system instructions, tool definitions, long reference documents. Place the cache_control breakpoint at the end of that static block. Put volatile content after it: the user’s latest message and anything that changes per request. The agency puts instructions, tools and booking terms first and the customer’s newest message last.

Put the static block in the top-level system parameter, not in messages. The cache reads the prompt in the order tools, system, messages. So the instructions in system are ahead of every turn that changes.

response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=4096,
system=[
{"type": "text", "text": LONG_STATIC_INSTRUCTIONS},
{"type": "text", "text": REFERENCE_DOC,
"cache_control": {"type": "ephemeral"}},
],
messages=[
{"role": "user", "content": dynamic_user_message},
],
)

If dynamic content is before the static block, the prefix changes on every request. Nothing matches, and you pay full price for every call. An ephemeral breakpoint lasts about five minutes from its last use. A {"type": "ephemeral", "ttl": "1h"} breakpoint lasts an hour, and its write cost (the price of storing the prefix in the cache) is higher. A request may contain at most four breakpoints.

A typical exam question describes an agent that loses amounts or dates after summarisation. The right fix is the persistent case facts block. Traps include telling the model to attend to everything and keeping full tool results as a precaution. Selective truncation is another trap, because the stateless API needs the whole history.

Five exam-style multiple-choice questions on Context Window Management. Pick an answer, then open the explanation.

A customer support agent handles a multi-issue session. After several turns, the agent refers to ‘your recent refund request’ instead of the specific $247.83 refund for order #8891. The conversation history is being summarised between turns. What is the most effective fix?

  • A. Increase the context window size to avoid summarisation entirely
  • B. Instruct the model to preserve all numerical values during summarisation
  • C. Keep a case facts block outside the summarised history itself
  • D. Store the full conversation in an external database and retrieve relevant turns on demand
Answer & explanation

Correct: C

  • A is wrong: Increasing the context window postpones the problem. Eventually it fills, and summarisation still destroys specifics.
  • B is wrong: Prompt-based instructions for summarisation are unreliable. The model will still compress details probabilistically.
  • C is correct: The persistent case facts block directly addresses the progressive summarisation trap by ensuring critical numerical and transactional data is never condensed.
  • D is wrong: This adds infrastructure complexity without addressing the core issue of which facts must persist in every prompt.

A research synthesis agent combines output from three subagents into a final report. Critical findings from the second subagent are consistently omitted from the synthesis. All three subagents produce high-quality outputs. Where should you look first?

  • A. The position of the second subagent’s output in the aggregated input — it may be buried in the middle
  • B. The synthesis agent’s context window — it may be running out of tokens
  • C. The second subagent’s prompt — it may not be formatting outputs correctly
  • D. The synthesis agent’s temperature setting — it may be too creative and ignoring details
Answer & explanation

Correct: A

  • A is correct: The lost-in-the-middle effect means models may miss findings buried in the middle of long inputs. Place key findings summaries at the beginning.
  • B is wrong: The issue is position-based attention, not context capacity.
  • C is wrong: The question states all three subagents produce high-quality outputs, so the formatting is not the issue.
  • D is wrong: Temperature affects randomness, not positional attention biases.

An order lookup tool returns 42 fields per result. The support agent only needs 5 fields to process a refund. After 8 turns, the agent’s responses become slower and less accurate. What is the root cause?

  • A. The model is hitting its maximum output token limit
  • B. The model needs a higher temperature to maintain creativity in long conversations
  • C. The order lookup tool is returning stale data after multiple calls
  • D. Untrimmed tool results are consuming the whole context budget
Answer & explanation

Correct: D

  • A is wrong: Output token limits affect generation length, not comprehension. The issue is input context consumption.
  • B is wrong: Temperature does not address context budget consumption.
  • C is wrong: Data staleness would cause incorrect information, not slower and less accurate responses across all topics.
  • D is correct: Each untrimmed 42-field result stays in the conversation history. Over 8 turns, that is 336 fields (only 40 of which are relevant) consuming tokens.

A developer builds a multi-turn support agent. They include only the last 3 messages in each API request to save tokens. Users report the agent ‘forgets’ context from earlier in the conversation. Why?

  • A. The model’s attention mechanism cannot handle conversations longer than 3 turns
  • B. The Claude API is stateless, so every request must carry the full history
  • C. The system prompt needs to instruct the model to remember earlier turns
  • D. The developer should use a different model with better long-term memory
Answer & explanation

Correct: B

  • A is wrong: The model can handle long conversations. The issue is that earlier messages are not being sent.
  • B is correct: The API is stateless. There is no server-side session state. Omitting earlier messages means the model literally does not have access to them.
  • C is wrong: The model cannot remember messages it was not given. Prompt instructions cannot recover missing context.
  • D is wrong: All API-based models are stateless. The issue is the developer’s truncation approach, not the model.

A multi-agent research pipeline has upstream research agents feeding findings to a downstream synthesis agent. The synthesis agent produces vague summaries without specific figures or citations. The research agents produce detailed, accurate outputs. What should you change?

  • A. Have upstream agents return structured data instead of verbose reasoning chains
  • B. Reduce the number of upstream agents so the synthesis agent has less input to process
  • C. Give the synthesis agent a larger context window to accommodate all research output
  • D. Add a summarisation step between research and synthesis to compress the research output
Answer & explanation

Correct: A

  • A is correct: Upstream agent optimisation ensures downstream agents receive structured, relevant data instead of verbose reasoning chains that waste context budget.
  • B is wrong: Reducing agents reduces research coverage. The issue is output format, not volume.
  • C is wrong: More context space does not help if the input is verbose reasoning chains that bury the key facts.
  • D is wrong: Adding summarisation would likely destroy the specific figures and citations, making the problem worse.