Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

AI Engineering~13 min readIntermediate
Deep Dive

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.

01

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.

→ The one-line definition

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.

02

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:

Anatomy of one request's context
SystemSystem prompt — identity, rules, output contract. Small, stable, always present.
ToolsTool definitions — every schema the model might call. Grows fast; mostly unread.
ExamplesFew-shot examples — canonical demonstrations of the behavior you want.
KnowledgeRetrieved content — RAG chunks, files, search results, loaded just-in-time.
HistoryConversation / trajectory — prior turns, tool calls and their results.
MemoryPersistent memory — durable facts about the user or task, written across sessions.
RequestThe current message — the thing the user actually asked, often the smallest part.
Every segment is useful. Every segment steals budget from the others. That tension is the job.

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).

03

Why "just add more context" fails

Million-token windows tempt you to shovel everything in. Resist. Three separate forces punish an overstuffed window:

The three taxes on a fat context

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:

total prefill = s·(1 + 2 + … + K) = s·K(K+1)/2 = O(K²)   →   s=1000, K=50: 1,000·50·51/2 = 1,275,000 tokens

Now cap the window with compaction — summarize old history so the context never exceeds, say, C = 4000 tokens. The total goes linear:

with compaction: total ≈ K·C = 50·4,000 = 200,000 tokens   (6.4× cheaper, and it stops growing)

The longer the task runs, the wider this gap opens — quadratic vs linear.

→ Mental model

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.

04

The four operations

Nearly every context-engineering technique is one of four moves:

OperationThe moveIn practice
WritePersist 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.
SelectPull into the window only what this step needs.Retrieval, just-in-time file loading, choosing 3 relevant tools instead of exposing 40.
CompressShrink what must stay.Compaction (summarize the oldest history), truncating tool outputs, distilling documents to the lines that matter.
IsolateSplit 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.

05

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:

Context over an agent's lifetime
Turn 1Small, clean: system prompt + task + tools. The model is sharp.
Turn 12Tool outputs pile up. Trim aggressively: keep conclusions, drop raw dumps.
Turn 30Approaching the budget. Compact: summarize the oldest trajectory into a paragraph; keep recent turns verbatim.
Turn 50+Long-horizon: write durable notes to files/memory, isolate subtasks into sub-agents, reload state just-in-time.

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.

06

The craft, in six habits

Day-to-day, good context engineering looks like this:

Habits that survive production
AltitudeWrite the system prompt at the right altitude — firm on outcomes and guardrails, silent on micro-steps. Too rigid breaks on edge cases; too vague invites drift.
Tool dietExpose the minimum viable toolset. Every unused schema is dead weight; overlapping tools confuse the picker. If a human can't say which tool fits, neither can the model.
Canonical examplesA few diverse, canonical few-shots beat a laundry list of edge cases. Examples are pictures worth a thousand rules.
Cache-awareKeep the prefix stable — system prompt and tools first, volatile content last — so prompt caching keeps hitting and your prefill bill collapses.
Fresh over fullPrefer summaries of old state + verbatim recent state over a full verbatim history. Recency deserves fidelity; the past earns a précis.
MeasureEval context changes like code changes. A retrieval tweak or a compaction prompt can move quality more than a model upgrade — and can silently regress it, too.
07

The stack: prompt → context → loop → harness

Context engineering is one layer of a stack that's crystallized around building with models:

LayerQuestion it answersWhere to go deeper
Prompt engineeringHow do I phrase this instruction?The Prompting Handbook
Context engineeringWhat should the window contain at this step?You're here.
Loop engineeringHow does each output feed the next input — and when do we stop?Loop Engineering
Harness engineeringWhat 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."

RUN IT YOURSELF

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.

CPython · WebAssembly
By the numbers

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.

StepQuantityArithmeticResult
1Window on turn 15,000 + 2,0007,000 tokens
2Window on turn 20, keeping everything5,000 + 20 × 2,00045,000 tokens
3Input processed over 20 turns, keeping everythingsum of 5,000 + 2,000k for k = 1…20520,000 tokens
4Window on turn 20, trimmed5,000 + 19 × 200 + 2,00010,800 tokens
5Input processed over 20 turns, trimmedsum of 7,000 + 200(k − 1)178,000 tokens
6Saving from trimming alone520,000 ÷ 178,0002.92× less input
7Prefix that is identical in every call20 × 5,000100,000 tokens, 56% of the trimmed total, cache-eligible
8Put today’s timestamp at the top of the system promptthe prefix no longer matches between calls0 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.

Watch for

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.

In the wild

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 from CLAUDE.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.

Self-check

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.

Frequently asked

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).

Context Engineering · AI Engineering · Vibe Engines · 2026
Finished this one? 0 / 209 Handbooks done
NextThe Structured Outputs Handbook Next on the “Prompting and context” ladder · rung 3 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks