Context engineering: what to put in the window and where
Context engineering decides which tokens a model sees on each call. How to budget the context window, order it for caching, and load what the model needs late.
- Published
- Reading time
- 10 min read
In short
- Context engineering is the work of choosing which tokens go into a model's context window on each call, and in what order. Prompt wording is one part of it.
- Order the window from the content that changes least to the content that changes most: tools, system prompt, shared documents, memory, history, then the new turn. That order keeps provider caches warm and puts the question at the end, where models use it best.
- Give every component a token budget and measure it on every request. Tool definitions alone can take tens of thousands of tokens before the conversation starts.
- Load late by default. Keep identifiers such as file paths and queries in the window, fetch content when a step needs it, and preload only what nearly every request uses.
Context engineering is the practice of deciding which tokens go into a model's context window on each call, and in what order. It covers everything the model reads: the system prompt, tool definitions, retrieved documents, memory, conversation history, and the new message. Prompt engineering, the wording of instructions, is one part of it.
Anthropic's applied AI team defines context engineering as the set of strategies for curating and maintaining the optimal set of tokens during inference. The definition is useful because it makes the window a budget. Every token you add costs money and latency, and, as context rot shows, it can lower the quality of the answer too.
What context engineering covers
Context engineering covers every component of the context window, who controls it, and how often it changes. Each component fails in its own way, so each needs its own owner and its own budget. Most production problems trace back to one component growing without anyone deciding that it should.
| Component | Who controls it | How often it changes | Typical failure |
|---|---|---|---|
| Tool definitions | Platform team, MCP servers | Per release | Too many tools, overlapping descriptions |
| System prompt | Product team | Per release | Edge-case rules piled up over months |
| Shared reference documents | Content owners | Daily or weekly | Whole documents where a section would do |
| Memory and notes | The agent | Per session | Stale facts with no expiry |
| Conversation history | The user and the agent | Every turn | Old tool output that is no longer true |
| Retrieved for this turn | The retrieval system | Every turn | Twenty passages where three would do |
| New message | The user | Every turn | Vague requests the model has to guess at |
Prompt engineering asks how to phrase an instruction. Context engineering asks whether the instruction, the document, or the tool belongs in this call at all. On a single-turn task with fixed inputs the two are nearly the same. In an agent that runs for forty turns, the second question decides the outcome.
The order of the context window
Order the context window from the content that changes least to the content that changes most. Tool definitions and the system prompt come first, shared documents next, then memory and history, then whatever was retrieved for this turn, and the new question last. Two separate effects reward this order.
The first effect is cost. Provider prompt caches match exact prefixes, so anything that changes invalidates everything after it. Putting a timestamp or a user's name in the system prompt forces a full-price write on every request. Prompt caching covers the mechanics; the design rule is that volatility should increase as you read down the window.
The second effect is quality. The "Lost in the Middle" paper found that models perform best when relevant information sits at the beginning or end of the input, and worst when it sits in the middle. Anthropic's prompting guide gives the practical form: put long documents near the top and the query at the end, which it says can improve response quality by up to 30% in its tests, especially with several documents.
The two effects agree, which is convenient. Shared documents go high in the window because they are stable and long. The question goes last because it changes every turn and because models attend to the end.
Wrap each document in tags that carry its source, such as <document> with a <source> and a <document_content> element. The model can then cite where a claim came from, and you can tell from a logged request which document a bad answer drew on.
Give each component a token budget
Set a token budget for each component and measure the real count on every request. A budget turns "the prompt got long" into a specific component that grew past its limit, with an owner who can fix it. Without one, the window fills by accretion until quality or cost forces an emergency cleanup.
Tool definitions are the component teams underestimate most. Anthropic's engineering team described a setup with five MCP servers whose 58 tools consumed about 55,000 tokens before the conversation started. That is a large share of the input on every turn, spent before the model has read the user's question.
A budget for a support agent might look like this. The numbers are illustrative; yours come from your own traffic.
| Component | Budget | What happens when it is exceeded |
|---|---|---|
| Tool definitions | 4,000 tokens | Load tools on demand instead of all at once |
| System prompt | 2,000 tokens | Review and remove rules nobody can justify |
| Retrieved passages | 6,000 tokens | Return fewer passages after reranking |
| History | 20,000 tokens | Compact, as described under context rot |
Count before you send. Anthropic's token counting endpoint accepts the same input as a message request, including tools and system prompts, and is free to call. Its count is an estimate, so treat budgets as limits with a small margin rather than exact thresholds.
System prompts at the right altitude
A system prompt should state goals, constraints, and the shape of good output, at a level of detail the model can apply to cases you did not list. Anthropic calls this the right altitude: specific enough to guide behavior, general enough that it is not a brittle list of if-then rules.
System prompts fail at both ends. A prompt that reads like code, with a rule for every incident since launch, breaks on the next case nobody wrote down and grows with every bug report. A prompt that says "be helpful and accurate" gives the model nothing to act on.
Three habits keep a system prompt at the right altitude:
- Group it into labeled sections, such as background, instructions, tool guidance, and output format, so each part has an owner.
- Use a few varied, representative examples instead of a long list of edge cases. Anthropic recommends a diverse, canonical set of examples over stuffing in every exception.
- Delete a rule when you cannot name the failure it prevents. A rule with no known failure is context the model must read and weigh for nothing.
Tools are context too
Every tool definition the model can see is part of its context, read on every call. Keep the set small, make each tool's purpose unambiguous, and avoid two tools that do nearly the same thing. A model that has to choose between overlapping tools makes worse choices and spends tokens doing it.
Anthropic's guidance is to curate a minimal viable set of tools, each self-contained and clear about its intended use. When the set cannot be small, stop loading every definition up front. Anthropic reported that its tool search approach, which loads definitions only when the model searches for them, cut token use by 85% in its tests while keeping the full tool library available.
Gateways can do the same work for every agent behind them. When Bifrost, an open-source AI gateway by Maxim AI, acts as an MCP gateway, its Code Mode exposes connected servers as stub files and lets the model write a short script to call them, so full tool definitions stay out of the window; Maxim AI's published benchmarks report input tokens down by up to 92.8% across large tool sets. Tool calling and what an MCP gateway does cover the rest of the tool side.
Retrieve just in time, preload only the common case
Load content when a step needs it, not before. Put lightweight identifiers in the window, such as file paths, record IDs, stored queries, and URLs, and give the model tools to fetch the content behind them. Preload only content that nearly every request uses, because preloaded content is read on every call whether it helps or not.
Anthropic describes Claude Code as a hybrid. Project instruction files are placed in the context up front, while search tools let the agent find and read other files just in time. The split follows usage: the instructions apply to nearly every step, and any particular source file applies to few.
Just-in-time retrieval has its own costs:
- Each fetch is a tool call, which adds a model round trip and its latency.
- The model has to know what to look for. Good identifiers, such as descriptive file names and query names, are part of the context design.
- Retrieved content lands at the end of the window, after the cached prefix, so it is billed at full price each time.
Use the hybrid when a workload has both kinds of content. Preload the small, stable set that every step needs, and let the agent fetch the long tail.
Memory, history, and what survives between turns
History is what happened in this session. Memory is what the agent chooses to keep across sessions. Treat history as something to shrink and memory as something to curate, with a source and an expiry date on every entry.
History grows on its own, and the ways to shrink it, such as clearing old tool output, compacting the conversation, and handing side tasks to sub-agents with clean windows, are covered in context rot. The design point for context engineering is where those steps run. Compaction rewrites the start of the conversation, which invalidates the cached prefix, so trigger it at a threshold in large steps rather than trimming a little on every turn.
Memory is retrieval with a write path, and it fails the way any data store does. An agent that writes "the user prefers Postgres" in March will still read it in November. Store each memory with where it came from and when, load only the entries relevant to the current task, and let entries expire unless they are confirmed.
How to check what is in the context window
Log the assembled context for every request, with a token count per component, and review it the way you would review a slow database query. Most context problems are obvious once you can see the window, and invisible until you can.
Record at least these fields on each call:
- Token count per component: tools, system prompt, documents, memory, history, new message.
- Cached and uncached input tokens from the provider's usage fields.
- The identifiers of the documents and memories that were loaded.
- The prompt version, so a change in the window can be tied to a deploy.
Then plot quality against input size. If your evaluation score falls as the window grows, you have found the budget your components need. What to record on every request lists the standard attribute names for token counts, and LLM evaluation covers the score.
Frequently asked questions
What is context engineering?
Context engineering is the discipline of choosing what information a language model receives on each call and how it is arranged. It includes the system prompt, tool definitions, retrieved documents, memory, conversation history, and the user's message. The goal is the smallest set of tokens that lets the model do the task well, ordered so that provider caching works and the question sits where the model uses it best.
What is the difference between context engineering and prompt engineering?
Prompt engineering is about phrasing: how to word instructions and examples so a model follows them. Context engineering is about selection and arrangement: which instructions, documents, tools, and history belong in this call, in what order, and within what token budget. Prompt engineering is one part of context engineering. The difference matters most in agents, where the context changes on every step.
What is a context window in an LLM?
The context window is the maximum number of tokens a model can read and write in one call, covering the system prompt, tools, documents, history, the new message, and the response. Its size varies by model and is listed on each provider's model page. The usable size is smaller than the maximum, because quality tends to drop as the input grows long.
Does a larger context window remove the need for retrieval?
No. A larger window lets more text fit, but every token is billed and read on each call, and accuracy tends to fall as input grows. Retrieval selects the few passages a request needs, which keeps cost down and keeps distracting material out. Use the larger window for headroom and keep retrieving what each step needs.
How do you reduce context window usage?
Measure tokens per component first, then cut the largest one. Common fixes are loading tools on demand instead of all at once, returning fewer retrieved passages after reranking, clearing old tool results from history, compacting long conversations at a threshold, and moving rarely used documents behind a fetch tool. Keep the stable parts first so the remaining tokens are read from the provider's cache.
Where should the question go in a long prompt?
Put the question at the end, after the documents and context it refers to. Research on long contexts found models use information best at the beginning and end of the input, and Anthropic reports that placing queries after long documents improved response quality by up to 30% in its tests. This order also fits caching, since the question is the part that changes every turn.