What Is Context Engineering? Stack and Token Budgets
The model can only work with what you put in front of it. Choosing that, turn by turn, is an engineering job.
Context engineering is deciding what information a model receives at each step, in what form and order, within a token budget. It covers instructions, tool definitions, state, memory and retrieved data. For agents that run many steps, it is one of the biggest influences on quality and cost.
What you will learn: how context engineering relates to prompt engineering and RAG, the layers of the context stack, how to budget a window, how to assemble context in code and how to measure whether it works.
Prerequisites: How LLMs Power Agents: Transformers, Tokens and Sampling for tokens and context windows.
Think of a desk
Imagine asking a skilled temporary worker to handle a customer case. You could hand them nothing, and they would guess. You could wheel in every filing cabinet, and they would spend the day searching. The useful choice is a tidy desk: the task, the rules, the case file, the two relevant policies, notes from earlier calls and the phone numbers they may need.
A model's context window is that desk. Anything not on it is invisible, apart from what the model absorbed in training. Anything on it competes for attention.
Context engineering, prompt engineering and RAG
| Aspect | Prompt engineering | Retrieval-augmented generation | Context engineering |
|---|---|---|---|
| Question | How should I instruct the model? | Which documents help answer this? | What should the model see now, from every source? |
| Main object | Instructions and examples | A searchable collection | The whole input and how it changes over time |
| Typical work | Wording, structure, examples | Chunking, search, ranking | Selection, budgeting, compression, isolation, memory |
| Changes per step | Rarely | Per query | Every turn |
They nest. Prompting writes some of the context, RAG supplies some of it, and context engineering manages all of it. RAG Explained and Agentic RAG and Agent System Prompts and Instruction Hierarchy cover the parts.
The context stack
| Layer | Include | Leave out | Common problem |
|---|---|---|---|
| Instructions | Rules that apply to this task | Rules for other tasks | Contradictions |
| Tools | Those usable now | Every tool the company owns | Wrong tool chosen |
| Memory | Facts relevant to this request | The whole profile | Outdated claims |
| Retrieved data | Best passages, with source and date | Whole files by default | Noise and conflicts |
| History | Decisions, open items, recent results | Old raw outputs | Unbounded growth |
| Request | Goal and success test | Nothing needed here | Buried under the rest |
One turn, before and after
A support agent receives: "It broke again, can I get my money back?" Compare two inputs for the same turn. Sizes are illustrative.
| Layer | Unmanaged | Engineered |
|---|---|---|
| Instructions | Rules for all departments, 6,000 tokens | Support rules, 900 tokens |
| Tools | 40 definitions, 8,000 tokens | 5 for orders and refunds, 1,000 tokens |
| Memory | Full customer profile | "Replaced the same item on 3 May", with its source |
| Retrieved data | The whole policy manual, two versions | Current refund section, dated |
| History | Every raw record returned so far | Order number, status and open question |
| Request | The sentence | The sentence, plus the goal and success test |
The second input is far smaller, but size is not the main gain. "Again" now has a meaning, because the earlier replacement is present. There is only one policy version, so the model cannot pick the old one. And it cannot call a payroll tool that was never offered. Good context engineering often adds one decisive fact while removing a great deal of noise.
Capacity and token budgets
The window's capacity is a ceiling, not a target. Plan how the space is divided before the agent runs, so that no layer can silently crowd out another.
| Allocation | Example share | Rule when full |
|---|---|---|
| Reserved output | 10% | Never borrowed |
| Safety margin | 10% | Absorbs estimate errors |
| Instructions and tools | 10% | Reduce tools by task |
| Memory | 5% | Keep the most relevant and recent |
| Retrieved data | 30% | Fewer, better passages |
| History and state | 35% | Summarize old turns |
The shares are illustrative. A research agent may need most of the space for sources; a booking agent may need very little of the window at all. Derive yours from measured runs.
Count tokens with your provider's tools. The common four-characters-per-token estimate is useful for rough planning only.
Assemble within a budget
This program gives each part a priority, always includes required parts, and fails loudly when they cannot fit.
"""Assemble a context within a token budget. Standard library only."""
def estimate_tokens(text):
return max(1, len(text) // 4) # rough guide; use your provider's counter
def assemble(parts, budget):
"""parts: dicts with name, text, priority (1 = most important), required."""
chosen, used = [], 0
for part in sorted(parts, key=lambda p: (not p["required"], p["priority"])):
size = estimate_tokens(part["text"])
if used + size <= budget:
chosen.append(part["name"])
used += size
elif part["required"]:
raise ValueError(f"required part does not fit: {part['name']}")
order = [p["name"] for p in parts if p["name"] in chosen] # keep reading order
left_out = [p["name"] for p in parts if p["name"] not in chosen]
return order, used, left_out
def part(name, chars, priority, required=False):
return {"name": name, "text": "x" * chars, "priority": priority, "required": required}
PARTS = [
part("instructions", 2400, 1, required=True),
part("tool definitions", 3200, 1, required=True),
part("user memory", 600, 3),
part("old history", 6000, 5),
part("retrieved policy", 2800, 2),
part("recent history", 2000, 2),
part("current request", 400, 1, required=True),
]
for budget in (5000, 3000, 2000, 1000):
try:
order, used, left_out = assemble(PARTS, budget)
print(f"budget {budget}: used {used}, left out {left_out}")
except ValueError as exc:
print(f"budget {budget}: {exc}")
Output:
budget 5000: used 4350, left out []
budget 3000: used 2850, left out ['old history']
budget 2000: used 2000, left out ['user memory', 'old history', 'retrieved policy']
budget 1000: required part does not fit: tool definitions
Notice two behaviors you should decide deliberately. At 2,000 tokens the policy document is skipped, yet the smaller recent history, listed after it, still gets in: this is greedy filling. And a part that does not fit disappears completely. A fuller system would compress it, or tell the model that something was left out. Failing when required instructions do not fit is much safer than sending a request without them.
Five things you can do with context
| Operation | Meaning | Example |
|---|---|---|
| Select | Choose what enters | Load only the tools for refunds |
| Retrieve | Fetch when needed | Read a file only after a search points to it |
| Compress | Say it in fewer tokens | Summarize twenty turns into decisions and open items |
| Offload | Keep it outside the window | Save a large result to a file and keep its path |
| Isolate | Give separate work separate context | A sub-agent reads fifty pages and returns a page |
Techniques are detailed in Context Assembly, Retrieval, Compression and Caching and Context Isolation, Provenance and Governance.
Form and order matter
- Label sources and dates, so the model can weigh them and cite them.
- Separate data from instructions with clear headings or tags.
- Prefer compact formats for tables, and remove fields nobody uses.
- Keep identifiers exact. Summaries must not round or rename them.
- Mind position. In long inputs, material in the middle can receive less weight; place critical rules and the current task where they are hard to miss, and test.
Load early or load just in time?
| Aspect | Load up front | Load just in time |
|---|---|---|
| How | Retrieve before the first call | Give the agent search and read tools |
| Speed | Fewer steps | More steps |
| Window use | Higher | Lower |
| Risk | Irrelevant or stale material | The agent fails to look |
A mixed approach is common: load the small set that is nearly always needed, and give tools for the rest.
Treat tool results as context you design
In agents, tool output often grows faster than any other layer. Shape it at the source, inside the tool, where it is cheapest to control.
- Page and filter. Return the first matches and say how many remain.
- Choose fields. An order lookup rarely needs internal database columns.
- Return references. Give a file path or record ID that can be opened later.
- Summarize with care. Keep numbers, names, dates and error text exact.
- Report limits. State when results were truncated or a source was unavailable.
Once a result has been used, you can often replace it in the history with a one-line record such as "searched policy: refund window is 30 days (document P-12)". Keep the full text in your logs or a file so that nothing is lost for audit. Do not remove a tool result while leaving its matching request, or the reverse, where your API expects them in pairs.
Design for cost and quality together
Because history is resent each turn, a bloated context is paid for again and again. An illustrative case: 20,000 extra input tokens carried through 15 steps is 300,000 additional tokens for one task. Multiply by daily volume and your provider's price to see what trimming is worth.
- Prompt caching can lower the cost and delay of repeated prefixes. It works best when stable content comes first and is not rewritten, so avoid putting a timestamp at the top. Check the rules of your provider.
- Compression costs something too: a summarizing call, and the risk of losing a detail.
- Routing a small context to a smaller model can save more than trimming a large one.
A compaction example
After thirty turns on a software fault, the transcript holds searches, file contents and test output. A compact replacement keeps what a fresh worker would need.
Goal: failing test "invoice total" must pass without changing the test
Found: rounding happens before summing (file billing/total.py)
Decided: sum first, round once; reason: matches the written rule
Changed: billing/total.py
Last test run: 41 passed, 1 failed (currency with no decimals)
Open: handle currencies with zero decimal places
Details: full logs saved in notes/run-log.txt
Decisions carry their reasons, so the agent is less likely to reverse them. The failing case is stated exactly. Bulk detail remains reachable by path. Test compaction by continuing real tasks from the summary alone and seeing what the agent has to rediscover.
Measure it
- Log what entered each request: layer, source, size and version.
- For failed runs, ask whether the needed fact was present. If absent, fix selection or retrieval. If present but ignored, fix order, noise or wording.
- Run removal tests: drop a layer and rerun your evaluation. If nothing changes, you may not need it.
- Track tokens per successful task, cache reuse, retrieval hit rate and success rate together.
Everything in the window is sent to the model service and may appear in logs or outputs. Apply access rules before assembly, so that a user's request can never pull in data that user may not see. Never put secrets in context.
Long-running tasks
When work outlasts one window, keep an external record: the goal, the plan, decisions with reasons, files touched and open questions. At a boundary, start a fresh context from that record instead of dragging the whole transcript forward. This is called compaction when it summarizes the conversation, and note-taking when the agent maintains the record as it works. See Long-Horizon, Multi-Agent and Enterprise Context.
Print the exact final input for a handful of real requests and read it as if you were the model. Duplicated passages, stale tool results and missing facts become obvious in minutes.
Common mistakes
| Mistake | Why it hurts | Instead |
|---|---|---|
| "Add more context" after every failure | Noise grows and the real cause stays hidden | Check whether the fact was present, then fix the right step |
| Summarizing summaries repeatedly | Errors and omissions compound | Summarize from the original record |
| One shared context for unrelated tasks | Details leak between cases or customers | Start a clean context per task |
| Silent truncation | Rules or results vanish unnoticed | Budget explicitly and log what was cut |
| Trusting retrieved text equally | A forum post outranks the policy | Rank by authority and date, and label it |
Who owns the context?
Context comes from many teams: someone writes the instructions, another maintains the tools, a third owns the documents and a platform stores memory. A change in any of them can alter behavior. Name an owner for each layer, version what can be versioned, and run the evaluation set when one changes, including changes made by other teams. When a result gets worse, the request manifest shows which layer differs from the last good run.
Checklist
- Each layer has an owner, a budget and a rule for overflow.
- Output space is reserved.
- Only relevant tools and memories are loaded.
- Retrieved items carry source and date.
- Access control happens before assembly.
- Requests can be reconstructed for debugging.
- Changes to context are evaluated like code changes.
Frequently asked questions
Is context engineering just a new name for prompt engineering?
It grew out of it. The difference is scope: managing everything the model receives across many turns, including what code retrieves, stores and removes.
Do very large context windows make it unnecessary?
No. Capacity helps, but cost, delay and distraction remain, and some information must still be chosen for reasons of access and freshness.
Which layer should I improve first?
Look at failures. Oversized tool results and unused tool definitions are common early wins, but your traces decide.
Can the model manage its own context?
Partly. It can write notes, choose what to read and request summaries. Keep budgets, access control and required instructions under your code's control.
References and further reading
- Effective context engineering for AI agents (Anthropic engineering)
- Lost in the Middle: How Language Models Use Long Contexts (paper)
- Context Rot (Chroma technical report)
- How contexts fail and how to fix them (Drew Breunig)
Next steps
Context Poisoning, Distraction, Confusion, Clash and Rot
Recognize and repair the ways context goes wrong.
Context Assembly, Retrieval, Compression and Caching
Build the assembly and compression steps.
Agent Memory Types and Persistence
Keep information beyond one window.