LLM Context Window Optimization: Practical Techniques
Count tokens before you send, cache stable prefixes, retrieve instead of stuffing, compact old turns and order long documents so the model can use them.
A bigger context window doesn’t mean you should fill it. Anthropic’s context window documentation says plainly that accuracy and recall drop as the token count climbs, and gives that effect a name: “context rot”. The Lost in the Middle paper, first posted in 2023, showed a related problem: where a fact sits in a long prompt changes whether the model finds it. So the practical work is less about squeezing more in and more about deciding what goes in, where it goes, and when it comes out again.
This guide covers six techniques that apply to any LLM API, with Anthropic and OpenAI docs as the reference points: counting tokens, caching stable prefixes, retrieving instead of stuffing, compacting history, ordering long documents, and clearing stale tool output. For chunking and reranking inside a retrieval pipeline, see the separate RAG context window management guide.
Know your limits first
Context sizes change with each model release, so read them from the vendor’s model table rather than from a blog post (this one included). As of the date above, Anthropic’s docs list a 1M-token context window for Claude Opus 5.5, Claude Sonnet 5.5, Claude Haiku 5.5, Claude Opus 4.7, Claude Sonnet 4.6 and several others, with up to 128k output tokens per request on those models. Older models, including the deprecated Claude Sonnet 4.5, have 200k.
Two details from the same page are easy to miss:
- Everything counts. The system prompt, every message, tool results, images, documents and tool definitions all use up the window, and so does the response the model writes, thinking included.
- Overflow behaves differently by model. If the input alone is too long, every model returns a 400 “prompt is too long” error. On Claude 4.5 and newer, a request whose input plus
max_tokensexceeds the window is accepted, and generation stops withstop_reason: "model_context_window_exceeded"if it runs out of room. Earlier models reject that request up front.
1. Count tokens before you send
Words and tokens don’t map one to one, and the mapping differs between vendors and even between model generations, so measure with the tokenizer your model actually uses.
For OpenAI models, the tiktoken library is the BPE tokeniser OpenAI publishes. It can look up the encoding for a given model:
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
n_tokens = len(enc.encode(document_text))
For Claude, use the token counting endpoint. It takes the same inputs as a normal message request (system prompt, tools, images, PDFs) and returns an input token total:
import anthropic
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-opus-5-5",
system="You are a scientist",
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(response.json()) # {"input_tokens": 14}
The endpoint is free, but it has its own requests-per-minute limit, separate from message creation. The docs call the result an estimate that can differ slightly from the real request. One trap matters when you switch models: Claude Opus 4.7 brought in a new tokenizer, and the same text produces noticeably more tokens on it and later models than on earlier ones. Anthropic’s advice is to recount against the model you’re moving to instead of reusing old numbers.
Once you can count, give each part of the request a budget (instructions, history, retrieved material, room for the answer) and enforce it in code.
2. Cache the parts that don’t change
Prompt caching doesn’t shrink the window. Anthropic’s docs are explicit that cached prefixes still occupy it. What caching does is make a large, repeated prefix much cheaper and faster to process, which changes how you weigh the cost of keeping long instructions or reference material in every request.
Both major APIs cache by prefix, so the rule is the same: put stable content first and variable content last.
Anthropic. You opt in with cache_control. The simplest form is one top-level field, which places the breakpoint on the last cacheable block and moves it forward as a conversation grows:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
cache_control={"type": "ephemeral"},
system="You are an AI assistant tasked with analyzing literary works. ...",
messages=[{"role": "user", "content": "Analyze the major themes in 'Pride and Prejudice'."}],
)
Things to know from the prompt caching docs:
- The prefix is built in a fixed order: tools, then system, then messages. A change at one level breaks the cache for that level and everything after it, so editing a tool definition invalidates the lot.
- The default cache lives for 5 minutes and is refreshed at no charge whenever it’s used. A 1-hour option costs more.
- Writing to the 5-minute cache costs 1.25 times the base input price; reads cost 0.1 times on most models, and less on some newer ones.
- Prompts below a per-model minimum length are silently not cached. If
cache_creation_input_tokensandcache_read_input_tokensare both 0 in the response, nothing was cached. - A breakpoint on a block that changes every request (a timestamp, the user’s message) never produces a hit. Put it on the last block that stays the same.
OpenAI. Caching is on by default for supported models. The OpenAI prompt caching guide says reuse requires the whole rendered prefix to match, and on GPT-5.6 and later models a prefix needs at least 1,024 tokens before it can be cached. Check cached_tokens in the usage data to see whether a request hit.
3. Retrieve instead of stuffing
If a document set is larger than the window, or changes often, or most of it is irrelevant to any one question, don’t paste it all in. Index it, pull the few passages that matter for the current query, and send only those. That keeps the window small and the signal high, which is exactly what context rot rewards.
Retrieval is a whole topic of its own. The RAG context window management guide covers chunk sizes and reranking, and frameworks such as LlamaIndex handle the indexing and retrieval plumbing. The point here is narrower: retrieval is a context-window technique first, because it decides what the model sees.
4. Summarise or compact old history
Long conversations and agent loops grow until something has to give. The common fix is to replace older turns with a summary and keep only recent turns verbatim. You can write that loop yourself: call the model to summarise the history, then start the next request from the summary.
Anthropic now offers it server-side as compaction, in beta. The model writes the summary on the server, so there’s no summarisation prompt to maintain. There are two modes:
| Mode | Who triggers it | What you change |
|---|---|---|
| On demand | Your code sends a compaction request | A loop that asks for the summary and puts the returned block first in messages |
| Token threshold | The API, when input reaches a level you set | One parameter on normal requests |
| Your own summariser | Your code | The summarisation call, its prompt and the history rewrite |
The docs recommend on-demand compaction where it’s available, and it can keep the last few turns word for word. If the default summary loses something a later turn needs, you can supply your own summarisation prompt.
5. Put long documents first and the question last
Order matters as much as size. The Lost in the Middle paper tested multi-document question answering and key-value retrieval and found models did best when the relevant text sat near the start or end of the input, and worse when it was in the middle. That held even for models built for long inputs.
Anthropic’s long-context prompting tips give concrete steps for inputs of 20k tokens or more:
- Put the long documents at the top, and the query, instructions and examples after them.
- Wrap each document in
<document>tags, with<document_content>and<source>subtags for metadata. - For long-document tasks, ask the model to pull out the relevant quotes first, then answer from those quotes.
<documents>
<document index="1">
<source>annual_report_2023.pdf</source>
<document_content>{{ANNUAL_REPORT}}</document_content>
</document>
</documents>
Analyze the annual report. Identify strategic advantages and recommend Q3 focus areas.
When you retrieve passages (technique 3), the same logic applies: put the strongest matches where the model is most likely to use them, not in the middle of a long list. The prompt engineering best practices post covers prompt structure more broadly.
6. Clear stale tool results and thinking
Agents that call tools pile up file contents, search results and command output that stopped being useful several turns ago. Anthropic’s context editing feature (beta, header context-management-2025-06-27) removes that material on the server before the prompt reaches the model:
clear_tool_uses_20250919removes the oldest tool results first once context passes a threshold you set, and leaves a placeholder in each one’s place. It can also drop the tool call inputs.clear_thinking_20251015controls how many earlier thinking blocks stay in context.
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"}]},
)
Your application keeps the full, unedited history; the editing happens only on the copy the model sees. The catch is caching: clearing tool results breaks the cached prefix at that point. The docs suggest the clear_at_least parameter so each clearing removes enough tokens to justify the new cache write. For long-running conversations in general, Anthropic points to compaction as the main tool and context editing for finer control.
How the techniques fit together
| Problem | Technique |
|---|---|
| Requests fail or get cut off | Count tokens and budget each part of the request |
| Same long instructions sent on every call | Prompt caching, stable content first |
| Corpus bigger than the window | Retrieval |
| Conversation keeps growing | Compaction or your own summariser |
| Model misses facts in long input | Documents first, question last, quote extraction |
| Agent context full of old tool output | Context editing |
Most production setups use several at once. A typical agent might cache its system prompt and tool definitions, retrieve documents per question, and compact or clear history as it runs. For the services that sit underneath these patterns, browse the LLM infrastructure category.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.