Context Engineering
A language model only sees the tokens inside its fixed window. Context engineering chooses what goes in there: which rules, which history, which retrieved passages and which tool output, and what gets cut when they stop fitting.
Why Does This Exist?
Prompt engineering assumes the model already holds everything it needs, and the only open question is how you phrase the ask. That picture breaks the moment a system answers more than one self-contained question. Picture a support assistant mid-conversation: it needs its standing rules, the last dozen turns, two retrieved help-center articles, and the raw JSON the order lookup just returned. No sharper instruction rescues you if the order details never entered the window. A better sentence can't summon a missing fact.
That gap is what context engineering covers: deciding what the model actually sees when it reads your instruction. Wording still matters, and prompt anatomy covers how a single prompt is built. This page covers the assembly around it: the four lanes competing for one fixed budget, the order you trim them in, and why fitting is still not enough. The frame itself is context windows. The token math is context budgeting. The reason a full window still misbehaves is context degradation. And if you want the contrast in one place, the prompt versus context engineering comparison draws the line.
The one idea you need first: a context window is the fixed number of tokens a model reads in one request, as defined in context window. Anything outside it is not skimmed or deprioritized. It's gone, and the model will answer without it rather than tell you it's missing.
Think of It Like This
Packing one carry-on under a weight limit
You're flying with one carry-on and a hard weight limit, and four people each hand you something that has to come along: your own essentials bag, a pile of laundry from the last leg, guidebook pages torn out for this city, and a sealed envelope you must hand over at the gate. The bag doesn't grow because four people showed up. You fold what compresses, you leave out what you can live without today, and you never touch the sealed envelope, because the trip fails without it.
Your essentials are the system prompt. The laundry is conversation history: bulky, mostly stale, but one sock in there might be the order number. The guidebook pages are retrieved passages. The sealed envelope is tool output: incompressible, and cutting it breaks the delivery.
The analogy stops where attention starts. Clothes don't interact in a suitcase, but tokens do: moving a rule from the top of the window to the middle changes how strongly the model honors it, and summarizing history rewrites evidence instead of just folding it. Packing decides what travels. Context engineering also decides what survives the trip in usable shape.
How It Actually Works
The four lanes sharing one window
Almost every production system fills the window from the same four lanes. The system prompt carries standing instructions: tone, escalation rules, what the assistant may promise. Its full treatment is in system prompts. History is what has been said this session; drop it and the assistant re-asks for the order number it already has. Retrieved passages arrive from a search step at request time, usually through the pipeline in RAG architecture; without them the model guesses at policy. Tool output is the raw result of an action just taken, delivered the way tool use and function calling describes; it's often the least compressible lane, because trimming it risks cutting the exact field the customer asked about.
Remove any one lane and a specific failure appears: no system prompt, drifting behavior; no history, repeated questions; no retrieval, confident wrong answers about policy; no tool output, an answer that ignores the live fact being asked about.
The budget rule and the cutting order
Write for the window size in tokens, and , , , for what the four lanes request. Everything the model sees must satisfy:
When the left side is bigger, the difference is the overflow, and which lane absorbs it is a design decision, not an accident. The usual priority: the system prompt is trimmed last, because it's small and cutting it changes behavior unpredictably. Tool output is pinned next, because the answer typically depends on one field inside it. That leaves history and retrieval to absorb the pressure. History goes first, oldest turns first, by summarizing or dropping; retrieval goes second, by keeping the matching passage and cutting the rest. A well-built assistant compacts old turns into a running summary before it cuts a retrieved passage further: a stale summary is a smaller loss than a policy article missing the clause the customer needs.
Worked example: a 4,300 token request in a 4,000 token window
Take a request where the lanes ask for , , and tokens, with . Add them: . The overflow is tokens.
History absorbs the cut first: . Nothing still overflows, so retrieval stays at , and the pinned lanes stay at and . The final window holds tokens, exactly the budget. The diagram above draws this same fixture: four lanes in, a 300 token piece spilling off the frame, history trimmed to 1900.
Why fitting inside the window is still not enough
Here's the mistake the budget rule invites: treating the problem as solved once everything technically fits. A model can hold a fact in context and still use it badly, because position matters. Instructions at the very top lose force as thousands of tokens pile beneath them, and a fact buried mid-prompt gets weaker attention than the same fact placed at the end. Length alone degrades use, independent of relevance. That's context degradation, and it's why stuffing the window to the brim can score worse than a shorter, sharper assembly.
So the test for adding anything is never "does this fit." It's "does adding this raise the odds of the right answer." Every kept token costs attention weight on everything else, plus latency and serving cost. That's the trade-off: recall against precision and cost. Cut too much and you lose the clause the answer needed; keep too much and you drown it.
Two honest boundaries close the picture. When not to use any of this machinery: a single self-contained question whose prompt sits far under the window needs none of it, and plain prompt wording wins. And the whole practice assumes trimming the oldest history first is safe, which fails whenever the key fact arrived early. If the order number appeared in turn one and your policy drops turn one first, the assistant re-asks for what it was told. Pin load-bearing facts, or summarize with them kept, instead of trusting recency. What outlives the window entirely is a different system, covered in memory systems.
Code
A minimal budget allocator: four requested lanes and a fixed window, with history absorbing the overflow first and retrieval second, while system and tool output stay pinned.
from dataclasses import dataclass
@dataclassclass Budget: system: int history: int retrieval: int tool_output: int
def allocate(window: int, requested: Budget) -> Budget: """Trim history first, then retrieval, until the lanes fit the window.""" total: int = requested.system + requested.history + requested.retrieval + requested.tool_output overflow: int = max(0, total - window) history: int = max(0, requested.history - overflow) covered: int = requested.history - history retrieval: int = max(0, requested.retrieval - (overflow - covered)) return Budget(requested.system, history, retrieval, requested.tool_output)
result = allocate(window=4000, requested=Budget(400, 2200, 1200, 500))print(result) # -> Budget(system=400, history=1900, retrieval=1200, tool_output=500)print(400 + 1900 + 1200 + 500) # -> 4000Feed it the numbers from any request and it shows exactly which lane absorbs the overflow: history first, retrieval next, system and tool output untouched. The fixture above is the worked example, so the output doubles as the check.
Watch Out For
Trimming the tool output because it's the biggest blob
Raw tool output is usually the most verbose lane in the prompt, which makes it the tempting first cut. It's also usually the lane the question depends on. Cut the delivery date out of an order-status JSON and the assistant returns a confident, complete-sounding answer that never mentions the one field the customer asked about.
Symptom: answers that read thorough yet miss the live fact. Fix: pin tool output at full fidelity and take the overflow from history, then retrieval. If the blob is truly huge, extract named fields in code before it reaches the window instead of letting the model read raw JSON.
Trusting oldest-first history trimming when the key fact arrived early
Oldest-first trimming assumes early turns matter least. That fails whenever the load-bearing fact arrived first: the order number in the opening message, the constraint the user stated up front. The assistant then re-asks for what it was already told, and the user concludes it has no memory at all.
Symptom: repeated questions for facts the session already contains, with no recent overflow to blame. Fix: keep a small pinned-facts block outside the trimmable history, or compact old turns into a running summary that carries facts forward. Never let a blind recency rule own facts you can't afford to re-ask for.
The Quick Version
- Context engineering decides what the model sees, not how the instruction is worded: four lanes, system, history, retrieval and tool output, share one fixed token window.
- The lanes must satisfy a budget rule, so any overflow is cut from somewhere, and the usual order trims history before retrieval while system and tool output stay pinned.
- A 4,300 token request in a 4,000 token window loses 300 tokens of history first, leaving 400 plus 1900 plus 1200 plus 500.
- Fitting is not enough, because position and length degrade how well the model uses what it holds.
- Add a token only when it raises the odds of the right answer, and pin load-bearing facts instead of trusting recency.