AI Development

AD-01

Engineer the context

What you'll produce: Context map and token budget

Definition

Context engineering is the practice of deciding which instructions, documents, tool descriptions, and history a model sees at each step of a task, and what stays outside the window until it is needed. The working artifact is a context map that lists every source, who loads it, when it loads, and how many tokens it may use.

TL;DR

Why the window is a budget

A model can only act on what is in its window when it is called. When an agent fails, the first question is whether it had what it needed. LangChain's writing on the subject makes the point directly: most unreliable agent behaviour traces back to missing or badly formatted context, not to a weak model. That gives a useful test to apply before touching a prompt. Could a capable person, shown exactly what the model was shown, have done the task?

The opposite failure is just as common. Long runs pile up tool results, and a window that holds too much has its own problems. An early mistake stays in view and gets repeated. Irrelevant material pulls the answer off course. Two sources disagree and the model picks one without saying so. Cost and latency rise with every token, on every call.

So the window is a budget, and context engineering is how you spend it. Our own note on harness changes argues that the structural parts of an agent, meaning its tools, the layer between the agent and its environment, and how memory is organised, carry over between models better than prompt wording does. The context map is where those structural choices get written down.

Map what the model sees

Start with an inventory. Take one full trace and list every block that entered the window. Most teams find more than they expected: a system prompt, one or more rules files, every tool definition, retrieved documents, the conversation so far, and raw tool results.

Then answer three questions for each block.

Question Options Why it matters
What kind is it? Instructions, standing guidance, tool definition, knowledge, history, tool result Each kind goes stale at a different rate
Who loads it? Software at a fixed point, the model on demand, a person Only software loading is certain
How much may it use? A token ceiling per source Without a ceiling, the largest block wins by default

The loader column deserves the most thought. Martin Fowler's site describes the same three choices for coding agents. Letting the model decide when to load something is what allows unattended work, but there is no guarantee it loads when you expect. A person invoking context gives control and costs automation. Software that injects context at a fixed point is predictable. Put anything the run cannot succeed without in the software column.

Four moves for a source that is over budget

LangChain groups the common techniques into four, and the grouping holds up in practice.

Write. Save information outside the window so it can be fetched later. A plan file, a notes file, or a large tool result written to disk all count. The agent keeps a path and a short preview in the window and reads the rest only if it needs to.

Select. Pull in only what the current step needs. This covers retrieval over documents, loading a skill when its description matches the task, and choosing a few relevant tools from a large set.

Compress. Keep the meaning and drop the tokens. Summarise old turns, trim tool output, or store summaries at more than one level of detail so an agent can scan many items briefly and expand the few that matter. Compression loses things, so the rule must name what always survives.

Isolate. Give a sub-task its own window. A subagent can read fifty files and hand back five lines. The main agent's window stays clean, at the price of more total tokens and a handoff that has to be written carefully.

Worked example: a refund triage agent

This example is fictional. A support team runs an agent that reads a refund request, checks the order and the policy, and either approves, refuses, or escalates.

The first trace shows 41,000 tokens in the window by the time the agent decides. The inventory looks like this: a system prompt of 1,200 tokens, a rules file of 3,800, definitions for 34 tools at 9,500, the full refund policy at 12,000, the order record at 6,500, and earlier tool results at 8,000.

The team sets a ceiling of 16,000 tokens and works down the list.

  • Tool definitions: the agent uses five of the 34 tools for refunds. The rest move to a separate configuration for other tasks. New ceiling 1,800.
  • Policy: retrieve the two or three sections that match the product category and the reason code instead of loading the whole document. New ceiling 2,500.
  • Order record: a software step extracts the eight fields the decision uses. New ceiling 600.
  • Tool results: results over 1,000 tokens are written to a file, and the window keeps the path and a summary. New ceiling 2,000.
  • Rules file: cut to the rules that apply to refunds. New ceiling 1,500.

The compaction rule says the customer's stated reason, the policy sections cited, and any refusal already given must survive every summary.

They rerun the 40 cases from the spec. Task success is unchanged, two escalation cases that used to be approved by mistake now escalate, and tokens per run fall by more than half. One case gets worse because the retrieval step missed a policy exception. That case goes into the retrieval design, which is the next topic.

Common failure modes

  • The rules file that only grows. Every incident adds a line and nothing is removed. Review it on a schedule and after each model change.
  • Loading every tool. Tool definitions are context. Overlapping descriptions make the model hesitate between tools, and unused ones cost tokens on every call.
  • Compaction that forgets the goal. A summary that drops a constraint produces work that looks right and is wrong. Our post on context drift describes the pattern: late steps act on a distorted version of early ones.
  • Trimming without measuring. A smaller window is not the aim. Keep the eval running so a saving that hurts the task is caught the same day.
  • Trusting model-loaded context for must-have facts. If the run fails without it, inject it in code.

How it connects to the other pillars

The context map depends on product decisions made earlier. The spec says what the task is and what correct looks like, which tells you what the model has to see. Without the spec's eval cases there is nothing to test a budget against.

It also feeds the factory pillar. A work order for an agent worker is a context pack: the goal, the constraints, the files in scope, and the checks to run. Teams that write good work orders are doing context engineering for another agent's window, and the same budget thinking applies.

The human side has a budget too. One of our posts counts the harnesses, agents, and skills on a single laptop and concludes that the person approving the work is now the scarce window. A context map that is short enough to review is part of respecting that limit.

Run it yourself

Time: ~2 hours for one agent

  1. Inventory what enters the window — You need: One complete trace of a real run, with a token count for every message and tool result. You get: A list of every source in the window, covering system prompt, rules files, tool definitions, retrieved documents, history, and tool results. Count tool definitions. They are often the largest block nobody wrote on purpose.
  2. Name the loader and the timing for each source — You need: The inventory and the agent's configuration. You get: One row per source showing whether it is always loaded, injected by software at a fixed point, pulled by the model on demand, or added by a person. Model-loaded context is what makes unattended runs possible, but you cannot be sure it loads. Use software-injected context for anything that must be present.
  3. Set the budget — You need: The model's window size, your cost per run target, and your latency target. You get: A token ceiling for each source and for the whole call, with room reserved for the output.
  4. Pick a move for every source over its ceiling — You need: The budget and the four moves (write, select, compress, isolate). You get: A decision per source, such as offload to a file, retrieve on demand, summarise, or hand to a subagent.
  5. Write the compaction rule — You need: The longest run you expect and the facts a run cannot afford to lose. You get: A rule stating when history is trimmed or summarised and which items always survive, such as the goal, constraints, decisions made, and open questions.
  6. Test the budgeted version against the old one — You need: The eval cases from the spec and both configurations. You get: A before and after table of task success, tokens per run, and latency.

Do it with AI

You are helping me produce a context map and token budget for one AI agent. Work only from the material I paste. Do not invent sources or token counts. If a number is missing, ask for it.

Agent task: [ONE SENTENCE DESCRIBING THE TASK]
Model and window size: [MODEL NAME, WINDOW IN TOKENS]
Targets: [COST PER RUN TARGET], [LATENCY TARGET]
Trace of one full run, with token counts per message: [PASTE TRACE]
Agent configuration (system prompt, rules files, tool definitions): [PASTE CONFIG]

Step 1. List every source that entered the window in the trace. For each one give: name, type (instructions, guidance, tool definition, retrieved knowledge, history, tool result), tokens used, and whether it was needed for this task (yes, partly, no) with one line of reasoning.

Step 2. For each source state who loads it today (software at a fixed point, the model on demand, or a person) and whether that is the right loader. Anything the run cannot succeed without must be loaded by software.

Step 3. Propose a token ceiling per source and a total ceiling that leaves room for the output. Show the arithmetic.

Step 4. For each source over its ceiling, recommend exactly one move: write it outside the window, select it on demand, compress it, or isolate it in a separate context. Say what could go wrong with that move.

Step 5. Write a compaction rule: the trigger, what is summarised, and the list of facts that must survive every compaction.

Output a single table (source, type, loader, timing, ceiling, move, risk), then the compaction rule, then a list of open questions I need to answer before this can be tested.

Chain it

  1. Context auditor — Reads recent traces and counts tokens per source for each run; Traces from the last 20 to 50 runs and the agent configuration → An inventory with median and worst-case tokens per source
  2. Budget drafter — Proposes a loader, a ceiling, and one move for each source over budget; The inventory plus cost and latency targets → A draft context map and token budget; gate: The engineer who owns the agent approves anything removed from the always-loaded set
  3. Compaction tester — Replays the longest recorded runs under the new budget and checks that the goal, constraints, and decisions survive each compaction; The draft map, the compaction rule, and long traces → A list of runs where a required fact was lost, with the step where it happened
  4. Regression runner — Runs the eval cases against the old and new configuration and reports the difference; Both configurations and the eval set → A before and after table of task success, tokens, and latency; gate: A person decides whether to ship when any eval case gets worse

How AI changes this

Automate

Keep human

Stage

FAQ

What separates context engineering from prompt engineering?

Prompt engineering improves the wording of one instruction. Context engineering decides everything the model sees at each step, including tool definitions, retrieved documents, history, and tool results, and it treats that set as something assembled at run time. The prompt is one row in the map.

Context windows keep growing. Do I still need a budget?

Yes. A larger window raises the ceiling but does not change the trade-off. Extra tokens cost money and time on every call, and the practitioners cited here report that agents get less effective when the window holds material they do not need. The budget is about what earns its place, not about what fits.

How many tokens should the always-loaded set use?

There is no standard number. A workable rule is to start small and add a rule only after a failure shows the model needed it. Review the set when you change models, because guidance an older model needed may no longer be necessary.

When should I move work into a subagent?

When a sub-task needs a lot of reading that the main task does not need to remember, such as searching many files to return one answer. The subagent spends its own window and returns a short result. Expect higher total token use and more coordination work, so do it for a measured reason.

Sources

Related