AI Agents in Practice: From One Model Call to a Production System
Part 7
〇七Context Is Not Memory
Removing a record from the context does not make the system forget it; keeping a record does not mean the model can see it
In round 1, a debugging Agent receives a constraint from the user: Read-only operations only; do not restart any service. In round 30 it recommends restarting the service that hosts the connection pool. The logs show the constraint was stored in the database the whole time, neither deleted nor changed.
The problem is elsewhere: to keep the context short, the runtime put only the latest 8 records into each request. From round 4 on, the constraint was no longer among the things the model saw. The system "remembered" it; the model "did not know" it.
The root of this failure is treating two concepts as one. In the loops of Article 01 through Article 06, the message list played two roles at once: it was everything the system kept, and it was the input sent to the model every time. As long as nothing is truncated, both roles hold the same content and the difference is invisible. Once truncation starts (Article 03), they come apart.
Two questions, two objects
Separate them, and let each answer one question:
- Context: what did the model see in this request? It is one request's input, bounded by the context window, rebuilt for every request, and gone once the request ends.
- Memory (here, every record the system keeps): what has the system stored so far? It lives in a database, files or object storage, is bounded only by storage capacity, and persists across requests and even across tasks.
Between them is a one-way build step: before each request, the runtime selects, trims and rewrites part of the Memory and assembles it into the Context. The model reaches Memory only through Context; deleting something from Context leaves Memory untouched; and whatever Memory holds but Context does not include does not exist for the model.
The distinction is not new. MemGPT (Packer et al., 2023) borrows the operating-system analogy: the model's context window is main memory (main context), external storage is disk (external context), and a program pages content between the two. In Effective context engineering for AI agents, Anthropic calls this work context engineering, which is about how to choose the set of tokens placed in the window for each inference.
"Memory" also has a narrower meaning in the Agent field: long-term information kept across tasks, such as user preferences and project facts. That is part three (Articles 17 to 20). Memory in this article is broader and means every record the system keeps, including the whole history of the current task.
Two objects in code
The code below writes Memory as an append-only Store and Context as the output of three build functions:
build_full: every record in the Store goes into the context unchanged, as in the previous six articles;build_window: the task description plus the latest 8 records, as in the Agent from the opening;build_layered: task and constraints are always kept, the latest 3 rounds stay verbatim, and older tool results are replaced by a one-line reference saying where the content lives in the Store.
It simulates a 40-round task with one tool call per round: 300 tokens of model output and 1,700 tokens of tool result. Save it as context_vs_memory.py; Python 3.9 or later, no third-party packages:
from dataclasses import dataclass
# ---------- Memory: every record the system keeps; append-only, never deleted because the context changed ----------
@dataclass
class Record:
id: str
round: int
kind: str # task / constraint / assistant / tool_result
tokens: int
text: str
class Store:
"""System-side storage. A list here; in production a database or object store."""
def __init__(self):
self.records = []
def add(self, round_, kind, tokens, text):
rec = Record(f"mem://r{len(self.records):03d}", round_, kind, tokens, text)
self.records.append(rec)
return rec
def get(self, ref):
"""Fetch the original record by reference: when the model needs old content, a tool calls this."""
return next(r for r in self.records if r.id == ref)
def tokens(self):
return sum(r.tokens for r in self.records)
# ---------- Context: before each request, pick part of the Store and assemble what the model sees this time ----------
def build_full(store):
"""Put the whole history into the context unchanged."""
return list(store.records)
def build_window(store, k=8):
"""Task description + the last k records."""
task = [r for r in store.records if r.kind == "task"]
rest = [r for r in store.records if r.kind != "task"]
return task + rest[-k:]
def build_layered(store, recent_rounds=3):
"""Always keep task and constraints; keep recent rounds verbatim; older tool results become one-line references."""
last = max(r.round for r in store.records)
out = []
for r in store.records:
if r.kind in ("task", "constraint") or r.round > last - recent_rounds:
out.append(r)
elif r.kind == "tool_result":
# a one-line reference, about 20 tokens: what was here and where to fetch it
out.append(Record(r.id, r.round, "ref", 20, f"round {r.round} grep_log result, see {r.id}"))
return out
def tokens(view):
return sum(r.tokens for r in view)
def sees_constraint(view):
return any(r.kind == "constraint" for r in view)
# ---------- A 40-round task ----------
def simulate(rounds=40):
store = Store()
store.add(0, "task", 40, "The /orders endpoint got slow in the last 30 minutes. Find out why.")
store.add(0, "constraint", 30, "Read-only operations only; do not restart any service.")
print(f"{'round':>5} {'store':>8} {'full':>8} {'window':>8} {'layered':>8} constraint_seen(window/layered)")
for n in range(1, rounds + 1):
store.add(n, "assistant", 300, f"round {n}: call grep_log on shard {n}")
store.add(n, "tool_result", 1700, f"logs of shard {n} (about 1,700 tokens)")
if n in (1, 5, 10, 20, 40):
f, w, l = build_full(store), build_window(store), build_layered(store)
print(f"{n:>5} {store.tokens():>8,} {tokens(f):>8,} {tokens(w):>8,} {tokens(l):>8,}"
f" {sees_constraint(w)!s:>5}/{sees_constraint(l)!s}")
# at round 40 the round-5 result is needed: the layered view holds only a reference, so fetch it
ref = next(r for r in build_layered(store) if r.kind == "ref" and r.round == 5)
print("ref in context:", ref.text)
print("recalled:", store.get(ref.id).text)
if __name__ == "__main__":
simulate()
Output:
round store full window layered constraint_seen(window/layered)
1 2,070 2,070 2,070 2,070 True/True
5 10,070 10,070 8,040 6,110 False/True
10 20,070 20,070 8,040 6,210 False/True
20 40,070 40,070 8,040 6,410 False/True
40 80,070 80,070 8,040 6,810 False/True
ref in context: round 5 grep_log result, see mem://r011
recalled: logs of shard 5 (about 1,700 tokens)What the results show
The store and full columns are identical. That is exactly why the two concepts get confused: without any build step, Context is the whole of Memory and the two curves coincide. By round 40 both are at 80,070 tokens and still growing linearly; they pass a 128K window around round 64.
The window column stays at 8,040 from round 5 on. The window holds 8 records, so the Context stops growing. The price is in the last column: the constraint record is pushed out of the window in round 4, and from then on the model cannot see it; the False for round 5 in the table is that result. The record is still in the Store, and store.records[1] can be read at any time, but that means nothing to the model.
The layered column rises slowly from 6,110 to 6,810. Each round adds one 20-token reference line, one hundredth of full's growth rate. The constraint stays visible. Older tool results are not in the Context, but references to them are: the model knows "round 5 checked shard 5, and the result is at mem://r011", and can fetch the original through a tool when needed, as the last two lines of output show.
Once separated, each object has its own constraints
With two objects, the design constraints differ too.
The Store's constraints are completeness and traceability. It should be append-only, never deleting, with a stable identifier on every record (the mem://r011 above) and the ability to read the original by that identifier. It is the only source of the Context, so whatever the Store loses, no build step can recover. It is also the basis for the replayable traces of Article 14: to reproduce a task you need the Store, not any single Context.
The Context's constraints are size and relevance. It has a hard limit (the window) and soft limits (the cost and latency computed in Article 02), and Lost in the Middle, cited there, shows that the more you put in, the worse the model uses the middle of it. So the Context's goal is not to hold as much of the Store as possible, but to hold what this step's decision needs.
Put both constraints on one object and they fight: deleting records to shrink the Context breaks the Store's completeness; keeping the Store complete by deleting nothing lets the Context grow without bound. The Agent in the opening had in fact already separated the two (the constraint stayed in the database and was not deleted by the window), but lacked a rule in the Context build: which records stay no matter how old they are.
The builder is a function you can test on its own
Treating Context as the output of build(store) -> context has another engineering benefit: the builder is a pure function that can be tested without the model.
The failure from the opening would have been caught before release with one assertion:
from context_vs_memory import Store, build_window, build_layered, sees_constraint
def make_store(rounds):
"""Build a Store after `rounds` rounds, with one constraint written in round 0."""
store = Store()
store.add(0, "task", 40, "The /orders endpoint got slow in the last 30 minutes. Find out why.")
store.add(0, "constraint", 30, "Read-only operations only; do not restart any service.")
for n in range(1, rounds + 1):
store.add(n, "assistant", 300, f"round {n}")
store.add(n, "tool_result", 1700, f"logs of shard {n}")
return store
for builder in (build_window, build_layered):
# the constraint should be visible at any round count
ok = all(sees_constraint(builder(make_store(r))) for r in range(1, 61))
print(f"{builder.__name__:<14} constraint visible for rounds 1..60: {ok}")
Output:
build_window constraint visible for rounds 1..60: False
build_layered constraint visible for rounds 1..60: True
Tests like this need no model call, finish in milliseconds, and can run in continuous integration (the test process that runs automatically on every commit). Article 16's regression suite puts it alongside the other build rules.
What the next nine articles answer
Once Context and Memory are separate, context management becomes the design of the builder. The remaining nine articles of part two each take one aspect of it:
- Article 08: layers inside the Store: what is core state, what is working context, what lives only in external storage;
- Article 09: a full reproduction of the sliding window losing a constraint, and truncation by interaction unit;
- Articles 10 and 11: the builder needs to know how many tokens each piece has, and how to split the budget between parts;
- Articles 12 to 15: when older history is summarized instead of kept verbatim, what the summary keeps, how to keep it from going wrong, and when to produce it;
- Article 16: the effect of the build on the prefix cache and cost, back to the question of Article 04.
build_layered here is a minimal example, and its retention rules (task, constraints, last 3 rounds) are written by hand. The next article turns those rules into three layers of state and compares full history with layered building on a more realistic task.