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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner The idea and its parts

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

AspectPrompt engineeringRetrieval-augmented generationContext engineering
QuestionHow should I instruct the model?Which documents help answer this?What should the model see now, from every source?
Main objectInstructions and examplesA searchable collectionThe whole input and how it changes over time
Typical workWording, structure, examplesChunking, search, rankingSelection, budgeting, compression, isolation, memory
Changes per stepRarelyPer queryEvery 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

InstructionsRole, rules, format. Stable
Tool definitionsNames, descriptions, schemas. Mostly stable
MemoryFacts kept from earlier sessions
Retrieved dataDocuments, records, search results
State and historyPlan, steps taken, tool results
Current requestWhat to do now
Stable layers first help caching. The current task near the end is easy to find.
LayerIncludeLeave outCommon problem
InstructionsRules that apply to this taskRules for other tasksContradictions
ToolsThose usable nowEvery tool the company ownsWrong tool chosen
MemoryFacts relevant to this requestThe whole profileOutdated claims
Retrieved dataBest passages, with source and dateWhole files by defaultNoise and conflicts
HistoryDecisions, open items, recent resultsOld raw outputsUnbounded growth
RequestGoal and success testNothing needed hereBuried 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.

LayerUnmanagedEngineered
InstructionsRules for all departments, 6,000 tokensSupport rules, 900 tokens
Tools40 definitions, 8,000 tokens5 for orders and refunds, 1,000 tokens
MemoryFull customer profile"Replaced the same item on 3 May", with its source
Retrieved dataThe whole policy manual, two versionsCurrent refund section, dated
HistoryEvery raw record returned so farOrder number, status and open question
RequestThe sentenceThe 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.

Intermediate Budgets and assembly

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.

AllocationExample shareRule when full
Reserved output10%Never borrowed
Safety margin10%Absorbs estimate errors
Instructions and tools10%Reduce tools by task
Memory5%Keep the most relevant and recent
Retrieved data30%Fewer, better passages
History and state35%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

OperationMeaningExample
SelectChoose what entersLoad only the tools for refunds
RetrieveFetch when neededRead a file only after a search points to it
CompressSay it in fewer tokensSummarize twenty turns into decisions and open items
OffloadKeep it outside the windowSave a large result to a file and keep its path
IsolateGive separate work separate contextA 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?

AspectLoad up frontLoad just in time
HowRetrieve before the first callGive the agent search and read tools
SpeedFewer stepsMore steps
Window useHigherLower
RiskIrrelevant or stale materialThe 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.

Expert Cost, quality and operations

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

  1. Log what entered each request: layer, source, size and version.
  2. 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.
  3. Run removal tests: drop a layer and rerun your evaluation. If nothing changes, you may not need it.
  4. Track tokens per successful task, cache reuse, retrieval hit rate and success rate together.
Privacy travels with context

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.

Expert tip

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

MistakeWhy it hurtsInstead
"Add more context" after every failureNoise grows and the real cause stays hiddenCheck whether the fact was present, then fix the right step
Summarizing summaries repeatedlyErrors and omissions compoundSummarize from the original record
One shared context for unrelated tasksDetails leak between cases or customersStart a clean context per task
Silent truncationRules or results vanish unnoticedBudget explicitly and log what was cut
Trusting retrieved text equallyA forum post outranks the policyRank 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

Next steps