A model remembers nothing. Each request is everything the model knows at that moment, and whatever an agent seems to remember was stored by your code and put back into a request. This creates two problems on two timescales. Inside one run, the context grows with every step. In Notebook 6a, a 14-step task that reads twelve files ends with a 3,645-token request, and the run sends 30,960 input tokens in total. Across runs, a new run starts empty unless something loads the old one. Users then repeat themselves in every conversation. This module treats both as one question: of everything the agent has stored, what should go into the next request?
Notebooks
Notebook 6a: Context management measures where the tokens of a long run go. It builds a sliding window that does not break tool calls, compacts old tool results and summarises history. It leaves the rule for when to act for you to write, and compares four strategies on one task. Notebook 6b: Sessions and long-term memory stores conversations as files that survive a restart and resumes a paused tool call in a new process. It extracts durable facts about a user, de-duplicates them, and injects them into a later conversation.
Storing is not sending
The agent from Module 4 keeps an append-only log of events and computes each request from it. Module 4 treated that as bookkeeping. Here it becomes the main design freedom: the log can keep everything while the request carries much less.
Definition 6.1 (Context engineering).Context engineering is choosing, at each model call, what the request contains: which instructions, which parts of the stored history, which retrieved documents and memories, and in what form. The event log is what the agent stores. The request is what it presents to the model, and it is computed from the log by a function you control.
The reason to care is cost, and the cost grows faster than the run. Write
which grows with the square of the number of steps. In Notebook 6a the first request is 388 tokens. Each step then adds about 250 tokens on average (from 151 to 656, depending on the file just read), and the total of 30,960 is more than eight times the largest single request. Most of it is tool output. In the last request, tool results take 74.8% of the tokens, tool calls 14.5%, tool schemas 9.4%, and the user’s question less than 1%. Long contexts also cost quality, not only money: Module 5 cited the evidence that models use the middle of a long context poorly.
Three ways to shrink a request
Definition 6.2 (Context reduction).A sliding window sends only the most recent part of the history, together with the instructions and the task. Compaction keeps every step but replaces old tool results with short stubs that say what was there. Summarisation asks a model to rewrite the older steps as a summary, which replaces them in the request.
Each of the three strategies (Definition 6.2) has a trap. A window must cut at a boundary between steps.
A tool result whose call was cut off is invalid input for most APIs. In Notebook 6a, the
obvious slice record[:1] + record[-8:] starts with a result whose call call_0010 is
gone, and sliding_window moves the cut so that calls and results stay together.
Compaction is cheap and loses contents. One stub reads “read_file(…) returned 2,454
characters; call it again if needed”, and compaction shrinks one request from 3,818 to
1,825 tokens. Summarisation keeps what matters, if the summariser is good. It costs extra
model calls.
The notebook gives all four strategies (none, window, compact and summarize, the
values of strategy=) the same 1,500-token budget and the same audit task: list every
amount of money in two handbook folders, file by file. The answer key has 27 amounts in 9 files.
| strategy | outcome | amounts found | agent tokens | summariser tokens | largest request |
|---|---|---|---|---|---|
none | finished in 14 steps | 27 of 27 | 30,960 | 0 | 3,645 |
window | hit the 24-step limit | 0 of 27 | 31,301 | 0 | 1,569 |
compact | finished in 14 steps | 3 of 27 | 17,288 | 0 | 1,652 |
summarize | finished in 14 steps | 27 of 27 | 13,176 | 5,150 | 1,195 |
The failures are more instructive than the success. The window dropped the agent’s record of progress. With the early calls gone, it could not tell which folders it had listed and which files it had read, so it started over, again and again, until the step limit. Its requests stayed small, and its total was the largest of all four. Compaction kept the record but not the contents. The stubs told the agent which files it had read, but not what was in most of them. It reported three amounts and said that the list may be incomplete, which is honest but not useful. The summary kept both the progress and the findings, in a structure of findings, work done and still to do, at a cost of 5,150 summariser tokens.
Remark 6.1 (What a summary must keep).A summary is a lossy compression chosen by a model. For an agent, the parts that must survive are the task and its constraints, what has been done, what was found, and what is left. These are the parts that let the next step continue the work. CS329Z Lecture 6 calls this preserving continuity. The offline summariser in Notebook 6a copies numbers with a regular expression, so at its default settings it never drops one. A real model can drop a number or change one, and nothing in the request would show the error. A summary is only as reliable as the model that wrote it.
When to act
A context manager needs a second decision besides how to shrink: when. Notebook 6a
leaves this to you. should_compact(stats) in agentlab/memory/context.py is a short
function whose docstring lists three policies. One acts when the request reaches 80% of
the token budget. One acts every fourth turn. One acts when tool output takes most of a
request that is already half the budget.
def should_compact(stats: ContextStats) -> bool:
return stats.tokens >= 0.8 * stats.budget # replace with your policyThe trade-offs are not only about tokens. Providers cache the start of a request (Module 2), and a cached prefix is cheaper and faster. Every time the context manager rewrites old history, the cached prefix becomes invalid. A policy that shrinks a little on every step can cost more than one that waits and then makes one large cut. The “every fourth turn” policy is crude, but it changes the prefix at predictable steps only.
Sessions: one conversation, many runs
Inside a run, the problem is too much context. Across runs, the problem is none: the next run starts with an empty event log, so there is nothing for context engineering (Definition 6.1) to choose from.
Definition 6.3 (Session).A session is the stored state of one conversation: its id, its user, its events and its state dictionary. A session manager loads it into the execution context before a run and saves it after, so each run continues where the last one stopped.
In Notebook 6b, JsonSessionManager writes one JSON file per session, and run_in_session
wraps the load, the run and the save. “Where do I live?” is answered from an earlier turn
of the same session, while a new session id knows nothing. A new manager and a new agent,
as after a restart, still find the conversation in the file. The session also stores tool
calls that are waiting for approval. A flight booking paused for confirmation can be
approved by a different process later, with no new user message. Module 5 paused a call
inside one process. A session (Definition 6.3) makes the pause survive a restart.
A file per session is fine for one process. A service with many users needs a database behind the same interface. It also has to handle two requests for the same session at once, and delete a user’s sessions when they ask.
Long-term memory: what to carry between conversations
A session holds one conversation. Some things a user says matter in every later conversation: a seat preference, a diet, the team they work on. The cognitive-architecture framework CoALA (Sumers et al., 2024) gives useful names for the kinds of memory an agent has:
| kind | what it holds | in this course |
|---|---|---|
| working | what the model sees now | the request (Notebook 6a) |
| episodic | what happened, step by step | session event logs (Notebook 6b) |
| semantic | facts about the user and the world | long-term memory items (Notebook 6b) |
| procedural | how to do things | instructions and skills (Module 8) |
Definition 6.4 (Long-term memory).Long-term memory stores facts across conversations in three steps. Extract: after a conversation, a model writes durable facts as structured items, each one sentence that makes sense on its own. Store: each item is added to a per-user store unless an existing item makes it redundant. Recall: before a model call in a later conversation, the items most relevant to the current message are added to the instructions.
Notebook 6b runs all three steps (Definition 6.4). From a conversation containing “I prefer aisle seats, and I’m vegetarian” and “This time I need to land before noon”, extraction keeps two items and leaves the one-off landing time out. A later conversation repeats the seat preference, and the duplicate check skips it at cosine similarity 1.00. In a new conversation, “Book me a flight from Denver to Oslo on 3 April” then becomes a booking for an aisle seat and a vegetarian meal. The memories are labelled in the instructions as possibly out of date, so that what the user says now takes priority.
Remark 6.2 (Similar is not the same).The duplicate check compares how alike two sentences look. “Prefers window seats on flights” has similarity 0.78 to the stored “Prefers aisle seats on flights”. That is below the 0.8 threshold, so the contradiction would be stored next to the original. Lower the threshold and the user’s change of mind is skipped instead. No threshold fixes this, because the question is about meaning. The book asks a model to label each new item ADD or SKIP. Mem0 (Chhikara et al., 2025) goes further, with four operations (ADD, UPDATE, DELETE and NOOP), so a new fact can replace an old one.
Memory also raises questions that are not about retrieval. It is personal data, so users should be able to see, correct and delete what is stored. It is also an attack surface. Anything written to memory is replayed into future prompts, so text that convinces the agent to “remember” an instruction gets a lasting foothold (Module 12). MemGPT (Packer et al., 2023) takes a different approach from the pipeline above. It gives the model tools to manage its own memory, in tiers like an operating system’s main memory and disk.
Try this
- In Notebook 6a, replace the body of
should_compactwith the “tool share” policy from its docstring and rerun the four strategies. Does compaction now find more amounts? - With a sliding window,
in equation stops growing. Why is the window’s total still the largest of the four? - Give the sliding window
keep_last=16instead of 8. Does the agent now finish? What is the smallest window that does? - Change the summariser so it keeps only “Key findings” and drops “Work done” and “Still to do” (Remark 6.1). What does the agent do next?
- In Notebook 6b, add an update rule to
LongTermMemory.add. If a new item has the same kind as a stored one and mentions the same subject, replace the old item (Remark 6.2). Test it with “I prefer window seats now.”
Readings
- Hur and Song, Build an AI Agent (From Scratch), Manning 2026, chapter 6.
- Stanford CS329Z, Engineering AI Agents, Lecture 6: Agent design patterns (slides), the part on context management, and Lecture 7: Agent memory architectures (slides).
- Anthropic, Effective context engineering for AI agents, 2025.
- Sumers et al., Cognitive architectures for language agents, TMLR 2024.
- Packer et al., MemGPT: towards LLMs as operating systems, 2023.
- Park et al., Generative agents: interactive simulacra of human behavior, UIST 2023.
- Chhikara et al., Mem0: building production-ready AI agents with scalable long-term memory, 2025.