Level 2 Agentic Coding · Building with AI
Context Engineering and Memory
Deciding what goes into a model's context window on every call. Budget the window, retrieve just in time, summarise and trim long conversations, give the system long-term memory, and use prompt caching to make the repeated parts cheap and fast.
- Level
- ●●●●● Intermediate
- Reading
- 15 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 10 concepts →
- Quiz
- 5 questions ↓
This leads to
Project Context and Memory FilesThe full path from zero — 10 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Dot Product, Norms and Similarity
- Large Language Models, Explained Simply
- Prompt Engineering
- Using LLM APIs
- Embeddings and Semantic Search
- Retrieval-Augmented Generation
- Context Engineering and Memory
Read them roughly in this order. See it on the concept map →
Why it matters
A single call to a model is easy to reason about: one prompt, one answer. Real applications are not single calls. A support chat runs for forty turns. A Retrieval-Augmented Generation system adds retrieved documents to every question. An agent calls tools fifty times, and each tool returns a page of output. Everything the model needs must be inside its context window (the maximum number of tokens it can take in at once), and the API remembers nothing between calls (Using LLM APIs). So on every call, something has to decide what goes in.
Context engineering is that decision, made deliberately: curating the whole set of tokens the model sees, not just the wording of the instructions. Anthropic's engineering team describes it as the natural successor to Prompt Engineering. Get it wrong and you see three kinds of failure:
- Cost and speed. You pay for every input token on every call. A chat that re-sends its whole history pays for the first message again on every turn.
- Quality. Models don't use a long context perfectly. Relevant facts buried among irrelevant ones get missed. This degradation as the context fills is often called context rot.
- Hard limits. Eventually the conversation or the agent's work no longer fits at all.
The intuition
Think of the context window as a desk. Everything the model can use right now must be on the desk: instructions, reference documents, notes, the conversation so far. The desk is big, but not infinite, and a cluttered desk makes it hard to find the one page that matters. Behind you is a filing cabinet (a database, files, a vector store) that can hold anything, but the model can only read what is on the desk.
A good assistant keeps the desk tidy. Reference material stays in the cabinet until it is needed. Finished work is filed away with a one-line note on the desk saying where it went. Old drafts are summarised and cleared. Important facts about the client are written on an index card that always stays on the desk.
Key idea Treat the context window as a scarce budget, not a bin. For every call, include the smallest set of tokens that lets the model do the job well: stable instructions first, then the information selected for this step, then the new request.
How it works
Sizes, and why bigger isn't free
Context windows have grown fast: 2,048 tokens for GPT-3 in 2020, 100,000 for Claude in 2023, and a million tokens for several models by 2024–2025. As of late 2026 Anthropic's current models accept up to 1 million input tokens, roughly 750,000 words. See Long Context and Efficient Attention for how models handle such lengths.
A big window doesn't remove the need to choose:
- Cost scales with tokens. On a model priced at $2 per million input tokens, a call with 500,000 tokens of context costs $1.00 before the model writes a word. At 1,000 calls a day that is $1,000 a day.
- Latency scales with tokens. The model must process the whole input before producing the first output token.
- Attention is spread thinner. The "Lost in the Middle" study (Liu et al., 2023) found models used information at the beginning and end of long contexts better than in the middle. Newer models do much better, but irrelevant material still competes with relevant material.
Budgeting the window
Start by writing down the budget, like a household budget. A worked example for a support assistant on a model with a 200,000-token window (many deployments impose a smaller working budget than the model's maximum, to control cost and quality):
| Part | Tokens | Changes |
|---|---|---|
| System prompt (role, rules, examples) | 3,000 | never |
| Tool definitions | 4,000 | rarely |
| Long-term memory about this user | 1,000 | per user |
| Retrieved documents (8 chunks × 500) | 4,000 | per question |
| Summary of older conversation | 1,000 | every few turns |
| Recent turns, verbatim | 6,000 | every turn |
| The new message | 200 | every turn |
| Reserved for the reply, including thinking | 16,000 | — |
| Total | 35,200 |
This uses under a fifth of the window, and that is deliberate. When a part threatens to grow (a 30-page document pasted by the user, a tool that returns a megabyte of logs), you decide in code what to do: truncate, summarise, store it and keep a reference, or fail clearly. You don't let it silently push out the system prompt.
Strategy 1: select just in time
Don't load everything up front. Keep lightweight references (file names, document ids, search queries) in context and load the content only when it is needed. RAG does this for documents. Tools do it for live data: rather than pasting a whole customer database into the prompt, give the model a lookup_customer(id) tool. Agents that work with codebases do it by listing files and reading only the ones that matter.
Strategy 2: compress what you keep
Long conversations need conversation summarisation: keep the most recent turns word for word, and replace older turns with a summary. A typical scheme:
- Keep the last turns (or the last few thousand tokens) verbatim.
- When the verbatim part exceeds its budget, take the oldest turns, ask a model to fold them into the running summary, and delete them.
- Put the summary above the recent turns in every request.
Summaries lose detail, so tell the summariser what matters for your application (decisions made, numbers agreed, open questions, the user's stated preferences). For agents, the same idea is called compaction: when the context approaches its limit, summarise the work so far and continue in a fresh window from the summary. As of 2026 several providers offer this server-side. Anthropic's API, for example, has a beta compaction feature and a context-editing option that clears old tool results automatically.
Tool outputs are often the biggest offenders. Truncate them, keep only the fields you need, or store the full output and give the model a short summary plus a reference it can use to fetch more.
Strategy 3: memory beyond the window
Short-term memory is what the conversation currently holds: recent turns and the running summary. Long-term memory persists across sessions: facts about the user ("allergic to penicillin", "prefers metric units"), decisions, and the state of ongoing work. It lives outside the model, in a database or files, and gets three operations:
- Write: decide what is worth remembering. Either your code extracts facts after each conversation (often with an LLM and a schema), or the model is given a tool to save notes itself. Anthropic calls the second approach structured note-taking and offers a memory tool for it.
- Retrieve: before each call, select the memories relevant to the new message, by similarity, recency, importance or simply "always include the profile".
- Update and forget: facts change ("I've moved to Bristol"). Store dates with memories, let new facts replace old ones, and give users a way to see and delete what is stored.
The MemGPT paper (Packer et al., 2023) framed this like an operating system managing memory: the context window is RAM, external storage is disk, and the model moves information between them with function calls.
Strategy 4: isolate work in sub-agents
When a task involves a lot of reading or exploring (searching a codebase, comparing twenty documents), give it to a sub-agent: a separate model call or loop with its own clean context window, which returns only a condensed result to the main agent. The main context receives 500 tokens of findings instead of 50,000 tokens of raw material. Multi-Agent Systems covers the patterns and their costs.
Prompt caching
Many requests start with the same long prefix: the same system prompt, the same tool definitions, the same 50-page manual, the same conversation so far. Processing that prefix is most of the work. Prompt caching lets the provider store the model's internal state for the prefix (the The KV Cache and Fast Inference) and reuse it when the next request starts with exactly the same tokens. A request that reuses a cached prefix is a cache hit: it costs much less and returns its first token sooner.
The rules, as of late 2026:
- It is a prefix match. Any change, even one character, invalidates the cache from that point on. So put stable content first (tools, system prompt, documents) and volatile content last (the new question, a timestamp). A timestamp at the top of the system prompt silently disables caching for everything after it.
- Anthropic caches when you mark a breakpoint with
cache_control. Writing to the cache costs a little more than normal input (1.25 times for the default 5-minute lifetime, 2 times for a 1-hour lifetime). Reading costs a small fraction of normal input: one-tenth on many models, less on the newest ones. Each hit refreshes the lifetime. There is a minimum prefix length, which depends on the model. - OpenAI caches long prompts automatically and bills cached input tokens at a discount.
- Check the response's usage fields (
cache_creation_input_tokensandcache_read_input_tokenson Anthropic) to confirm caching is actually happening.
Worked example. A user asks 100 questions about a 50,000-token manual within one session, on a model priced at $2.00 per million input tokens, with cache writes at $2.50 and cache reads at $0.10 per million (Claude Sonnet 5.5's prices in November 2026). Without caching: $100 \times 50{,}000 \times 2.00 / 10^6 = $10.00$. With caching: one write, $50{,}000 \times 2.50 / 10^6 = $0.125$, plus 99 reads, $99 \times 50{,}000 \times 0.10 / 10^6 = $0.495$, for a total of $0.62. That is a 94% saving on the manual's tokens, and every answer starts faster. This is also why "put the whole document in the prompt and cache it" can beat Retrieval-Augmented Generation for a single large document used intensively.
In code
A small memory manager, runnable offline. It keeps recent turns verbatim within a token budget, folds older turns into a running summary, and selects the most relevant long-term fact for each new message. The summariser is a crude stand-in (it keeps the first clause of each turn), so you can see what lossy compression does.
import re
def n_tokens(text):
return max(1, len(text) // 4) # rough rule: ~4 characters per token
class Memory:
"""Short-term memory: recent turns verbatim, older turns folded into a summary.
Long-term memory: facts saved explicitly, selected by relevance to the new message."""
def __init__(self, summarise, budget=60):
self.summarise, self.budget = summarise, budget
self.summary, self.turns, self.facts = "", [], []
def add_turn(self, role, text):
self.turns.append(f"{role}: {text}")
while sum(map(n_tokens, self.turns)) > self.budget and len(self.turns) > 2:
oldest = self.turns.pop(0) # compress, don't just drop
self.summary = self.summarise(self.summary, oldest)
def remember(self, fact):
self.facts.append(fact)
def context(self, message, k=1):
words = lambda t: set(re.findall(r"[a-z]+", t.lower())) - {"is", "a", "my", "and", "the"}
relevant = sorted(self.facts, key=lambda f: -len(words(message) & words(f)))[:k]
return "\n".join(["<facts>", *relevant, "</facts>",
f"<summary>{self.summary}</summary>", *self.turns,
f"user: {message}"])
# Stand-in summariser: keep the first clause of each folded turn. Use an LLM in practice.
def short_summary(summary, turn):
return (summary + " | " if summary else "") + turn.split(",")[0].split(".")[0]
mem = Memory(short_summary)
mem.remember("The user's dog, Biscuit, is allergic to chicken protein.")
mem.remember("User lives in Leeds and prefers metric units.")
mem.remember("User is vegetarian but the dog is not.")
for role, text in [
("user", "I want to plan meals for my dog, he is a 20 kg spaniel"),
("assistant", "Great, a 20 kg active spaniel needs roughly 1,000 to 1,200 kcal a day."),
("user", "Can you suggest a weekly menu, nothing too expensive"),
("assistant", "Here is a simple plan built around rice, fish and vegetables."),
]:
mem.add_turn(role, text)
ctx = mem.context("Is turkey a good protein for my dog?")
print(ctx)
print("tokens:", n_tokens(ctx))
# <facts>
# The user's dog, Biscuit, is allergic to chicken protein.
# </facts>
# <summary>user: I want to plan meals for my dog</summary>
# assistant: Great, a 20 kg active spaniel needs roughly 1,000 to 1,200 kcal a day.
# user: Can you suggest a weekly menu, nothing too expensive
# assistant: Here is a simple plan built around rice, fish and vegetables.
# user: Is turkey a good protein for my dog?
# tokens: 96
Two things to notice. The allergy fact came from long-term memory, selected because it shares "dog" and "protein" with the question, and it is exactly what a good answer about turkey needs. And the summary dropped "he is a 20 kg spaniel" from the first turn. Here the weight survives in a later turn, but in a longer chat it would be lost. That is why real summarisers are told what to keep, and why durable facts belong in long-term memory rather than in the summary.
In production, replace short_summary with an LLM call ("Update this summary with the new turn. Keep names, numbers, decisions and open questions."), count tokens with the provider's token counter, and store facts in a database.
Prompt caching with Anthropic's SDK. The cache_control marker on the last system block caches everything up to it (tools and system prompt). The question, which changes every time, comes after it:
import anthropic
client = anthropic.Anthropic()
manual = open("printer_manual.txt").read() # ~50,000 tokens, identical every call
def ask(question):
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=2000,
system=[
{"type": "text", "text": "You answer questions about the printer manual below."},
{"type": "text", "text": f"<manual>\n{manual}\n</manual>",
"cache_control": {"type": "ephemeral"}}, # cache everything up to here
],
messages=[{"role": "user", "content": question}],
)
u = response.usage
print(f"cache write {u.cache_creation_input_tokens}, cache read "
f"{u.cache_read_input_tokens}, uncached {u.input_tokens}")
return next(b.text for b in response.content if b.type == "text")
ask("What does error E-4012 mean?") # first call: large cache write
ask("How do I clean the print head?") # within 5 minutes: large cache read
Common pitfalls
- Unstable prefixes. A timestamp, a random request id, or a JSON object whose keys come out in a different order each time, placed early in the prompt, quietly disables caching. Keep the prefix byte-for-byte identical.
- Everything into the summary. Summaries drift and lose details with every fold. Keep durable facts (names, numbers, preferences, decisions) in structured long-term memory.
- Unbounded tool output. One tool that returns 80,000 tokens of logs can fill the window and push out the instructions. Cap and summarise tool results.
- Remembering the wrong things. Memory written automatically can store mistakes, jokes taken literally, or instructions injected by a malicious document, and then repeat them in every later session. Review what gets written, and let users inspect and delete it.
- Assuming a bigger window fixes it. Moving to a 1-million-token model without curating the context usually raises cost and latency, and quality may not improve.
Watch out Long-term memory is personal data. Storing what users say across sessions brings privacy obligations: tell users what is remembered, let them see and delete it, keep each user's memories strictly separate, and never retrieve one user's memories into another's context. See Privacy, Data and Copyright.
Where it leads
- AI Agents: agents live or die by context management across dozens of tool calls.
- Multi-Agent Systems: sub-agents as a way to keep each context small and focused.
- Tool Use and Function Calling and Model Context Protocol: just-in-time access to data instead of pasting it in.
- Long Context and Efficient Attention and The KV Cache and Fast Inference: what happens inside the model with very long inputs, and the mechanism behind prompt caching.
- Evaluating LLM Applications: measuring whether summarisation or memory actually improves answers.
- Building AI Products: cost and latency budgets in practice.
A bit of history
Early LLM applications were limited by tiny windows: GPT-3's 2,048 tokens forced developers to summarise and truncate aggressively. Windows then grew quickly: GPT-4 launched in 2023 with 8,000 and 32,000-token versions, Anthropic offered 100,000 tokens in May 2023 and 200,000 that November, and Google's Gemini 1.5 reached a million tokens in early 2024. Research projects explored memory beyond the window, notably the generative agents simulation (Park et al., 2023), whose characters stored and retrieved memories, and MemGPT (2023). Anthropic introduced prompt caching in August 2024, and OpenAI added automatic caching that autumn. As agents became practical in 2025, the term context engineering caught on to describe the whole discipline of deciding what a model sees, and providers began shipping memory tools, context editing and automatic compaction.
Try it
- In the memory code, lower
budgetto 30 and add four more turns. Print the summary after each turn. At what point does information you would need later disappear?- Write a better stand-in summariser that keeps every number in a folded turn (hint:
re.findall(r"\d[\d,.]*", turn)). Does the 20 kg survive now?- Using the caching worked example, compute the cost of 10 questions instead of 100. Then compute it with the 1-hour lifetime (write cost 2 times the base price, so $4.00 per million). When is the longer lifetime worth it?
Hint for 3: with 10 questions the 5-minute cache costs $0.125 + 9 \times 0.005 = $0.17$ against $1.00 uncached. The 1-hour cache only pays off when questions are spaced more than 5 minutes apart, so the shorter cache would expire between them.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Effective context engineering for AI agents
Treats the context window as a limited attention budget: context rot, compaction, structured note-taking, sub-agents and just-in-time retrieval.
Prompt caching (Claude)
How to mark a reusable prompt prefix with cache_control, the cache lifetimes, what invalidates the cache, and how cached tokens are priced.
Lost in the Middle: How Language Models Use Long Contexts
Models use information at the start and end of a long context better than information in the middle. Explains why ordering retrieved passages matters.
MemGPT: Towards LLMs as Operating Systems
Manages a model's limited context like an operating system manages memory: the model moves information between its context and external storage with function calls.
Building Effective Agents
A clear, practical essay on agent patterns (workflows vs agents) and when to use each.
Patterns for Building LLM-based Systems & Products
A long practitioner's essay on evals, RAG, fine-tuning, caching, guardrails, defensive UX and collecting feedback.
AI Engineering
Building applications on foundation models: evaluation, prompting, RAG, agents, fine-tuning, inference optimisation.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/context-engineering.md