Choose what the agent needs for its next decision
Context engineering decides what the model sees for its next decision: trusted instructions, the user request, tool definitions and results, retrieved evidence, recent history, and current working state. It is different from durable memory—the context is the selected working packet for this step, while memory is information that may be stored and recalled later.
What You Will Learn
- Distinguish next-step context from information stored as memory.
- Select context by relevance, trust, recency, and token budget.
- Separate trusted instructions from untrusted retrieved content.
- Calculate a context budget with room for output and new observations.
Context is the packet used for the next decision
Context is everything deliberately assembled for one model call: trusted instructions, the current goal, tool definitions, selected history, retrieved evidence, and recent tool results. Memory is different. Memory is persisted information that may be searched and inserted into a later context when it becomes relevant.
Good context engineering makes four judgments. Relevance asks whether the item helps this next decision. Trust asks whether it is an instruction, user input, or untrusted evidence. Recency asks whether a newer fact supersedes it. Token budget asks whether the item earns the limited space it consumes.
Assemble a context packet without mixing trust levels
Separate system and developer instructions, the user request, working state, and untrusted retrieved content by role and trust level.
Select only tool definitions, memories, documents, and history relevant to the next decision.
Compress or summarize older material while preserving confirmed facts, decisions, constraints, citations, and open commitments.
Reserve token space for new tool results instead of filling the context before the agent acts.
For long tasks, refresh a compact state summary and test for lost constraints, noisy evidence, or context poisoning at important checkpoints.
Instructional figure
Assembling context by role and trust
How should different information sources enter one next-step model call?
Context assembler
What belongs in the next-step context?
Compression must preserve commitments
A useful state summary keeps confirmed facts, decisions, constraints, citations, completed work, and open commitments. It can remove greetings, repeated wording, and obsolete intermediate discussion. The goal is not merely fewer tokens; it is a smaller packet that still preserves what the agent must not forget.
Worked Example: Budgeting a 32,000-token context window
The 32,000-token limit is the chosen model/API limit for this example. The application reserves 4,000 tokens for the model's response before assembling the input.
- Instructions and tool definitions use 3,500 tokens; current state uses 1,500; retrieved evidence uses 15,000; and conversation history uses 6,000.
- Current input = 3,500 + 1,500 + 15,000 + 6,000 = 26,000 tokens.
- Committed budget including output = 26,000 + 4,000 = 30,000 tokens.
- Remaining headroom = 32,000 − 30,000 = 2,000 tokens.
- A new 4,000-token tool result will not fit: it exceeds the 2,000-token headroom by 2,000 tokens, so evidence/history must be reranked, compressed, or dropped before the next call.
What the result means: Reserving output alone is not enough for an acting agent. It also needs headroom for observations that arrive after tools run.
Instructional figure
A 32K context budget with room for action
Why must an acting agent reserve space for both output and future tool results?
rules + tools
state
free
A Realistic Example: A support agent handling a returning customer
The agent receives policy rules, the current ticket, a short verified customer summary, and the latest tool result instead of fifty full past conversations.
Read the Mechanism in Code
Use the label and note to understand what this block represents before reading each line.
context = [system_policy, current_task]
context += retrieve_relevant_memories(current_task, limit=3)
context += [latest_tool_result]
response = model(context)Hands-On Runnable Python Lab: Fit a New Tool Result into a 32,000-Token Budget
Treat 32K as exactly 32,000 tokens for this exercise. Instructions use 3,500, state 1,500, evidence 15,000, history 6,000 and the response reserve 4,000. These are supplied tokenizer-count fixtures, not string-length estimates.
- Add the input categories and output reserve to obtain 30,000 used and 2,000 free.
- Add the new 4,000-token result. The request would now require 34,000 tokens.
- Remove 2,000 tokens of expendable history after preserving active commitments and evidence references.
- Recalculate: 3,500 + 1,500 + 19,000 + 4,000 + 4,000 = 32,000. Reject a request if safe compaction cannot make it fit.
A new observation needs space inside the same fixed window
All three stacked bars use one token scale. The red dashed line is the 32,000-token ceiling, including the output reserve. Compaction removes 2,000 history tokens.
capacity = 32000
parts = {"instructions": 3500, "state": 1500, "evidence": 15000, "history": 6000, "output": 4000}
def report(label):
used = sum(parts.values())
print(f"{label}: used={used:,}; free={capacity - used:,}")
report("Before result")
parts["evidence"] += 4000
report("After result")
overflow = max(0, sum(parts.values()) - capacity)
history_floor = 4000 # protected commitments retained in the compacted history
removable = parts["history"] - history_floor
if overflow > removable:
raise ValueError("Cannot safely fit: retrieve less or split the task")
parts["history"] -= overflow
report("After compaction")
print("history removed:", overflow)
print("instructions unchanged:", parts["instructions"] == 3500)
print("output reserve unchanged:", parts["output"] == 4000)
Before result: used=30,000; free=2,000
After result: used=34,000; free=-2,000
After compaction: used=32,000; free=0
history removed: 2000
instructions unchanged: True
output reserve unchanged: TrueWhat This Run Shows
- Negative free capacity indicates overflow; sending the oversized request is not a valid compaction strategy.
- Only history changes in this policy. Other tasks may discard redundant evidence instead, but must preserve required sources.
- Exactly filling the illustrative window proves the arithmetic, not that a real model will use all those tokens effectively.
Budgeting is a resource-allocation decision with semantic consequences. Inspect the compacted material as well as its token count, and leave an operational margin when tool output size is unpredictable.
From the Exercise to an Application
Experiment: Increase the new result to 6,000 tokens while keeping the history floor.
The overflow becomes 4,000, but only 2,000 history tokens may be removed. The program raises an error instead of erasing protected content.
Summary / Key Takeaways
- Context engineering decides what the model receives for its next decision; it is not the same as durable memory.
- A useful context packet may include trusted instructions, the current task, working state, selected tool definitions, retrieved evidence, relevant memories, and recent history.
- Context should be selected by relevance, trust level, recency, and token budget rather than by simply including everything available.
- Untrusted retrieved text and tool output should be clearly separated from trusted instructions so data cannot silently become authority.
- Long histories should be compressed while preserving confirmed facts, constraints, decisions, citations, and open commitments.
- Output space and future tool results need reserved capacity; a context window can be full even when more evidence is still required.
- A larger context window does not guarantee better decisions—noise, stale evidence, and conflicting instructions can reduce reliability.
Verified Further Reading
These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.
OpenAI API: Counting Tokens
Exact input-token counting for request content, tools, images, files, and message structure.
OpenAI API: Compaction
Current guidance for reducing long-running context while preserving state needed for later turns.
OpenAI API: Conversation State
Explains conversation persistence, context-window accounting, input/output/reasoning tokens, and truncation risks.