Context as a Scarce Resource
Treat the context window as a limited budget: see why accuracy and cost suffer as context grows, split the window into shares with a reserve for the reply, keep long-term state outside the prompt, and load tools, skills and sub-tasks only when a step needs them.
Contentsand lesson path
On this page
- Why a Bigger Window Does Not Give Better Answers
- A Context Budget: Splitting the Window
- Working Memory vs Long-Term Storage: Decoupling Context from State
- Practice
- Apply it
- Review prompt
Lessons of Memory & Context Engineering
- Context as a Scarce Resource Concept · 15 min
- Building a Per-Step Context Assembler Worked example · 20 min
- Lab: Compaction for a Fifty-Step Task Lab · 25 min
- Loading Tools and Skills on Demand Worked example · 15 min
- A Long-Term Memory Store with Write and Expiry Policies Lab · 25 min
- Check: Context and Memory Design Review Knowledge check · 8 questions
What you will learn
- Assemble each step's context from instructions, tool definitions, history, retrieved data and tool results within a token budget.
- Reduce context load by loading tools, instructions or skills on demand and by isolating sub-tasks in separate contexts.
Prerequisites: Tokens & Context
01. Why a Bigger Window Does Not Give Better Answers
Current large language models accept hundreds of thousands of tokens, and some accept a million. That makes it tempting to treat the context window as a place to put everything: raw logs, whole database schemas, dozens of tool definitions and the full conversation. When the agent then fails, the first idea is often to add even more context and hope the model finds the part that matters.
In production agents this approach usually makes results worse, not better. Context is not a free, lossless hard drive; it is a limited working space. A model may accept 200k or 1M tokens, yet its accuracy on any single detail often drops as the context grows.
The best-known evidence is the "Lost in the Middle" study by Liu et al. (2023). On question answering and key-value lookup tasks, the models they tested used a relevant passage best when it sat near the start of the input (a primacy effect) or near the end (a recency effect), and accuracy dropped when it sat in the middle. Newer models do better on such tests, but a constraint or observation buried in a long, cluttered context is still easier to miss than one in a short, focused one.
Long contexts also cost money and time. Prompt caching makes a repeated prefix cheaper, but processing a large context still raises time-to-first-token (TTFT, the delay before the first output token) and the bill. An agent that carries 50,000 tokens of raw history on each of thirty steps sends 1.5 million input tokens, most of which the current step does not need.
Irrelevant context also misleads the model. If an agent still carries hundreds of lines of debug logs from earlier failed attempts, it can pick up an old error message and try to fix a problem that no longer exists.
02. A Context Budget: Splitting the Window
A reliable agent treats its context window as a budget that is split between parts of the prompt. The input shares below are a starting point to tune on your own traces, not fixed rules; the output reserve is not a share at all:
-
System prompt and fixed rules (5-10%). The role of the agent, its safety rules and the output format. This part is the same on every call, so it is the best part to cache: prompt caching needs a prefix that is byte-identical from call to call.
-
Goal and plan (5-10%). The goal of the user, the current checklist, and the steps already done and checked.
-
Recent turns (25-35%). The current instruction and the last three to five tool results that the next step needs.
-
Retrieved context (20-30%). Documents, tool definitions or stored facts fetched for this step only, by search or by a plain filter.
-
Completion reserve (the requested output size). Room for the reply, equal to the
max_tokensyou request for this call. The output counts toward the context window, and on current Claude models thinking tokens are part ofmax_tokenstoo (OpenAI'smax_output_tokenslikewise includes reasoning tokens). Some APIs reject a request whose input plusmax_tokensis larger than the window; recent Claude models accept it but stop early when generation reaches the window limit. Either way, the full reply only fits if the input leavesmax_tokensof room. Size the reserve from what this call needs, up to the model's output limit (128K tokens on current Claude models); a fixed percentage is either too small for a long answer or wastes room on a short one.
Checking these shares before every call turns a surprise overflow into a decision your code makes. For instance, if retrieval suddenly adds a 15,000-token PDF excerpt, the check sees that the recent turns no longer fit, and the code shortens the excerpt or extracts the part it needs before it calls the model.
The Python snippet below keeps room for the reply first, then works out how many tokens are left for recent turns once the fixed parts and the retrieved context are counted. It raises an error when fewer than 1,000 remain, so the caller compacts the history before the call instead of after a failure.
from typing import Dict
class ContextBudgetManager:
def __init__(
self, context_window: int, max_output_tokens: int
):
# Input + requested output must fit the window, so reserve exactly the
# max_tokens you request (it includes any thinking), not a fixed share.
self.completion_reserve = max_output_tokens
self.usable_input_budget = context_window - self.completion_reserve
def calculate_allocation(
self, system_tokens: int, goal_tokens: int, dynamic_tokens: int
) -> Dict[str, int]:
fixed_tokens = system_tokens + goal_tokens
available_for_history = (
self.usable_input_budget - fixed_tokens - dynamic_tokens
)
if available_for_history < 1000:
raise ValueError(
f"Context budget exceeded: only {available_for_history} tokens "
"remaining for working memory. Compaction required."
)
return {
"system_and_goal": fixed_tokens,
"dynamic_retrieval": dynamic_tokens,
"working_memory_budget": available_for_history,
"completion_reserve": self.completion_reserve,
}03. Working Memory vs Long-Term Storage: Decoupling Context from State
A useful principle of context engineering is to separate working memory (what is in the prompt right now) from long-term storage (what the system keeps across calls and sessions). A rough comparison is a computer: the context window is like a CPU cache, fast to use but small, and a store such as PostgreSQL, a vector database or Redis is like the disk. The comparison holds for size and speed only. Unlike a cache, every token in the window is paid for again on each call, and a fuller window can make the model use each part less well.
So do not use the context window as your database. Move information both ways:
-
Move old results out. Store finished observations and raw tool outputs outside the prompt, and leave a short reference the agent can use to fetch them again.
-
Bring facts in when a step needs them. Retrieve only the snippets the next step uses.
-
Summarise long stretches. Replace a long run of turns with a short summary of what was done and found, and drop the word-for-word exchange.
The same budget applies to what the agent can do, not only to what it has seen. Three habits keep that part small:
- Load tool definitions on demand. Every tool definition is sent on every call. An agent connected to servers with 100 tools can spend tens of thousands of tokens on definitions before the task starts, and a long list also makes the right tool harder to pick. Keep a few core tools loaded and add a search tool that loads the others when a step needs them.
- Show skills by name first. A skill is a packaged set of instructions for one kind of task. Put only each skill's name and one-line summary in the context, and load its full text when the model decides to use it. This is called progressive disclosure.
- Isolate broad sub-tasks. A wide search, such as reading thirty files to find one function, can run in a separate context (a sub-agent). It returns a short structured result, and the raw files never enter the main context.
Lesson 04 builds all three: a dispatcher that loads tools with permission checks, skills shown by summary, and a sub-task that runs in its own context.
Decoupling context from storage keeps the prompt size bounded even over hundreds of turns. How well the agent remembers then depends on what your summaries and retrieval keep, which lessons 03 and 05 test.
04. Practice
05. Apply it
Rules to apply when you design the memory of an agent:
- Set explicit token limits for system instructions, tool definitions and history before you assemble any prompt.
- Put hard constraints in the system prompt, near the start, and restate the current task goal at the end of the prompt, the two places where models tend to use information best.
- Summarise or prune raw JSON tool results before they enter the history; do not keep megabytes of API responses in working memory.
- Size the reply reserve from the
max_tokensyou request on each call (it already includes any thinking), and check input plus that reserve against the model's context window before sending. - Track prompt tokens per step as a main metric; a sharp jump usually means old context is piling up and needs compaction.
Budgeting this way turns context overflows into checks that fail before the call, keeps each step focused on what it needs, and makes token cost per step something you can predict and alert on.
06. Review prompt
Explain why treating large context windows as infinite storage harms agent accuracy. Describe the "Lost in the Middle" phenomenon, detail the five allocations of a disciplined context budget, and explain how to keep working memory separate from long-term storage.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.