Delve · Field guide
Context Engineering: Deciding What the Model Sees
Prompt engineering tunes the sentence. Context engineering budgets the window — what enters, in what form, in what order, and what gets evicted.
Delve Editorial · AI Engineering · 10 min
#context-engineering #prompt-engineering #ai-agents #retrieval #evaluation
The short answer
Context engineering is the practice of deciding which tokens occupy an LLM's context window at each step — what goes in, in what form, and in what order — rather than only how an instruction is worded. It treats the window as a scarce budget to be written to, selected from, compressed, and isolated against a specific task.
The discipline appeared because the bottleneck moved. When most LLM work was single-turn, phrasing was the lever; once systems became agents that call tools and run for dozens of turns, the limiting factor became what the model can still see at step forty. A perfect instruction wrapped around a bloated, stale window still fails. The contested part is magnitude: everyone agrees curation helps, but how much long context genuinely degrades accuracy is still unsettled.
- Core unit The whole context window
- Working loop Write, select, compress, isolate
- Main enemy Attention dilution
01 · The definition
What the term names, and why it appeared when it did
Prompt engineering asks how to word an instruction. Context engineering asks a different question: given a fixed number of tokens the model can attend to at once, which ones earn a place, and which get evicted.
The working definition used by Anthropic is a set of strategies for curating and maintaining the optimal set of tokens during inference — including everything that lands in the window outside the prompt itself: tool schemas, retrieved documents, message history, memory files . That framing matters because it expands the object of design from a string to a state.
The term spread through practitioner writing rather than a paper. Andrej Karpathy's framing — filling the context window with just the right information for the next step — treats the window like RAM and the model like a CPU; LangChain popularised it and sorted the tactics into four moves . Vendors adopted it because their own products hit the problem first.
The rename tracks a shift in bottleneck. When most LLM work was one-shot classification or drafting, phrasing was the lever, so prompt engineering was the whole job. Once systems became agents — multi-turn, tool-calling, stateful — the limiting factor moved to what the model could still see at step forty. A flawless instruction wrapped around a bloated, stale window still fails. Prompt engineering is a subset of the larger problem, not a rival to it .
Scope remains genuinely contested: some writers use the term for any retrieval and orchestration work. The narrower sense — token selection and maintenance — is more useful.
The object of design stops being a string and becomes a state.
Attribution of the term is fuzzy; it emerged in practitioner posts across late 2024–2025 rather than in a single citable paper.
02 · The mechanism
The window is a budget, not a bucket
More competes for the window than the conversation. A typical production request carries system instructions; tool definitions and JSON schemas, which can consume thousands of tokens before any user text appears; retrieved passages; persistent notes or memory; the message history; and raw tool outputs — logs, file contents, API responses — that an agent pasted in and never cleaned up. Each has a different refresh rate and a different cost of being wrong.
The mechanism behind context rot is dilution. Attention is spread across the tokens present, so the same fact is easier to apply at 2K tokens than buried in 100K. Irrelevant material is not inert: it competes for the same budget and can pull generation toward plausible but wrong continuations. Models also show positional bias — material in the middle of a long input is used less reliably than material at the start or end.
Treat the magnitudes with suspicion. One preprint reports accuracy decaying sharply as input length grows even on simple retrieval tasks ; another claims an architectural add-on eliminates specific long-context failure classes . Both are early-stage, and S2's setup is idiosyncratic enough that it should not be generalised. What survives the dispute is directional and modest: adding tokens does not monotonically improve answers, and the ordering and salience of what you include changes outcomes.
The practical consequence is that context is a design surface, not a storage decision.
Benchmark-to-production generalisation is the weakest link: needle-in-a-haystack tests measure retrieval, while real agent work requires reasoning over the retrieved material.
03 · The method
Write, select, compress, isolate
The operable loop is four moves, and they are easier to hold in mind than any framework or vendor SDK . Each one attacks dilution from a different angle.
Write. Push durable state out of the window entirely: scratchpads, todo files, decision logs, structured state blocks. An agent that writes its plan to a file can recover it after compaction; one that keeps it in message history loses it the moment the transcript is trimmed.
Select. Pull in only the slice the current step needs. Anthropic's just-in-time pattern keeps lightweight identifiers — file paths, stored queries, links — in context and loads the payload through a tool at the moment of use . Retrieval quality, metadata filters, and tool design do the work here, and they matter more than raw window size.
Compress. Summarise resolved history, prune tool output before it re-enters, truncate deliberately. The cheapest compression is refusing to paste a 40KB log when the last twenty lines plus an error count answer the question.
Isolate. Split work across sub-agents so each receives a narrow brief and returns a condensed result. The parent's window stays small; the child's stays focused on one thing.
Close the loop with evaluation. A context change is an improvement only if a task benchmark moves — success rate, turns to completion, cost per task. Without that measurement you are optimising for how tidy the prompt looks.
The deliverable is a pipeline with budgets and tests, not a better sentence.
04 · The trade-offs
Why more context is not free
Every token is paid for twice: once in money and once in latency, both roughly scaling with prompt length, and the bill recurs on every step of a multi-turn agent. A twenty-turn agent carrying a 50K-token window re-reads on the order of a million tokens of prompt over the session. Caching and prompt-prefix reuse soften the price but do not remove the arithmetic.
The second cost is harder to see: confident wrongness. A bloated context produces plausible answers grounded in the wrong passage, and that failure is harder to debug than a bad prompt because nothing looks broken — the model had the information, just not the right information in the right place.
Boundary conditions decide whether any of this is worth building. For a single-turn classifier, extractor, or drafting task, prompt engineering is the entire job; there is one input, no history, no tools, and a context pipeline is over-engineering . Context engineering pays off when work is long-horizon, stateful, and multi-tool, and when correctness depends on facts accumulated over dozens of steps. The middle case — a two-turn support bot over a knowledge base — is mostly a retrieval-quality problem, and buying a larger window is usually the wrong fix.
One live disagreement: how much long-context degradation is intrinsic to attention versus an artefact of weak retrieval and badly designed benchmarks. Studies that control retrieval quality report smaller penalties, and model families differ sharply. The safe claim is that curation helps, not that long context is inherently harmful.
If you cannot name the metric a context change is supposed to move, you do not yet have a reason to make it.
05 · In practice
A context assembly pipeline for a support agent
Take an agent handling refunds across a 40-turn conversation with five tools. The assembly order has to be explicit, or it degrades into whatever the framework does by default.
Pinned every turn: identity and permissions, the policy clauses relevant to this customer's tier (a few hundred tokens, not the whole policy corpus), the schemas for tools callable on this turn, and a short structured state block — order ID, refund status, what has already been tried.
Retrieved on demand: help-centre articles and similar past tickets, fetched by query at the step that needs them, capped at a handful of passages with filters on product and date.
Filtered before re-entry: raw tool responses. A shipping API returning 8KB of tracking events becomes three lines and a status code before the model sees it again.
Compaction trigger: when history crosses a threshold, summarise the resolved portion into the state block and drop the transcript. For genuinely long-running work, a full reset with a handoff artifact can beat incremental compaction, because summarisation carries forward the same distortions it was meant to fix — a claim from practitioner notes rather than controlled study .
Sub-agents: a refund-eligibility check runs in a child holding only the order record and the policy excerpt, returning a verdict with citations.
The deliverable is a pipeline with per-section token budgets, a test set of real conversations, and a metric — resolution rate and cost per resolved ticket — that visibly moves when you change it.
The compaction-versus-reset trade-off is the least settled part of this pipeline; measure it on your own traffic rather than importing a rule.
Where context engineering sits
These are nested concerns, not competing philosophies — but they fail in different ways.
| Dimension | Prompt engineering | Retrieval (RAG) | Context engineering |
|---|---|---|---|
| Unit of work | One instruction | One query-to-documents lookup | The whole window, every step |
| Main lever | Wording, examples, format | Chunking, embeddings, reranking | Write, select, compress, isolate |
| Fails when | Task needs state across many turns | The needed fact is already in the conversation | No eval loop measures the change |
| Cost driver | Iteration time | Index size and retrieval latency | Prompt tokens per step |
| Best fit | Single-turn tasks | Static knowledge grounding | Long-horizon, multi-tool agents |
Common misconceptions
- Context engineering is a rebrand of prompt engineering. Prompt engineering optimises a message; context engineering optimises everything sampled alongside it — tool schemas, retrieved passages, history, memory. Wording a perfect system prompt cannot fix a window full of stale, irrelevant tool output.
- Million-token windows make the discipline obsolete. Larger windows raise the ceiling but not the quality of attention across it. Cost and latency still scale with tokens, and positional and dilution effects persist. Bigger windows change the budget; they do not remove it.
- Adding more retrieved documents improves accuracy. Past a small number of well-chosen passages, extra documents add distractors and can push accuracy down. Precision and ordering usually beat volume.
Build the pipeline, not the sentence
Four steps that turn context work from intuition into something you can test.
Inventory what is actually in the window
Log one real request and count tokens by category: system prompt, tool schemas, retrieved documents, history, raw tool output. Most teams find tool schemas and unfiltered outputs are the largest and least examined blocks.
Set a per-section budget
Assign explicit ceilings — for example 15% system and tools, 25% retrieved material, 40% history, 20% headroom — and enforce them in code. Budgets force the eviction decisions that otherwise happen by accident when a truncation cut lands mid-sentence.
Filter tool output before it re-enters
Write a thin adapter per tool that returns the three fields the agent actually needs plus a count of what was dropped. This single change typically removes the most tokens for the least engineering effort.
Measure against a fixed task set
Keep twenty to fifty real conversations as a benchmark. Track success rate, turns to completion, and cost per task before and after any context change. A change that improves tidiness but not the metric is not an improvement.
What would change my mind: Credible, replicated evidence that curated retrieval pipelines perform no better than simply dumping the full corpus into a large window at equal cost — that would collapse most of the discipline into prompt engineering plus a bigger bill.
Recall check
An agent performs well for eight turns and then starts repeating actions it already completed. Which explanation fits the context-engineering account best?
- The system prompt needs stronger, more emphatic wording
- The context window is too small and must be enlarged
- Accumulated history and tool output are diluting attention, so the state the agent needs is no longer salient
- The model's temperature is set too high
Repetition after many turns is the signature of state falling out of salience, not of a weak instruction. The fix is writing state to a durable artifact, filtering tool output, or compacting — not shouting louder in the system prompt.
Which task is the weakest case for building a context-assembly pipeline?
- A 40-turn support agent with five tools
- A single-turn ticket classifier with one input and no history
- A coding agent working across many files and sessions
- A research agent reconciling dozens of sources
With one input, no history, and no tools, there is nothing to select, compress, or isolate. Prompt engineering is the whole job, and a pipeline adds latency and complexity for no benefit.
What does the isolate move actually buy you?
- Each sub-agent gets a narrow context, so its attention is not split across unrelated material, and the parent receives a condensed result
- It permanently deletes old messages from storage
- It shrinks the model's vocabulary
- It removes the need for retrieval
Isolation is a scoping technique. The child works on a bounded brief with a clean window; the parent stays small because it receives a summary rather than the working transcript.
Open questions
- Does retrieval quality fully substitute for long context, or is there a residual penalty that no amount of curation removes? If curation is a full substitute, the engineering answer is always smaller windows plus better retrieval; if not, some tasks genuinely need raw context length.
- When should an agent compact its history versus reset with a handoff artifact? The two strategies have different failure modes and different costs, and the choice currently rests on practitioner anecdote rather than controlled comparison.
- What is the right unit of evaluation for a context pipeline — task success, cost per task, or turns to completion? Without an agreed metric, context changes get judged on how tidy the prompt looks, which rewards exactly the wrong optimisations.
Sources
- The Y -Combinator for LLMs: Solving Long-Context Rot with λ -Calculus - Tasks & Scaling Protocols — arXiv
- Eliminating Context Rot in Frozen LLMs: A Three-Mode Structural State-Coupling Architecture — Zenodo
- Context Engineering - Context Engineering — LangChain
- Effective context engineering for AI agents — Anthropic
- title: "Context Engineering" - title: "Context Engineering" — GitHub