Skip to main content
LearnMLAcademy
Advanced10 min read

Context Engineering for Agents

Optimize AI agent context windows with token budgets and smart compaction, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

  1. Separate system and developer instructions, the user request, working state, and untrusted retrieved content by role and trust level.

  2. Select only tool definitions, memories, documents, and history relevant to the next decision.

  3. Compress or summarize older material while preserving confirmed facts, decisions, constraints, citations, and open commitments.

  4. Reserve token space for new tool results instead of filling the context before the agent acts.

  5. 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?

System + developer rules
trusted authority
User request
task input
Memory + task state
selected application data
Retrieved pages + tool output
untrusted evidence

Context assembler

Relevant?Trusted as what?Current?Fits budget?
Next-step model context
roles and provenance preserved
Trusted instructions remain distinct from user input and untrusted evidence. The assembler selects relevant, recent information and labels provenance before the model sees it.

What belongs in the next-step context?

What belongs in the next-step context?
SourceTrust levelWhy include it?Compression strategyCommon failure
System / developer instructionsTrusted authorityDefine role, rules and tool policyKeep exact critical constraintsHidden by long noisy context
User requestTask input, not system authorityStates the goal and user constraintsKeep intent and explicit choicesAmbiguity silently guessed
Working stateApplication-maintainedTracks progress, decisions and open workStructured compact summaryStale or missing commitments
Retrieved evidenceUntrusted dataSupplies task factsRerank, quote minimally, keep provenancePrompt injection or irrelevant passages
Tool resultUntrusted observationShows what happenedReturn only decision-relevant fieldsVerbose output floods the 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.

  1. Instructions and tool definitions use 3,500 tokens; current state uses 1,500; retrieved evidence uses 15,000; and conversation history uses 6,000.
  2. Current input = 3,500 + 1,500 + 15,000 + 6,000 = 26,000 tokens.
  3. Committed budget including output = 26,000 + 4,000 = 30,000 tokens.
  4. Remaining headroom = 32,000 − 30,000 = 2,000 tokens.
  5. 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?

3.5K
rules + tools
1.5K
state
15K retrieved evidence
6K history
4K output
2K
free
Input = 26K
3.5 + 1.5 + 15 + 6
Committed = 30K
26K input + 4K output
New result = 4K
Only 2K free → compress first
The current plan commits 30K of 32K tokens, leaving only 2K. A new 4K tool result cannot fit until lower-value context is compressed or removed.

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.

Conceptual pseudocode
context = [system_policy, current_task]
context += retrieve_relevant_memories(current_task, limit=3)
context += [latest_tool_result]
response = model(context)
Learner note: Conceptual context-assembly pseudocode. Retrieval and model calls are placeholders for application components.

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.

used = 3,500 + 1,500 + 15,000 + 6,000 + 4,000 = 30,000; new total = 34,000; overflow = 2,000
The incoming tool result requires 4,000 more tokens. Preserve instructions, state and the output reserve; reducing history from 6,000 to 4,000 creates exactly the missing 2,000 tokens.
  1. Add the input categories and output reserve to obtain 30,000 used and 2,000 free.
  2. Add the new 4,000-token result. The request would now require 34,000 tokens.
  3. Remove 2,000 tokens of expendable history after preserving active commitments and evidence references.
  4. 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

Stacked token budgets: 30,000 before a tool result, 34,000 after it, and 32,000 after reducing history by 2,000. Dashed line marks capacity.Before: 30KNew result: 34K — too muchCompacted: 32K — fits32K capacity ↑Instructions 3.5KState 1.5KEvidenceHistoryOutput reserve 4KHistory 6K → 4K; output reserve intact
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.

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.

Complete Python ExercisepythonRunnable
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)
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
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: True
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. Negative free capacity indicates overflow; sending the oversized request is not a valid compaction strategy.
  2. Only history changes in this policy. Other tasks may discard redundant evidence instead, but must preserve required sources.
  3. 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

From the Exercise to an Application
SituationPractical choiceImportant qualification
Large tool resultSelect relevant fields or retrieve a narrower sliceRetain source IDs and required qualifications.
Long conversationCompact completed work into structured stateNever summarize a pending approval into a granted one.
Nothing safe to removeSplit the task or ask for narrower scopeDo not silently drop policy or required evidence.
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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Context Engineering for Agents"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the main difference between context and durable memory?
Question 2 of 5numerical/formula
A 32,000-token window reserves 4,000 tokens for output. Input material currently uses 26,000 tokens. How many tokens remain before the reserved output space would be consumed?
Question 3 of 5practical selection
A new tool result is 4,000 tokens, but only 2,000 input tokens remain. What is the best response?
Question 4 of 5conceptual
Why should retrieved webpages be separated from trusted system/developer instructions?
Question 5 of 5debugging/diagnostic
An agent includes fifty old conversations even though only two are relevant, and performance gets worse. What is the likely problem?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the main difference between context and durable memory?▼

Correct Answer: Context is the working packet for the next decision; memory is persisted information that may be retrieved later

Context is what the model sees now. Memory is information stored for possible later recall into a future context.

2A 32,000-token window reserves 4,000 tokens for output. Input material currently uses 26,000 tokens. How many tokens remain before the reserved output space would be consumed?▼

Correct Answer: 2,000

The maximum input under the 4,000-token output reserve is 28,000. With 26,000 input tokens used, 2,000 remain.

3A new tool result is 4,000 tokens, but only 2,000 input tokens remain. What is the best response?▼

Correct Answer: Compress or drop lower-priority context and keep the important evidence

Context engineering requires reprioritizing and compressing less useful material while preserving trusted instructions and required evidence.

4Why should retrieved webpages be separated from trusted system/developer instructions?▼

Correct Answer: Untrusted content can contain instructions that should not gain authority over the agent

Retrieved content is data, not authority. Clear trust boundaries reduce the risk of context poisoning and prompt injection.

5An agent includes fifty old conversations even though only two are relevant, and performance gets worse. What is the likely problem?▼

Correct Answer: Context noise and poor relevance selection

More context can hide important constraints and add stale or irrelevant information. The context should be selected, not accumulated blindly.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next