Context Engineering: Designing What the Model Sees
How to assemble, budget, order and protect everything that goes into an LLM’s context window, and keep it healthy as your product grows.

On this page
A language model only ever sees one thing: the text in its context window at the moment it generates. Everything you want it to know, follow or avoid has to be in that text. Context engineering is the discipline of deciding what goes into the window, in what order, at what cost, and how you keep that decision healthy as the product grows.
From prompts to context
"Prompt engineering" suggests a clever sentence you tune until the model behaves. In production that framing breaks down quickly. A real request is assembled from several sources: fixed instructions, tool definitions, a few examples, documents fetched for this question, a summary of the conversation so far, and finally the user's message. The wording of any single line matters far less than which pieces are present, how big they are, and where they sit.
So treat the context as a build artifact. It is generated by code, it has a size budget, it has parts that change on every call and parts that never change, and it can be versioned and tested like anything else you ship.
Anatomy of a request
Most production requests are built from the same six layers. Knowing which is which tells you what to cache, what to trim and what to distrust.
| Layer | Changes | Cacheable | Main risk |
|---|---|---|---|
| System rules | Per release | Yes | Contradictory rules piling up over time |
| Tool / function definitions | Per release | Yes | Too many tools confuse selection |
| Few-shot examples | Rarely | Yes | Examples bias output toward their quirks |
| Retrieved knowledge | Every call | No | Irrelevant or stale chunks crowd out good ones |
| Conversation memory | Every turn | Partly | Grows without bound; old turns dilute rules |
| User input | Every call | No | Untrusted: may contain injected instructions |
The top three are your stable prefix. The bottom three are volatile. That split drives almost every other decision in this article.
Budgeting the window
A bigger context window is not a free pass. Every token you send is paid for on every call, adds latency, and competes for the model's attention. Models also attend unevenly: material at the very start and the very end of a long context tends to be used more reliably than material buried in the middle. Stuffing the window with "just in case" content often makes answers worse, not better.
Play with the budget below. Notice how quickly retrieved chunks and long histories dominate, and how small the stable, cacheable prefix becomes once a conversation runs for a while.
A few rules of thumb that fall out of this:
- Set a hard budget per layer, not just a global limit. For example, retrieved knowledge gets at most 6k tokens and history at most 4k, whatever happens.
- Retrieve fewer, better chunks. Ten mediocre passages are worse than three well-ranked ones. Re-ranking (covered in RAG) is usually a better investment than a larger window.
- Always reserve room for the answer. A request that fills the window leaves the model no space to finish.
Ordering for caching and attention
Many providers cache the longest prefix a request shares with a recent request and bill those tokens at a fraction of the normal price. That only works if the stable parts come first and stay byte-for-byte identical. One timestamp or user name inside the system prompt breaks the cache for everything after it.
SYSTEM_RULES = load_prompt("support-agent", version="2026-10-01") # versioned file, never edited in place
EXAMPLES = load_examples("support-agent", version="2026-10-01")
def build_messages(question, retrieved, history_summary, recent_turns):
context_block = "\n\n".join(f"[{c.id}] {c.text}" for c in retrieved)
return [
# 1. Stable prefix: identical across users and calls, so it can be cached.
{"role": "system", "content": SYSTEM_RULES},
*EXAMPLES,
# 2. Volatile middle: summarised memory, then the most recent turns verbatim.
{"role": "user", "content": f"<conversation_summary>\n{history_summary}\n</conversation_summary>"},
*recent_turns,
# 3. The current question last, with its supporting documents right next to it.
{"role": "user", "content": f"<documents>\n{context_block}\n</documents>\n\nQuestion: {question}"},
]Putting the documents next to the question also helps attention: the evidence and the thing it is evidence for sit together at the end of the window, where the model is reading most carefully.
Keeping long conversations healthy
Conversation history is the layer that silently eats your budget. A common pattern is a rolling summary: keep the last few turns word for word and compress everything older into a short running summary that you regenerate occasionally.
KEEP_VERBATIM = 6 # most recent turns kept exactly
SUMMARY_BUDGET = 400 # tokens
def compact_history(turns, summary):
if len(turns) <= KEEP_VERBATIM:
return summary, turns
older, recent = turns[:-KEEP_VERBATIM], turns[-KEEP_VERBATIM:]
summary = summarise(
previous_summary=summary,
new_turns=older,
instructions="Keep decisions, numbers, names and open questions. Drop pleasantries.",
max_tokens=SUMMARY_BUDGET,
)
return summary, recentSummaries lose detail, so decide explicitly what must survive: commitments made to the user, identifiers, constraints they stated. If something is critical (an account number, a chosen plan), store it as structured state in your application and re-inject it, rather than hoping the summary keeps it.
Treat untrusted text as data
Everything in the context is just tokens to the model. A retrieved web page or an email can contain text like "ignore your previous instructions", and the model has no hard boundary that stops it from obeying. Role separation (system vs user) is a strong habit the model learned in training, not a security guarantee.
Defend in layers:
- Fence untrusted content in clearly labelled tags and tell the model it is material to analyse, never instructions to follow. Strip or escape your closing tag from the content so it cannot break out of the fence.
- Keep secrets out of the context. If the model never sees an API key, it cannot leak one.
- Limit what outputs can do. If a model can call tools, validate every call in code: allow-lists, argument checks, and human confirmation for anything irreversible.
Version it and measure it
Context changes are code changes. Each one can fix the case you were looking at and quietly break three you weren't. The antidote is a small, boring evaluation loop that runs on every change:
import json
def run_eval(build_fn, model, cases_path="evals/support-agent.jsonl"):
results = []
for line in open(cases_path):
case = json.loads(line)
reply = model.generate(build_fn(**case["inputs"]))
results.append({"id": case["id"], "pass": case_passes(reply, case["expect"])})
passed = sum(r["pass"] for r in results)
print(f"{passed}/{len(results)} passed")
return resultsStart with 30 to 50 real examples, including the awkward ones from support tickets. Pin the model version alongside the prompt version, because the same context can behave differently on a newer model. Upgrade both deliberately, with the eval as the gate.
A short checklist
- Stable prefix first, byte-identical across calls; volatile content after it.
- A token budget for each layer, plus a reserve for the answer.
- Fewer, better-ranked documents, placed next to the question.
- Rolling summaries for long chats; critical facts kept as structured state.
- Untrusted text fenced and treated as data; real guarantees enforced in code.
- Prompts and examples versioned; every change gated by an eval set.
Next, see how the knowledge layer gets filled: embeddings turn text into searchable vectors, and RAG puts the best matches into the window.