AI, Data & Machine Learning
Context engineering: the discipline that replaced prompt engineering
Why context engineering replaced prompt engineering: retrieval quality, position bias, compaction and trust boundaries, grounded in the long-context research.
Key takeaways
- Context engineering is the practice of deciding what information reaches the model on each request — retrieval, tool definitions, history, instructions — rather than optimising the wording of a single prompt.
- A larger context window did not remove the problem. Attention across a long input follows a U-shaped curve against position — material in the middle is used measurably less well, a result established by Liu et al. in TACL and refined by later work.
- The main levers are retrieval quality, compaction of history, tool surface size and strict separation of trusted instructions from untrusted content.
- Most quality problems blamed on the model are context problems: the right information was not present, or was buried among irrelevant material.
- Treat the context window as a budget with a cost per token in latency, money and accuracy. Spend it deliberately.
Context engineering is the name the field settled on once it became clear that prompts were not the hard part. For about two years, the folk wisdom of working with language models was that the prompt was the artefact. People collected prompts, traded them, wrote guides about phrasing.
Then production systems arrived and the picture changed. The wording of the instruction turned out to account for a small share of the quality variance. What dominated was whether the necessary information was in the window at all, and whether it was findable among everything else in there.
That shift now has a name.
What the discipline covers
Context engineering is everything that determines the model's input on a given request:
- Instructions — the system prompt, the persistent behavioural rules
- Retrieved knowledge — documents, records, code, whatever the task needs
- History — prior turns, and how much of them survives
- Tool definitions — every available tool's name, description and schema
- Intermediate state — results of earlier tool calls, plans, scratchpad content
Each of these competes for the same finite budget, and each has a cost in latency, money and — the one people miss — accuracy.
Position bias is a measured property, not folklore
The claim that "where you put things in the window matters" has a research basis worth knowing, because it tells you how to arrange context rather than just that you should.
Liu et al. established the canonical result in Lost in the Middle: How Language Models Use Long Contexts, published in TACL: on multi-document question answering and key-value retrieval, model performance follows a U-shaped curve against the position of the relevant information. Accuracy is highest when the needed passage sits at the very start or the very end of the context and degrades measurably when it sits in the middle — in some configurations, performance with the relevant document mid-context fell below performance with no retrieved documents at all (TACL 2024).
Subsequent work attributes this to an intrinsic attention bias toward extreme positions rather than to anything semantic, and has produced calibration methods that partially correct it (arXiv:2406.16008). More recent work in 2026 develops a structural account of why transformers exhibit the bias (arXiv:2602.16837) and shows that correcting position bias alone is not sufficient to fix long-context retrieval behaviour (arXiv:2606.27793).
Three practical consequences follow directly:
- Rank properly and put the best material at the edges. If your retriever returns twenty passages in similarity order and you concatenate them, your best-but-not-first result is landing in the dead zone.
- Fewer passages is not just cheaper — it is more accurate. Shortening the context moves everything closer to an edge.
- A long-context model does not make retrieval quality optional. A large window changes what fits, not how attention is distributed across it.
Retrieval is the largest lever
For most systems, retrieval quality explains more of the output quality than any other single factor. If the answer is not in the window, no amount of instruction will produce it; if it is buried among nineteen near-misses, it often may as well not be.
The parts that matter in practice:
Chunking. Splitting by fixed token count is the default and usually the worst option. Split on structure — sections, functions, records — so a chunk is a self-contained thought rather than an arbitrary window.
Ranking, not just similarity. Vector similarity gets you candidates. A reranking pass over those candidates is consistently one of the highest-return additions to a retrieval pipeline, because "similar" and "relevant to this question" are different properties.
Hybrid search. Semantic search is weak on exact identifiers — error codes, part numbers, function names, proper nouns. Keyword search is weak on paraphrase. Almost every real system wants both.
Freshness. Stale retrieved content is worse than missing content, because it is confidently wrong. Re-indexing policy is part of the design, not an operational afterthought.
Fewer, better chunks. Returning five good passages beats twenty mediocre ones on accuracy, cost and latency simultaneously. This is the rare change with no trade-off.
Compaction: what to do with history
Any long-running session eventually exceeds its budget. The strategy you pick for that determines whether the system degrades gracefully or gets strange.
| Strategy | How it works | Where it fits |
|---|---|---|
| Truncation | Drop oldest turns | Simple chat where early context stops mattering |
| Summarisation | Compress older turns into a summary | Long conversations that need continuity |
| Structured state | Maintain explicit facts outside the window, reinject as needed | Agents with goals and long horizons |
| Checkpointing | Snapshot a clean state, restart from it | Long autonomous runs |
The failure to avoid is naive truncation on a session where the important constraint was stated in turn two. The model does not know it has forgotten; it simply behaves as though the rule never existed.
Tool definitions are context too
An easy one to miss: every tool available to the model occupies context on every single request, whether it is used or not.
A server exposing forty tools is spending a meaningful slice of the window on descriptions before any work happens, and giving the model forty options to choose wrongly between. Fewer, better-scoped tools consistently outperform exhaustive coverage — which is the same conclusion the MCP ecosystem has been converging on independently.
Agent memory: what to keep outside the window
Compaction answers what to do when a session outgrows its budget. Agent memory answers a harder question: what a system should still know next week.
The distinction matters because they are solved differently. Compaction is a summarisation problem inside one session. Memory is a storage and retrieval problem across many, and treating it as the former is why long-running agents feel amnesiac in some ways and cluttered in others.
Three layers are worth separating explicitly:
Working memory — the current window. Volatile, expensive, and the only thing the model can actually attend to. Everything else exists to decide what lands here.
Episodic memory — what happened before. Previous sessions, decisions taken, corrections the user made. The failure mode is storing raw transcripts and retrieving them by similarity: you get plausible-looking fragments of old conversations with no indication of whether they are still true.
Semantic memory — durable facts about the user, the account, the domain. "This customer is on the enterprise plan." "We decided against Postgres in March." These want to be structured records, not prose, because they need to be updated and invalidated rather than accumulated.
The practical guidance that follows:
- Write memory deliberately, not automatically. Systems that persist everything a user says accumulate contradictions. Something has to decide what is worth keeping, and "everything" is not a policy.
- Give facts an expiry or an owner. A stored preference from four months ago may be wrong. Without a way to invalidate it, the system confidently applies stale information — the same failure as stale retrieval, with a longer half-life.
- Retrieve memory the same way you retrieve documents. Rank it, budget it, and be willing to leave it out. Memory that always loads is just a longer system prompt with worse hygiene.
- Make it inspectable. When an agent behaves oddly, "what did it think it knew" is the first question. A memory store nobody can read is a debugging dead end.
Debugging a context problem
Most reports of "the model is bad" are context problems in disguise, and they resolve in a fairly reliable order. When quality is poor, work through this before touching the model or the prompt:
- Was the necessary information in the window at all? Log the assembled context, not just the prompt and completion. Roughly half of quality complaints stop here.
- If it was, where was it? Buried at position fourteen of twenty retrieved chunks is functionally close to absent. Re-rank and re-test before concluding anything about the model.
- How much irrelevant material was alongside it? Ablate: remove a source, re-run the evaluation set, see whether quality moves. If it does not, you were paying for tokens that did nothing.
- Is the instruction contradicted anywhere? A system prompt saying one thing and a retrieved document implying another produces behaviour that looks random and is not.
- Only then, change the prompt or the model. These are the two levers people reach for first and the two that least often explain the problem.
Trust boundaries are structural
Everything in the window looks the same to the model. Your carefully written system instruction and a sentence inside a retrieved document have no inherent difference in authority.
This is why prompt injection is not fixable by asking the model to ignore instructions in retrieved content. Beurer-Kellner et al. make the argument precisely in Design Patterns for Securing LLM Agents against Prompt Injections: their organising principle is that once an agent has ingested untrusted input, it must be constrained so that input cannot trigger any consequential action. The security property comes from the constraint on the action space, not from anything the model was told. Every pattern in that paper trades some agent generality for a provable limit on what an injection can achieve.
The mitigation is therefore structural:
- Label untrusted material explicitly as data, and keep it separate from instruction
- Give the model only the authority the task requires — not the union of everything it might need
- Gate consequential actions behind approval rather than trusting the model's judgement about when to take them
- Log what went into context, not just what came out, so an incident is diagnosable
This is covered in more depth in prompt injection and LLM security.
How to work on it
Treat context as a budget and instrument it like one.
- Measure composition. For a typical request, how many tokens go to instructions, tools, history and retrieval? The answer is often surprising, and frequently indefensible.
- Ablate. Remove a source and re-run your evaluation set. If quality does not drop, you were paying for nothing.
- Evaluate retrieval on its own. Before end-to-end quality, measure whether the right document is in the top five. Most "the model is bad" reports are retrieval failures wearing a disguise.
- Set a ceiling and hold it. Without one, context grows monotonically because every individual addition seems reasonable.
- Test long sessions specifically. Quality at turn one tells you nothing about quality at turn forty, which is where users actually live.
Building retrieval or agents that need to hold up?
Much of our AI, data and machine learning work turns out to be context engineering under a different name. We start by measuring what is actually in your window.
Budgeting context as a cost line
Because every token in the window is paid for on every request, context composition is a cost decision as much as a quality one — and the two usually point the same way, which is unusually convenient.
A useful exercise: take a typical request and account for where the tokens went.
| Component | Typical share | Question to ask |
|---|---|---|
| System instructions | Small, fixed | Is any of this restating what the model already does? |
| Tool definitions | Often larger than expected | Could half these tools be removed? |
| Retrieved material | Usually dominant | Would five well-ranked chunks beat twenty mediocre ones? |
| Conversation history | Grows unbounded | What is the compaction policy, and has anyone tested it? |
| Intermediate results | Spiky | Is the full tool output needed, or a summary of it? |
Most teams doing this for the first time find one component consuming a share nobody would defend if asked directly — commonly tool definitions, or retrieval returning far more than the model can use.
The good news is that trimming usually improves accuracy and latency at the same time as cost, because everything you remove moves the remaining material closer to the edges of the window where attention is strongest. This is one of the few places in engineering where the cheap option and the good option coincide, and it is worth exploiting deliberately rather than stumbling into.
Where to start if none of this exists yet
For a team with a working AI feature and no context discipline, the first three moves in order:
Log the assembled context. Not the prompt template — the actual bytes that went to the model, per request, with the retrieval scores attached. Almost nothing else is diagnosable without this, and most teams do not have it.
Build a small evaluation set. Thirty realistic inputs with acceptable outputs is enough to convert prompt changes from argument into measurement.
Measure retrieval precision separately. Ask only whether the necessary document made the top five. Fix that before touching anything else.
Everything further — compaction policy, tool surface pruning, memory design — is easier once those three exist, and mostly guesswork before.
Why the rename matters
It is easy to dismiss the terminology shift as fashion. It is not. "Prompt engineering" framed the work as writing — a thing one person does in a text box, iteratively, by feel. "Context engineering" frames it as systems design: a pipeline with retrieval, ranking, budgets, eviction policies, trust boundaries and observability.
The second framing is correct, and teams that adopt it stop trying to fix retrieval problems by rewording instructions.
Frequently asked questions
What is context engineering?
It is the practice of designing what information goes into a model's context window on each request and how it is arranged — the system instructions, retrieved documents, conversation history, tool definitions and any intermediate results. The shift in name reflects a shift in where the difficulty sits: in production systems, almost none of the quality variance comes from the phrasing of a prompt and almost all of it comes from whether the right material was present.
How is it different from prompt engineering?
Prompt engineering optimises a string a human wrote. Context engineering designs a pipeline that assembles the input at runtime, often from many sources, under a token budget. One is copywriting; the other is systems design with retrieval, ranking, caching and eviction policies.
Doesn't a bigger context window solve this?
It removes the hard ceiling, not the problem. Liu et al. showed in TACL that accuracy follows a U-shaped curve against where the relevant information sits — strongest at the beginning and end of the context, measurably weaker in the middle, in some cases falling below the no-retrieval baseline. Later work traces this to an intrinsic positional attention bias rather than anything about meaning. Long contexts also cost more and respond more slowly, so filling a large window because you can is a reliable way to get both a higher bill and a worse answer.
What is context rot?
It is the informal name for quality degrading as a context grows — through accumulated irrelevant history, stale retrieved material, contradictory instructions from different sources, and the model's own earlier mistakes being carried forward as though they were established facts. It is why long-running agent sessions tend to get worse over time rather than better, and why compaction strategies matter.
How do you stop untrusted content from hijacking an agent?
Structurally, not by asking it nicely. Keep a clear boundary between trusted instructions and retrieved or user-supplied content, label untrusted material as data rather than instruction, do not grant the model authority it does not need for the task, and gate consequential actions behind explicit approval. Prompt injection is not fully solvable at the prompt layer, so the mitigation has to be architectural.
How do you measure whether context engineering is working?
Evaluate retrieval separately from generation. Before asking whether the final answer was good, measure whether the necessary document appeared in the top handful of results for a set of realistic queries. If retrieval precision is poor, end-to-end quality scores tell you almost nothing about the model or the prompt, and effort spent on either is wasted. Once retrieval is sound, an end-to-end evaluation set run on every change becomes meaningful.
Is context engineering just a new name for RAG?
Retrieval-augmented generation is one component of it — an important one, often the dominant one, but not the whole discipline. Context engineering also covers how much conversation history survives, how many tools are exposed, how intermediate results are summarised, where trusted instructions sit relative to untrusted content, and how the whole assembly is budgeted. A system can have excellent retrieval and still perform badly because its tool surface is bloated or its history compaction discards the constraint that mattered.
How large should a context window actually be in production?
Smaller than you can afford, in almost every case. Long contexts cost more, respond more slowly, and place material in positions where attention is measurably weaker. The useful discipline is to set a ceiling, measure what each component contributes by removing it and re-running your evaluation set, and treat unexplained growth as a defect rather than an inevitability.
References & further reading
- [1]
- [2]
- [3]
- [4]
- [5]
- [6]Model Context Protocol specification ↗
modelcontextprotocol.io
- [7]
Related reading
Model Context Protocol (MCP): what it is and when it is worth adopting
What MCP is, when it beats a direct integration, and the tool-poisoning research you should read before connecting an MCP server to production data.
Why AI features take five times longer than the demo suggested
The demo took two days; shipping took four months. Where that time goes, why it is nobody's fault, and the questions that get you a realistic timeline.
Should your startup build AI features?
How to tell a genuine AI use case from a defensive one, what inference actually costs to run, and the failure modes that cost customers rather than money.