Context engineering: deciding what an agent knows right now
The hard part of an agent is not the model call. It is choosing which facts, memories and live signals go into the window, in what form, and what stays out.
Context engineering in 60 seconds
- What: the discipline of selecting, ordering, shrinking, protecting and delivering the information a model sees on each call.
- Why it matters: most agent failures that look like model weakness are really the wrong information, too much information, or stale information.
- Three words to keep apart: knowledge is curated reference material, memory is what persists between interactions, and context is the temporary working set for this one step.
- Core idea: treat context as a control plane. Data about who is asking, what they need and why steers behaviour, instead of branches hardcoded in the application.
- Weak spots: curation cost, stale signals, and the temptation to pour in everything because the window is large.
The problem it solves
A model answers using whatever is in front of it. It has no view of your policies, your customer or the last ten seconds of your logs unless you put them there. So every agent design contains a quiet question: what should this agent know at this moment, for how long, and what should it forget?
Early systems answered by pasting in a long static prompt. That works for a demo. In production it breaks in two directions. If you include too little, the agent guesses. If you include too much, it loses the thread, answers slowly and costs more. A cook making an omelette gains nothing from memories of kneading dough, and a model gains nothing from ten wiki pages when one paragraph applies.
Context engineering replaces the static prompt with a small system that decides, per step, what goes in. It moves the question from 'how do I word the prompt' to 'what is the smallest, most useful set of information for this decision right now'.
Knowledge, memory and context
- Knowledge is curated reference material: policies, rules, product facts and approved procedures. Someone has checked it. It changes slowly and has an owner.
- Memory is what persists across interactions: what this customer asked last week, which fix worked last time, what the user prefers. It is written by the system, so it can be wrong or out of date.
- Context is the temporary working set assembled for one call. Think of it as RAM. It is built from knowledge, memory and live signals, used once, and then discarded or partly written back to memory.
The consequence is that retrieval is not the same as context. Retrieval fetches candidates. Context engineering decides which candidates survive, how they are arranged and what is done to them on the way in. The memory types hub covers the storage side, and working memory covers the window itself.
Context as a control plane
In a traditional service, behaviour lives in code paths. If the user is a premium customer, an if-statement sends them down a different branch. In an agent, you can often get the same effect by changing what the agent is told. A refund request arrives with the customer tier, the order history, the refund policy and the risk score in context, and the model adjusts its behaviour accordingly.
That makes context a control plane: data about who, what and why steers the system. It is powerful, because you can change behaviour without a deployment. It is also risky, because a wrong or poisoned context entry changes behaviour just as quietly. Treat context content with the same care as configuration, including ownership, review and an audit trail.
The context engine
The context engine is the machinery around the model that does the assembly. Its jobs are to select, filter, rank, structure, compress, protect and deliver. You can picture it as a compiler. Raw data goes in, such as documents, tickets, logs and conversation turns. Reasoning-ready state comes out, in a shape the model can use well.
The 'protect' step is easy to forget. Before anything reaches the model, the engine should check that the caller is allowed to see it, apply business rules, remove personal data that the task does not need, and keep untrusted text away from instruction slots. This is where guardrails meet context. A document retrieved from a shared drive is data to be read, never a command to be followed.
Two streams: history and now
Useful context usually mixes two kinds of signal. The first is historical: runbooks, past incidents, earlier conversations, decisions already made. This is episodic and reference material, and it usually lives in a vector store or a graph. The second is real time: what is happening in the last few seconds, such as error logs, sensor readings or the current page the user is on.
The balance matters. With too much history, the agent leans on stale facts and misses what changed. With too much real time, it reacts to every blip and forgets what it learned an hour ago. The streams are fetched and prepared asynchronously, then fused at the last moment so the freshest signal is genuinely fresh. The goal is usefulness under constraint, not completeness.
Curate knowledge, do not dump data
A common shortcut is the equivalent of running a database query that selects everything: fetch the top ten wiki pages and put them all in the prompt. It feels safe, because the answer is probably in there somewhere. In practice it buries the useful paragraph, raises cost and gives the model more chances to latch onto an irrelevant detail.
The alternative is a curation pipeline that runs in the background, away from the request path. It distils, ranks and condenses source material into entries that are ready to use. A million support rows can become one summary entry, rebuilt every twelve hours. A set of linked documents can become a small graph plus a short description of each node. At request time the engine picks from curated entries, which is faster and more predictable.
Domain-specific context
There is no universal context recipe, because what matters depends on the job. A fraud agent at a bank cares about timestamps, unusual locations, device changes and the compliance rules that apply to the transaction. A contract-review agent for a legal team cares first about which state or country's law governs the document. If both used the same generic retrieval, both would do worse.
So drive the engine with a profile per agent type: which sources to consult, which fields to prioritise, and what to drop first.
A worked example
Acme Travel runs an agent that handles rebooking when a flight is cancelled. A customer writes: 'My flight to Lisbon was cancelled, what can you do?' A naive build dumps the whole booking record, the full fare rules document and the last forty messages. The agent replies slowly and quotes a rule that applies to a different fare class.
- Intent and role: the engine classifies the request as 'disruption, rebooking' and notes the caller is the passenger, not an agent of the airline.
- Knowledge selected: the two clauses of the disruption policy that match the fare class, not the whole document. About 300 tokens.
- Memory selected: the passenger prefers morning departures and has a connection in Madrid. About 80 tokens.
- Live signal: three alternative flights with seats left, fetched a moment ago. About 200 tokens.
- Protection: the passport number and card details are removed, since rebooking does not need them.
- Result: a context of around 700 tokens in a fixed layout, instead of 9,000 tokens of everything. The agent offers the 09:40 option and cites the clause.
The model is identical in both builds. Only the context changed, and the answer got faster, cheaper and correct.
Building it
MAX_CONTEXT_TOKENS = 1_500 # hard budget for one model call
MIN_RELEVANCE = 0.55 # drop anything weaker than this
FETCH_TIMEOUT_S = 2.0 # never wait long for a live signal
# Which sources matter most for each task type, in priority order.
PROFILES = {
"rebooking": ["policy", "live_options", "memory"],
"refund": ["policy", "memory", "live_options"],
}
def build_context(request, task_type: str) -> str:
# Placeholders: fetch_* return lists of {text, score, tokens}.
pools = {
"policy": fetch_policy(request, top_k=5),
"memory": fetch_memory(request.user_id, top_k=5),
"live_options": fetch_live(request, timeout_s=FETCH_TIMEOUT_S),
}
parts, used = [], 0
for source in PROFILES[task_type]:
# Best first, and only if relevant enough.
for item in sorted(pools[source], key=lambda i: -i["score"]):
if item["score"] < MIN_RELEVANCE:
break
if used + item["tokens"] > MAX_CONTEXT_TOKENS:
break # budget reached for this source
parts.append((source, redact_pii(item["text"])))
used += item["tokens"]
# Fixed layout: system rules, user facts, then the task.
sections = [f"## {name}\n{text}" for name, text in parts]
return "\n\n".join(sections + [f"## task\n{request.text}"])
The fetch functions and redact_pii are placeholders. The point is the shape: a budget, a relevance floor, a priority order per task, a timeout on live data, and redaction before assembly.
Design decisions
- Where assembly lives: build one context service that all agents call, rather than letting each agent assemble its own. It gives you one place for permissions, redaction and logging.
- Budgets per agent type: set a token budget for each task, and decide in advance what is dropped first. Do not let the budget be 'whatever fits'.
- Curation versus request-time work: push expensive summarising and ranking into background jobs. Keep the request path to selection and assembly.
- Freshness rules: each source gets a maximum age. A live feed older than a few seconds is treated as missing, not as truth.
- Ownership: knowledge entries need a named owner and a review date. Memory entries need an origin and a time to live.
- Isolation: keep one tenant's or user's context out of another's at the store level, not by prompt instruction.
- Traceability: log which items entered each context and why, so a bad answer can be traced back to its inputs.
Measuring it
- Context precision: the share of items in the window that a grader says were actually needed for the answer.
- Context recall: the share of facts needed for a correct answer that made it into the window. Test with cases where the right answer is known.
- Tokens per call: the mean and 95th percentile, and the time to first token, tracked by task type.
- Answer quality against context size: run the same questions with small, medium and large contexts. Many teams find quality peaks well below the window limit.
- Staleness rate: the share of answers that used a source older than its allowed age.
- Leak checks: red-team tests that try to pull another user's data or planted instructions through the context path.
When to use it, and when not to
| Situation | Invest in a context engine? | Why |
|---|---|---|
| Several agents share data sources and policies | Yes | One engine gives consistent permissions, redaction and logging. |
| Answers depend on both history and live signals | Yes | Fusing the two streams is the hard part, and it needs a clear owner. |
| A single chat assistant with a short fixed prompt | No | A well-written prompt is enough, and an engine adds moving parts. |
| Regulated data such as payments or health records | Yes | Protection and audit at assembly time are required, not optional. |
| One-off prototype or internal demo | Not yet | Start with a simple retrieval step, and add curation when quality plateaus. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Smaller, better-chosen context usually improves accuracy and reduces odd answers. | Measure precision and recall of context on a fixed test set. |
| Cost | Fewer tokens per call lowers spend, but curation jobs and stores add their own cost. | Compare total cost per answer, not only model cost. |
| Latency | Assembly adds steps, though smaller prompts return sooner. | Precompute curated entries and cap live fetch time. |
| Complexity | A new service with its own data pipelines, owners and failure modes. | Start with one agent type and grow the engine from real needs. |
| Risk | A single wrong or poisoned entry can steer many answers. | Review knowledge entries, scan inputs and log every item used. |
Compared with prompt engineering and plain retrieval
Prompt engineering is about wording one instruction well. It remains useful, but it does not decide which facts are present. Plain retrieval, as in agentic RAG, fetches relevant passages, but usually stops at ranking. Context engineering sits above both. It also handles budgets, protection, freshness, structure and the mix of history with live signals. You still need good prompts and good retrieval. The engine makes them work together, and the context lifecycle page follows what happens to that context over time.
What this means for your role
Common mistakes
- Filling the window because it is large, then wondering why answers are slow and vague.
- Treating retrieval results as final context without ranking, trimming or checking permissions.
- Mixing system instructions, user facts and retrieved text in one block, so the model cannot tell them apart.
- Using one generic recipe for every agent, instead of a profile that fits each job.
- Redacting personal data after the prompt is built, or not at all.
- Never logging what was in the context, which makes bad answers impossible to explain.
Further reading
- Context lifecycle and memory tiers: selection, injection, compression and expiry over time.
- Agentic AI architecture: an overview: how context fits with the other themes.
- Memory types: the storage side of knowledge and memory.
Context engineering is a small amount of careful plumbing with a large effect. Keep what the model sees small, current, safe and well ordered, and most of the rest of the agent gets easier.