Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Context Engineering:
the right tokens, at the right time.
The best prompt in the world loses to a well-curated context window. Context engineering is the discipline that replaced prompt-tweaking: deciding what the model sees at every step — instructions, tools, retrieved knowledge, history, memory — and, just as deliberately, what it doesn't. Here's the whole craft in one sitting.
From prompts to context
For a couple of years, getting better output meant wordsmithing the instruction — prompt engineering. That still matters. But the moment you build anything real — a RAG app, a copilot, an agent — the instruction becomes a small slice of what the model actually reads. The rest is assembled by your system: tool definitions, retrieved documents, conversation history, memory, the last tool's output.
Context engineering is the art and science of filling the context window with just the right information at each step. The unit of optimization stops being the sentence and becomes the whole window — and in an agent, that window is rebuilt every single turn.
Prompt engineering asks "how do I phrase this?" Context engineering asks "what should the model see at this step — and what should it not?"
The term went mainstream in 2025–26 because everyone hit the same wall: models got smart enough that the bottleneck moved from the model's ability to reason to the system's ability to feed it the right material. Garbage in the window, garbage out of the model — no matter how good the model is.
What actually fills the window
Before optimizing the context, inventory it. A production request is a stack of segments, each competing for the same budget:
Two practical tools for feeling this tension: the Context Window Visualizer (watch the segments fight for space) and the Context Cost Planner (what that space costs in dollars and latency).
Why "just add more context" fails
Million-token windows tempt you to shovel everything in. Resist. Three separate forces punish an overstuffed window:
Attention tax
- Recall degrades as the window fills — context rot
- Middle content is recalled worst ("lost in the middle")
- Irrelevant or stale text actively distracts the model
Cost & latency tax
- Every token is prefill compute you pay for, every call
- Time-to-first-token grows with input length
- Long contexts break prompt-cache hits when they churn
The third force is subtler: behavioral drift. A window full of old errors, dead ends, and contradictory snippets teaches the model the wrong pattern for this turn — it imitates the mess. An agent that keeps every failed attempt in view gets worse at the task, not better.
The cost tax is quadratic — and that's the surprise
The cost tax isn't linear, it compounds. An agent that appends every turn without pruning holds roughly k·s tokens on turn k (s = tokens added per turn). You re-pay prefill on the whole window every turn, so the total input processed over K turns is a sum:
Now cap the window with compaction — summarize old history so the context never exceeds, say, C = 4000 tokens. The total goes linear:
The longer the task runs, the wider this gap opens — quadratic vs linear.
Treat attention as a budget, not a bucket. Every token you include is a claim that it's worth more than the token you left out. Spend deliberately; audit ruthlessly.
The four operations
Nearly every context-engineering technique is one of four moves:
| Operation | The move | In practice |
|---|---|---|
| Write | Persist information outside the window so it survives without occupying it. | Scratchpads and note files, durable memory stores, "write down what you learned" steps between turns. |
| Select | Pull into the window only what this step needs. | Retrieval, just-in-time file loading, choosing 3 relevant tools instead of exposing 40. |
| Compress | Shrink what must stay. | Compaction (summarize the oldest history), truncating tool outputs, distilling documents to the lines that matter. |
| Isolate | Split work so no single window carries everything. | Sub-agents with clean, task-scoped contexts that return only findings; sandboxes holding state outside the model. |
Notice what's not on the list: "buy a bigger window." Window size changes how much you can include; the four operations decide what you should.
Where it gets hard: agents
A single Q&A call is a one-shot packing problem. An agent is a packing problem that compounds: every loop iteration appends tool results, observations and decisions, and yesterday's clever context is today's rot. Long-horizon tasks force the full toolkit:
Two patterns do most of the work. Just-in-time retrieval: instead of pre-loading everything the agent might need, give it lightweight references (file paths, doc ids, queries) and tools to load them when needed — the way a human keeps tabs closed until they matter. Structured note-taking: have the agent maintain its own state file — objectives, decisions, open questions — that persists outside the window and gets pulled back after compaction.
This is also where context engineering meets loop engineering: the loop decides when to compact, when to spawn a sub-agent, when to re-read notes. The two disciplines are the software half of what the model's intelligence can't do alone.
The craft, in six habits
Day-to-day, good context engineering looks like this:
The stack: prompt → context → loop → harness
Context engineering is one layer of a stack that's crystallized around building with models:
| Layer | Question it answers | Where to go deeper |
|---|---|---|
| Prompt engineering | How do I phrase this instruction? | The Prompting Handbook |
| Context engineering | What should the window contain at this step? | You're here. |
| Loop engineering | How does each output feed the next input — and when do we stop? | Loop Engineering |
| Harness engineering | What orchestration code runs the loop safely — tools, retries, budgets, evals? | The AI Harness Roadmap |
They compose: the harness runs the loop, the loop reassembles the context, the context carries the prompt. Master one and the neighbors start mattering immediately — which is exactly why "prompt engineer" quietly became "AI engineer."
Pack a context window like a budget
"Treat attention as a budget, not a bucket" is a slogan until you pack a window. Here's the Select operation as code: a fixed token budget and ten candidate pieces (system prompt, the question, retrieved chunks, stale history, unused tool defs), each with a token cost and a relevance value. Two strategies fill the same budget — naive (keep pieces in arrival order, truncate) and engineered (rank by value-per-token, then fill). Run it and watch engineered capture more relevance with fewer tokens, by spending budget on signal instead of old turns. Change the items or the budget.
Worked example: a 20-turn agent, untrimmed vs trimmed
Say an agent’s prefix (system prompt plus tool definitions) is 5,000 tokens. Each turn, it calls a tool that returns 2,000 tokens. Once a result has been used, the trimmed version keeps only a 200-token conclusion. The numbers are illustrative; the arithmetic is exact.
| Step | Quantity | Arithmetic | Result |
|---|---|---|---|
| 1 | Window on turn 1 | 5,000 + 2,000 | 7,000 tokens |
| 2 | Window on turn 20, keeping everything | 5,000 + 20 × 2,000 | 45,000 tokens |
| 3 | Input processed over 20 turns, keeping everything | sum of 5,000 + 2,000k for k = 1…20 | 520,000 tokens |
| 4 | Window on turn 20, trimmed | 5,000 + 19 × 200 + 2,000 | 10,800 tokens |
| 5 | Input processed over 20 turns, trimmed | sum of 7,000 + 200(k − 1) | 178,000 tokens |
| 6 | Saving from trimming alone | 520,000 ÷ 178,000 | 2.92× less input |
| 7 | Prefix that is identical in every call | 20 × 5,000 | 100,000 tokens, 56% of the trimmed total, cache-eligible |
| 8 | Put today’s timestamp at the top of the system prompt | the prefix no longer matches between calls | 0 of those tokens hit the cache |
Trimming is the Compress operation, and it turned a window that grew by 2,000 tokens a turn into one that grows by 200. On turn 20 the model reads 10,800 tokens instead of 45,000, so it is cheaper and has less noise to get lost in. Steps 7 and 8 are the cache-aware habit in numbers. Over half of what you send can be served from the prompt cache, but only while the prefix stays byte-for-byte identical. One volatile line at the top throws all of that away.
Common mistakes
- Compacting away the constraints
A summary of turns 1–30 keeps what was done and drops what was asked: “stay on the current API version”, “don’t touch the migrations”. The agent then breaks a rule it can no longer see. Keep the task statement and hard constraints verbatim, outside the part that gets summarized.
- Deleting failures without a note
Keeping every failed attempt in view teaches the model the mess. But deleting them with no trace sends it straight back into the same dead end. Replace each one with a line in the notes: “tried X, failed because Y”.
- Volatile content at the front
Timestamps, request ids, the user’s name, or a tool list rebuilt in a different order on each request all change the prefix. Prompt caching matches the prefix exactly, so one changed byte near the top means a cache miss for everything after it. Stable first, volatile last.
- Passing raw tool output straight through
A 5,000-line log or a full HTML page goes into the window because the tool returned it. Shape output at the tool: the matching lines, counts, head and tail, plus a path or id the agent can use to load more if it needs to.
- Retrieval that returns the same thing five times
Top-5 chunks from three copies of one document, or from last year’s version and this year’s, fill the budget with repetition and conflicting facts. Deduplicate, filter by version or date, and rerank before packing.
Where this shows up in production and interviews
- Coding agents
Claude Code shows all four operations. It reads files on demand through tools instead of loading the repository (Select). It compacts long sessions with
/compact(Compress). It reloads durable project notes fromCLAUDE.md(Write). And it can hand a search to a sub-agent with its own window (Isolate). - Prompt caching on every major API
The large model APIs offer prompt caching: a repeated prefix is billed at a discount and returns its first token sooner. It is why “system prompt and tools first, volatile content last” is an engineering rule, not a style preference. The structure of the window sets the bill.
- Support and docs copilots
A RAG assistant is a Select problem on every request: which 5 of 50,000 chunks go in, plus the user’s account details and the last few turns. Most quality gains in these products come from retrieval, reranking and chunking, measured with evals, rather than from the instruction text.
- The interview version
In “design a chat assistant that supports long conversations”, walk through the budget. Say what is always in the window, what is retrieved, when history gets compacted, and where memory lives between sessions. Then show the O(K²) growth from the page and how compaction makes it linear.
Check yourself
Run the page’s numbers (s = 1,000 tokens per turn, C = 4,000 with compaction) to 100 turns instead of 50. How big is the gap now?
Untrimmed: 1,000 × 100 × 101 ÷ 2 = 5,050,000 tokens. Compacted: 100 × 4,000 = 400,000. That is 12.6× cheaper, up from 6.4× at 50 turns. Doubling the task length roughly doubles the ratio, because one side is quadratic and the other is linear.
Right after its first compaction, an agent starts retrying an approach it already ruled out. What went wrong?
The summary kept the progress and dropped the negative result. Before compaction, the failure was in the transcript. After, nothing in the window says “X doesn’t work”. The fix is to write it down: a notes file or a summary rule that keeps every ruled-out approach and the reason in one line.
Your system prompt never changes in meaning, yet the cache hit rate is near zero. Where do you look?
At the bytes before the first thing that varies. Common culprits are a date or request id in the system prompt, user-specific text placed before the tools, and tool definitions serialized in a different order each time. Caching needs an identical prefix, so move everything volatile to the end.
An agent with 40 tools keeps picking the wrong one. Longer tool descriptions, a bigger model, or something else?
Something else: Select. Expose only the handful of tools relevant to the current step, and merge tools that overlap so the choice is clear. Longer descriptions add tokens to every call and make the overlap harder to see. A bigger model still has to choose between 40 near-duplicates. If a human can’t tell which tool fits, the model can’t either.
Quick answers
What is context engineering?
The discipline of curating everything the model sees in its window — system prompt, tools, examples, retrieved knowledge, history, memory — so each inference step gets exactly what it needs and nothing it doesn't.
How is it different from prompt engineering?
Prompt engineering optimizes one instruction; context engineering manages the whole window over time — a budget allocated across competing sources, reassembled every turn in an agent.
Why doesn't a bigger window solve it?
Attention is finite: recall degrades as the window fills (context rot), middle content gets lost, and every token adds prefill cost and latency. Bigger windows raise the ceiling, not the quality.
What are the four operations?
Write (persist outside the window), Select (retrieve only what's relevant), Compress (summarize and trim to budget), Isolate (split across sub-agents with clean windows).
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agentic AI Interview HandbookTwenty topics every senior AI engineer should be able to reason about live — from eval pipelines to reliability patterns for generative systems.Read →
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →
- The Agent Patterns HandbookThe design patterns behind every LLM agent — the ReAct Thought–Action–Observation loop, tool/function calling, plan-and-execute, reflection, memory, multi-agent orchestration, and the failure modes (loops, hallucinated tools, recovery, human-in-the-loop) that break agents in production.Read →
- The Model Context Protocol (MCP) HandbookThe open standard connecting AI agents to the outside world — why M×N bespoke integrations collapse to M+N, the host/client/server roles over JSON-RPC, the three primitives (tools, resources, prompts), the connect→discover→call session lifecycle, when MCP earns its keep, and the security sharp edges (a server's output is untrusted input).Read →
- The Loop Engineering HandbookStop prompting your agents — design the system that prompts them for you. The inner vs outer loop, the four loop types (heartbeat, cron, hook, goal), the six building blocks (automations, worktrees, skills, MCP connectors, subagents, external memory), stopping conditions and the verification split, state across runs, cost engineering, and the six failure modes that burn tokens at 3am.Read →
- The Agent Skills HandbookPackaged, on-demand expertise for AI agents: what a skill folder actually is (SKILL.md + scripts + resources), progressive disclosure and why the system prompt couldn't do it, the skills vs tools vs MCP vs fine-tuning decision table, six habits of skills that actually trigger, and why third-party skills are supply-chain dependencies to review like code.Read →