Context engineering explained: prompt engineering vs context engineering, context rot and how to fix it
Context engineering is the work of deciding everything a language model sees on each turn: the system prompt, examples, retrieved documents, tool definitions and results, the conversation history and memory files. Prompt engineering is one part of it, the wording of the instructions. It matters because long contexts degrade (context rot), so the fix is rarely a cleverer prompt. It is a smaller, fresher, better ordered context, built with four moves: select, compress, write and isolate.
What is context engineering?
Context engineering is deciding everything a large language model sees when it writes its next answer, and keeping that set small and useful. The context is not only your prompt. It is every token in the request: the system prompt and its instructions, a few examples, documents retrieved from a knowledge base, the definitions of the tools the model may call, the results those tools sent back, the conversation so far, memory files loaded from storage, and finally the user's new message.
Anthropic's engineering post Effective context engineering for AI agents defines context as the set of tokens included when sampling from a model, and calls context engineering the natural progression of prompt engineering. Its guiding principle is worth keeping on a sticky note: find the smallest set of high-signal tokens that maximizes the likelihood of the outcome you want.
To keep this concrete, we will follow one running example. Brightbox is a small home internet provider with an AI support assistant. On every turn, the assistant reads a long system prompt, the whole 40-page help center, 30 tools and the full conversation. On the first message it is excellent: Maya asks why her bill went up, and it answers with the right plan and the right price.
Forty turns later, after a long router troubleshooting session, it asks which plan she is on (she said it at turn 3), quotes a 14-day refund window from an outdated page (today's rule is 30 days), suggests restarting the router she restarted twenty minutes ago, and calls the wrong one of three look-alike account tools. Same model, same prompt. The context changed.
Context engineering vs prompt engineering
Prompt engineering is the craft of writing and organizing instructions: clear wording, a role, an output format, good examples. It mostly shapes one block of text that you write once and tune. Context engineering asks a different question on every turn: what should the model see right now? Its answers are retrieval, trimming, summarizing and splitting the work, as well as wording.
| Prompt engineering | Context engineering | |
|---|---|---|
| The question | How should I say it? | What should the model see right now? |
| Scope | The instructions | Instructions, documents, tools, history, memory |
| When | Written once, then tuned | Decided again on every turn |
| Typical fix | Reword, add an example | Retrieve, trim, summarize, split the work |
| How it fails | Vague or brittle wording | Missing, stale or buried information |
You need both. Good instructions still matter, and our guide to few-shot prompting covers how to pick examples. But a perfect prompt cannot rescue a context full of stale, buried or missing information. None of Brightbox's four symptoms is a wording problem.
Tokens and the context window in plain words
A token is a small piece of text that a model reads and writes: often a whole short word, sometimes part of a longer word, a space or a punctuation mark. Claude's glossary notes that tokens can be words, subwords, characters or bytes, and that the number of characters per token depends on the model and the language. The same text can therefore be a different number of tokens on different models; a token counting API gives the exact figure. Limits, speed and price are all measured in tokens.
The context window is all the text the model can look at while it writes a reply, including the reply itself. Claude's documentation calls it the model's working memory, as opposed to what it learned in training. Everything in the request counts toward it: the system prompt, every message (tool results, images and documents included), the tool definitions, and the output with any thinking.
One detail surprises many people. The model keeps nothing between calls. Your application sends the whole conversation again on every turn, so turn one is small, turn ten is bigger, and by turn forty Brightbox sends tens of thousands of tokens, mostly old troubleshooting logs. Windows are large today (up to a million tokens on some Claude models), so it fits. Whether the model still uses it well is another matter. Our guide to the LLM context window covers sizes and overflow behavior in more depth.
Context rot: why longer contexts get worse
Context rot is the decline in accuracy and recall as the token count grows. Claude's documentation puts it plainly: more context is not automatically better, so curating what is in context matters as much as how much space is available. Anthropic's post explains the mechanism with an attention budget. In a transformer, every token can attend to every other token, so n tokens create n² pairwise relationships, and each extra token thins the attention available to the rest.
Chroma measured the effect in its Context Rot report (July 2025), testing 18 models. Three findings map directly onto support bots and agents:
- Performance became less reliable as input length grew, even on simple tasks such as repeating a list of words.
- Even a single distractor, text that looks relevant but is not, reduced accuracy, and more distractors did more damage.
- On a long-memory benchmark, a focused prompt containing only the relevant part of a conversation scored significantly higher than the full conversation, across all models.
That third result is the Brightbox story in one line.
Lost in the middle: position matters too
An earlier paper, Lost in the Middle by Liu and colleagues, placed the information needed for an answer at different points in a long input. Models did best when it was near the beginning or the end, and significantly worse when it sat in the middle, even models explicitly built for long contexts. The tasks were multi-document question answering and key-value retrieval.
Put the research next to Brightbox and every symptom has a cause. Maya's plan, mentioned at turn 3, is now buried in the middle of a huge history. The outdated refund page is a perfect distractor. The steps she already tried are lost in old logs. And three overlapping account tools make the right choice ambiguous.
The four moves of context engineering
Most context engineering techniques fall into four moves. A common way to name them, used in LangChain's write-up on context engineering for agents, is write, select, compress and isolate. We will take them in the order Brightbox needs them.
| Move | What it means | Typical techniques |
|---|---|---|
| Select | Bring in only what this turn needs | Retrieval (RAG), just-in-time loading through tools, tool search |
| Compress | Keep the meaning with fewer tokens | Summaries, compaction, clearing old tool results |
| Write | Save information outside the window | Notes files, memory directories, case files |
| Isolate | Split work into separate contexts | Subagents with their own context window |
Two supporting habits apply to all four: put things in a sensible order, and design tools that do not waste context.
Select: retrieval and just-in-time loading
Brightbox pasted all 40 help pages into every request. The first fix is retrieval: split the help center into chunks, search them with the customer's question, and send only the few chunks that match. That is retrieval-augmented generation, explained step by step in What is RAG?. Two details fix the refund bug: remove or clearly label outdated pages so the old policy cannot come back, and store metadata such as the date and the plan so retrieval can filter on it.
The second fix is just-in-time loading: do not load data before you know you need it. Keep light references in context, such as Maya's account number or a ticket ID, and let the assistant fetch details with a tool at the moment it needs them. Anthropic's post describes this as keeping lightweight identifiers and loading data at runtime. Many agents use a hybrid: Claude Code, for example, loads CLAUDE.md up front and searches files with tools only when a task needs them.
Compress: summaries, compaction and exact facts
Compaction replaces the older turns of a long conversation with a summary, while the latest turns can stay word for word. Claude's API offers server-side compaction (in beta at the time of writing), and in Claude Code the /compact command summarizes the conversation on demand. The lightest form of compression is clearing old tool results: a router test from thirty minutes ago does not need to stay in full when a one-line note of what it found is enough.
Summaries have a known weakness: they drop exact details. "The customer had connection issues and tried some fixes" loses the plan, the router model and which steps were tried. So keep a short case facts block outside the summary, with exact values (plan, router, steps tried, policy version, next action), updated as the conversation goes and sent on every turn. It is small and never paraphrased. The guide to long-running agents shows the same pattern for agents that run for hours.
Write: notes and memory files outside the window
The write move saves information outside the context window so it survives when the window is cleared or compacted. An agent can keep a notes file or a memory directory. Claude's API has a memory tool for this: the model requests file operations (create, view, edit, delete) under a memories directory, and your application runs them against storage you control.
For Brightbox, the assistant writes a case file with the steps tried, their results and the next step. If Maya returns tomorrow, a fresh session reads that file instead of the whole old chat. Treat memory like a small database: keep it organized, expire stale files, and keep secrets and personal data out of it unless you have a reason and a policy.
Isolate: subagents with their own context
The isolate move gives a messy side task its own context. Brightbox wants to check outage logs near Maya's address, which means reading thousands of log lines that would flood the main conversation. Instead, the main assistant hands the task to a subagent. The subagent starts with a fresh, empty context, does the searching and filtering, and returns a short summary. Anthropic's post mentions condensed summaries of often 1,000 to 2,000 tokens.
The main context receives the answer, not the noise. The trade-off is more tokens overall and more moving parts, so isolate heavy work that splits off cleanly. Our pages on Claude Code subagents and multi-agent systems cover the design choices.
Order, position and prompt caching
Because of lost in the middle, order is a context engineering decision. Claude's prompting guide recommends placing long documents near the top of the prompt, above the question, instructions and examples, and reports that queries at the end can improve response quality by up to 30 percent in tests, especially with complex multi-document inputs. Put the most important fresh facts close to the question, wrap each document in tags with its source, and for long documents ask the model to quote the relevant parts before it answers.
Prompt caching, in one sentence: when the start of your request is identical between calls, the API can reuse it, which makes those calls faster and cheaper. That is another reason to keep stable parts first (tools, then the system prompt) and changing parts last. Cached tokens still count toward the context window; caching changes the price, not the size.
Tool design that saves context
Tools cost context twice: their definitions sit in every request, and their results land in the history. Anthropic's post warns about bloated tool sets with overlapping functionality, which is exactly Brightbox's three account lookups. Merge them into one tool with a clear name and description. Then make results small: return the six fields the assistant needs rather than the whole 200-line record, add filters and paging for lists, and return clear error messages instead of stack traces. The basics of tool calls are in Claude tool use explained.
When you have many tools, load their definitions on demand. Claude's tool search tool lets you mark tools as deferred; the model searches the catalog and loads only the few it needs. The documentation suggests it from about ten tools, notes that choosing the right tool gets harder past 30 to 50, and recommends keeping the three to five most used tools always loaded.
Finally, the system prompt itself. Anthropic's post asks for the right altitude: not a brittle list of if-this-then-that rules, not vague advice like "be helpful", but clear principles organized in sections. For examples, a few diverse, canonical ones beat a long list of edge cases.
Brightbox, before and after
| Turn 40 | Before | After |
|---|---|---|
| System prompt | Long, full of edge-case rules | Focused, in sections, with three example conversations |
| Knowledge | All 40 help pages, old refund page included | Three retrieved chunks with today's policy |
| Tools | 30 definitions, three overlapping | A few tools, small results, the rest deferred |
| History | 40 raw turns, plan lost in the middle | Summary of old turns, last turns word for word |
| Facts | Scattered across the chat | Case facts block near the question |
| Side tasks | Outage logs pasted into the chat | A subagent returns a short summary |
The new request is smaller, fresher and better ordered. Maya's plan sits right next to her question, the old refund rule is gone, and the assistant stops repeating fixes.
A context engineering checklist for agents and RAG apps
Building the context
- [ ] List every source of tokens, and measure each.
- [ ] Retrieve instead of pasting; remove stale documents.
- [ ] Load details just in time, through tools.
- [ ] Keep tools few and distinct, with small results.
- [ ] Compact old turns, but keep exact facts apart.
Running and testing it
- [ ] Write long-lived state to files.
- [ ] Send heavy side tasks to subagents.
- [ ] Documents first, the question last.
- [ ] Log the full request the model saw.
- [ ] Test long conversations at turn forty, not turn one.
Common context engineering mistakes
- "A bigger window fixes it." Bigger windows still rot; fitting is not the same as using.
- Everything, just in case. Every extra token is a possible distractor.
- Tools that return whole records. The history fills with noise the model must read on every turn.
- Summaries that drop numbers and dates. Plans, amounts and dates vanish unless kept apart.
- Memory that only grows. Stale notes become distractors of their own.
- Subagents that return everything they read. The noise comes straight back into the main context.
The best habit is to look at what the model actually saw. Each API response reports the tokens the request used, and in Claude Code the /context command shows what is filling the window. A small test set of long conversations, like Maya's, catches context problems that a first-message test never will.
Recap
Prompt engineering is how you word the instructions; context engineering decides everything the model sees, on every turn. Tokens fill a limited window, and long contexts rot: information in the middle is used less well, and distractors hurt. Select with retrieval and just-in-time loading, compress with summaries while keeping exact facts, write notes outside the window, and isolate heavy work in subagents. Then order the context well, cache the stable start, and keep tools small.
Sources: Anthropic, Effective context engineering for AI agents; Chroma, Context Rot; Liu et al., Lost in the Middle; Claude docs, Context windows; Claude docs, Glossary; Claude docs, Compaction; Claude docs, Memory tool; Claude docs, Tool search tool; Claude docs, Prompt caching; Claude docs, Prompting best practices; Claude Code docs, Subagents; Claude Code docs, Commands; LangChain, Context engineering for agents. Independent guide, not affiliated with Anthropic.
FAQ
What is the difference between prompt engineering and context engineering?
Prompt engineering is writing and organizing the instructions you give a model: the wording, a role, a format, examples. Context engineering is the larger job of deciding everything the model receives on each turn, including retrieved documents, tool definitions, tool results, conversation history and memory. Anthropic describes context engineering as the natural progression of prompt engineering. You need both.
What is context rot?
Context rot is the drop in accuracy and recall that happens as the number of tokens in a model's context grows. Chroma's Context Rot report tested 18 models and found performance became less reliable with longer inputs, even on simple tasks. A bigger context window lets more text fit, but the model does not use all of it equally well.
What are the main context engineering techniques?
Most techniques fall into four moves. Select brings in only what the turn needs (retrieval, just-in-time loading through tools). Compress keeps the meaning with fewer tokens (summaries, compaction, clearing old tool results). Write saves information outside the window (notes, memory files). Isolate splits work into separate contexts (subagents). Order and tool design support all four.
Does a bigger context window fix the problem?
No. A larger window means more text fits, but research such as Lost in the Middle and Chroma's Context Rot report shows that models use long inputs unevenly: information in the middle is used less well, and irrelevant but similar text acts as a distractor. Curating what goes in matters as much as how much space you have.
What is the lost in the middle problem?
In the Lost in the Middle paper, Liu and colleagues placed the relevant information at different positions in a long input. Models answered best when it was near the beginning or the end, and worst when it sat in the middle, even models built for long contexts. That is why the order of the context matters, not only its content.
Read next
- LLM Context Window Explained: Claude's Working Memory
- What Is RAG? Retrieval-Augmented Generation Explained
- Long-Running AI Agents: Keep Context, Facts and Progress
- Claude Code Tutorial for Beginners: Install to First Commit
- Git Worktree Explained: Work on Several Branches at Once
- Software Engineering Unpacked: home
- The CCAR-F video playlist on YouTube