An agent with no memory meets you as a stranger every time. Tell it about your gluten allergy in session 12 and it offers you pasta in session 24. Pick how it remembers, then slide time forward.
Learn the four kinds of agent memory, the stores that hold them, the four design patterns the lecture teaches, how memory is tested, and where it still fails.
Choose a kind of memory, then drag the session of the question. Watch which facts reach the answer. Then we build, piece by piece, what sits underneath: the types, the stores, skills, tiers, reflection, maintenance and the tests.
You need a rough idea of what an agent is (a language model in a loop that calls tools) and a little Python for the code. We build the rest from zero.
Based on Lecture 7 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang. Lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 6, Design Patterns.
YOU, SESSION 24Can you recommend a recipe I could cook tonight?
A toy story built on the lecture’s PersonaMem example (slide 11): you say you love Italian food in session 2, then in session 12 that you are allergic to gluten and now cook Mediterranean seafood. The window of 8 sessions, the 40 sessions and the store that keeps the first value it saw for each topic are our illustrative choices; the two replies for the “never updated” and “updated” stores paraphrase the slide.
Chapter 0
See what an agent loses when every session starts empty, and what it gains when it can keep something
Imagine you hire a very capable assistant who has one odd condition: every morning, they forget everything. On Monday you explain that the project uses tabs, not spaces. You show them how to run the tests. You warn them that the staging server is read-only. By noon they work well.
On Tuesday they arrive, smile, and ask what the project is. You explain it all again. On Wednesday, the same. The assistant is not weak. They simply have nowhere to put yesterday.
That is a language model agent with no memory. A session is one run of the agent, from the moment you start it to the moment it stops. A session ends, the text it read disappears, and the next session starts from a blank page. Lecture 7 of CS 329Z is about the cure: agent memory, anything the agent can write down in one session and read back in another, or later in the same session.
The lecture opens with two screenshots, before it says a word about memory. The first shows an AI manager at a small shop. An employee writes that they are running late. The handbook’s attendance rules are in view, and the manager replies that it is no problem. Later the employee clocks in at 11:08, after the promised 10:45. The slide gives no verdict. Take it as a picture of an agent that must keep rules and promises straight over a long stretch of time, and that can only do so if they are written somewhere it can read.
The second is a messaging thread. A user told an agent to look through an inbox and suggest what to archive or delete, and not to act until told. The agent’s tool log shows it deleting messages anyway, while the user types “Do not do that” and “Stop don’t do anything”. The slide does not give a cause. A common cause for this kind of failure is that an instruction lives only in the context, the text the model is reading right now. If that text is shortened or reset, the instruction goes with it. Take it as a warning about instructions, not as a finding about that one run.
Then the slide with the big claim: memory is essential for long-running, multi-session agents. The rest of the lecture breaks that claim into five parts, which the lecture times as 5, 10, 35, 15 and 10 minutes: why memory matters, the types of memory, the architectures, how to evaluate memory, and the open problems. We follow the same order.
The lecture names three problems that appear when an agent has no memory. Each one has a different shape, so each one needs a different fix.
Try each loss below. The model is small on purpose, so you can count it by hand.
Choose a kind of loss, then drag the slider. The top row is an agent with no memory. The bottom row is the same agent with a place to write things down.
Illustrative numbers, ours: a task of 9 steps, 4 facts, and a window that holds the last 30 steps of one session. The lecture names the three losses (slide 9); it gives no counts.
In the first two views the cost of no memory is repetition, and it grows in a straight line with the number of sessions. In the third view the cost is a hole. The agent’s window slides forward, and the goal you gave at step 1 slides out of it. No amount of re-asking fixes that, because you cannot re-ask in the middle of a task you thought the agent was handling.
Slide 10 turns each loss around into a benefit. Personalization: the agent learns your preferences and uses them. Learning from experience: the agent learns a skill in one session and applies it in a later one. Statefulness: you can continue where you left off, for example “open up the proposal we were working on again”. The lecture gives one published example for each.
The first, from the PersonaMem study (Jiang et al., 2025), is the story in the hero. A user says they love Italian food. Ten sessions later they say they are allergic to gluten and now eat Mediterranean seafood. Later still they ask for a recipe. The good agent suggests gluten-free seafood. The bad agent remembers only the first preference and offers pasta. The lesson is subtle: having memory is not enough, the memory must also stay current.
The second, from Agent Workflow Memory (Wang et al., 2024), shows an agent that completes a web task, such as finding a place on a map, and keeps the steps that worked. On the next web task it places those steps in its system prompt (the standing instructions at the top of each request) as guidance, so it starts with a plan that already worked once. Chapter 3 builds this.
The third, from Du et al. (2025), is about statefulness. A user asks to update a flight reservation, a task the agent started in an earlier session. Without multi-session memory, the figure counts 10 turns of conversation before the agent has the details it needs. With memory, it counts 2. The agent finds the origin and destination, the airline and the seat class already written down, and asks only to confirm.
The slides set three learning objectives. Recognize why memory matters in multi-session and user-facing agents. Differentiate memory architectures by their design patterns. Identify the challenges that are still open. Chapters 1 to 7 cover the first two, Chapter 8 covers how to test them, Chapter 9 covers the third.
Course business takes one paragraph. The Laude Institute gave every student $200 more in Amazon credits through a partnership with AWS, and details will follow by message. Homework 1 is due on 30 October. None of this changes the content, so we move on.
Chapter 1
Sort what an agent keeps into working, episodic, semantic and procedural memory, and see where each one lives
Watch a cook in a busy kitchen. On the counter in front of her sit the onions she is chopping and the order ticket she is reading. In her head sits the memory of last Thanksgiving, when the gravy split. She also knows, without looking anything up, that saffron is expensive. And her hands know how to make a roux, with no thought at all.
Those are four different kinds of remembering: what is in front of you, what happened to you, what is true, and how to do things. Psychologists gave them names long ago. The lecture borrows the names, through a 2024 paper called CoALA (Cognitive Architectures for Language Agents, by Sumers and colleagues; our paper lesson goes through it in full).
A cognitive architecture is a plan that says what memories a mind has and what loop it runs to decide what to do. CoALA draws that plan for a language agent. The figure on slide 16 has a large box for working memory at the centre, and three boxes for long-term memory around it: procedural, semantic and episodic. Arrows run from working memory out to actions, and the actions come in two sorts. External actions talk to the world: dialogue, physical, or digital. Internal actions work on memory: retrieval, reasoning and learning.
That split matters for design. An agent that can only act on the outside is a reflex. An agent that can also read and write its own memory can improve. The rest of the lecture is about the internal actions.
Working memory is what the agent can see and reason over right now. For a language model agent this is almost always the context window, the text the model reads on each call. The model reads that text in small pieces called tokens, roughly a short word or part of a word, so we measure the window in tokens. The window starts with the system prompt, the standing instructions placed at the top of every request. After it come the observations, the goals, the user’s input and the agent’s own reasoning so far. On the slide, a box called the context manager feeds a single LLM call.
Episodic memory holds the agent’s past behaviour, as sequences called trajectories: what it saw, what it did, what came back. In a chatbot this is a store of all prior conversations. It is usually the raw log. The slide shows the memory stream from the Generative Agents paper, a plain list of time-stamped lines such as “desk is idle” and “Isabella Rodriguez is writing in her journal”.
Semantic memory stores facts about the world: details about the user, preferences, general knowledge. This is what most people mean when they say a chatbot has memory. The slide shows ChatGPT’s memory panel, a list of short facts such as “Has a 2 year old daughter named Lina” and “Loves to travel”.
Procedural memory holds the rules that apply to working memory to decide how the agent behaves. It is the agent’s skills, the knowledge of how to complete a task. The slide shows a skill file, a short document with a name, a description and instructions. In the CoALA figure, procedural memory is drawn as two boxes, the language model itself and the agent’s code.
Here is the first device. Each card is something an agent might keep. Pick its type, and the card will say what shape the data takes in a real system.
Read the card, then choose the type that fits best. A wrong pick still teaches: the card shows why, and the shape of the real data.
The eight cards and their shapes are ours; the four definitions and the example formats (a memory stream, a list of user facts, a skill file) are from slides 17 to 20.
There is a second, separate question: is the memory inside the model or outside it? Slide 21 gives both answers. Parametric memory is built into the model’s weights, the numbers learned in training. Context memory is text added to the model’s input.
| Type | Parametric (in the weights) | Context (in the prompt) |
|---|---|---|
| Semantic | Pretrained knowledge | Retrieved facts |
| Procedural | Instruction following | Retrieved skills |
| Episodic | Not applicable | Retrieved conversations |
| How it changes | Fine-tune to add knowledge or skills | A context manager pulls in the right memories |
Why is episodic memory “not applicable” in the weights? Training does not store “what happened to me on Tuesday”. It blends millions of documents into general patterns. A particular afternoon cannot be pulled back out. So an agent that must remember its own history needs that history in text.
Almost everything in this lecture is context memory. Weights are slow and costly to change. Text can be written in a second and deleted in another. The question this makes sharp is: who puts the right text into the window? The lecture calls that job the context manager. Try its work below.
Switch memories on and off, then shrink the budget. When the request is too long, the manager drops the lowest-priority piece first.
Token counts are illustrative: a 300-token system prompt, 40 for your message, 90 for three facts, 600 for two raw past episodes, 450 for a skill. The priority order (instructions, your message, facts, skill, episodes) is our choice; real context managers differ.
Look at what the manager had to decide. Raw episodes are long, so they are the first to go. Facts are short and valuable, so they stay. This is the same trade the whole lecture keeps returning to: what is worth the window space?
Chapter 2
Compare files, databases and knowledge graphs by running the same question through each of them
Suppose your agent has been working with you for three months. It has written 5,000 small notes. Today you ask it four questions. “What happened with order 0130?” “What can Maya eat?” “Who else is at Maya’s company?” “What did we decide on 6 October?” Each one needs a different way of finding the right note.
This chapter is about that choice. The lecture frames the whole design of a memory system as three questions, and the third is the subject of this chapter.
What gets stored and retrieved? Facts, specific or general. Procedures. The progress of a conversation. When do we trigger a write or a read? Perhaps the agent calls a memory tool on demand. Perhaps a background worker does it. Perhaps an event fires it, such as the end of a session. How do we store and find memories? That is the choice of store. The slides name three: a filesystem, a database and a knowledge graph.
A filesystem is the folders and files on a disk. In this design, every memory is a file. The agent can manage its own memories, and the folders give you a hierarchy for free. The slide shows a design from LangChain’s Agent Builder: a folder for procedural memory with files such as AGENTS.md, a folder for semantic memory with skill files and knowledge notes, and a folder of dated conversation files for episodic memory.
The memory tools are the ordinary shell commands. ls lists a folder. cat reads a file. grep searches files for a piece of text, and it finds exact matches only. This is why the filesystem is so good at questions with an exact handle, such as an order number or a date, and so weak at questions about meaning.
A vector database stores each note as a list of numbers called an embedding. The numbers are chosen so that notes with similar meaning get similar lists. To search, you embed the question and fetch the notes whose lists lie closest to it. This finds “allergic to gluten” for the question “what can Maya eat?”, though the two share no word. Our retrieval lecture built this from zero, and the slide says simply: recall our RAG lecture.
The slide adds two more database tools. An SQLite database is a small database in one file, handy when you want to filter on metadata such as a date or a user. And BM25 handles exact-term lookup. It scores each note by how many of the question’s words it contains, giving more weight to rare words.
A worked number. With 12 notes, the word “gluten” sits in 1, so its IDF is ln((12 − 1 + 0.5) ÷ (1 + 0.5) + 1) = ln(8.67) = 2.16. The word “maya” sits in 4 notes, so its IDF is ln(2.89) = 1.06. Say a note has the word once and has average length. Then the fraction is 1·2.5 ÷ (1 + 1.5) = 1, so the note scores exactly the IDF. Rare words win.
A knowledge graph stores facts as nodes (things, called entities) joined by labelled edges (relations). “Maya works at Acme” becomes the node Maya, the node Acme, and an edge WORKS_AT between them. Slide 28 shows Zep, a memory service built this way (Rasmussen et al., 2025). Its graph has three levels. The first holds raw episodes, such as conversations and documents. The second holds the entities and relationships pulled out of them. The third holds communities, clusters of related entities with a summary of each.
The strength of a graph is the question that needs two hops: from Maya to her company, then from the company to everyone else who works there. A pile of notes cannot walk that path. A graph walks it in two steps.
Now run the same four questions through all four search methods. The toy memory below holds 12 notes. You can see which notes each method returns and which ones you needed.
Choose a question, then a search method. Green dots mark the notes you need. The three best hits are drawn in warm and numbered.
Toy memory: 12 short notes of our own. grep is a real case-insensitive text match on the one keyword an agent would type. BM25 is the real formula above with k1 = 1.5 and b = 0.75 on the whole question. Vector search uses a hand-placed 2-D map where closer means more similar (real embeddings have hundreds of numbers and use cosine similarity). The graph walk follows the named relation for up to two hops from the entity named in the question.
Run all four questions with all four methods and you will see a pattern that no store wins every time. Grep nails the order number and the date, and finds nothing for “eat”. Vector search finds the allergy by meaning, but blurs the order number into its neighbours. The graph answers the coworker question by walking, and has nothing to say about a date. That is why real systems often combine stores, and why the lecture lists all three.
The lecture comes back to this contest in Chapter 8: on one benchmark of agent trajectories, a plain filesystem scored above retrieval, with the caveat that the two runs used different models.
Chapter 3
Watch an agent keep what worked, as code in a skill library and as steps in a workflow, and reuse it on the next task
The lecture sorts the memory architectures it covers into four patterns, shown on slide 29. Learning procedures from experience: recall past successful trajectories. Tiered memory hierarchy: organise long-term and short-term memory. Reflective memory consolidation: think about memories before storing them. Memory maintenance: clean up, remove and update old memories. Chapters 3 to 7 take them in this order. This chapter is the first.
Think about learning to cook a dish. The first time, you read the recipe, make three mistakes and spend two hours. The second time, you glance at your own notes: “salt the water first; low heat for the sauce”. You finish in forty minutes. Nothing in your brain changed. You wrote down what worked and you read it back. The pattern here is the same, and it is about procedural memory: knowing how.
Voyager (Wang et al., 2023) is an agent that plays Minecraft by writing code. It has three parts. An automatic curriculum picks the next task that is neither too easy nor too hard. An iterative prompting mechanism asks the model to write a program for the task, runs it in the game, and feeds back the game’s response and any errors. A self-verification step then asks the model whether the task really succeeded, and the loop repeats until it did. The third part is the one this lecture cares about: the skill library.
When a program passes verification, Voyager stores it as a skill. The library is keyed by an embedding of the program’s description, a list of numbers that places similar descriptions close together (Chapter 2). On a new task, Voyager embeds the task, fetches the top 5 closest skills, and puts their code in the prompt. Skills can call other skills, so a simple skill becomes a building block for a harder one. The library is a compounding store: every verified success makes later tasks shorter.
The tool below runs that lookup on a toy library of eight skills. It turns the task and each description into a list of word counts, then scores how closely the two lists point the same way. That score is the cosine: 1 means the same direction, 0 means no shared words. It is a stand-in for a real embedding. Pick a task and see which skills come back. Then add the verified new skill and ask again.
Choose a task. The five closest skills come back, with their scores. Press Add the verified skill to store the finished program, then pick the same task again.
Toy library of our own. The real Voyager embeds each program’s description with a text embedding model and keeps the top 5; here the vectors are word counts, with a trailing “s” removed, and the score is their cosine.
Two things to notice. First, a task with no close skill, like collecting lava, gets weak scores, and the agent must work it out from scratch before it can add a skill. Second, after you add a skill, that skill is the best match for its own task. The next agent run starts from a finished program, not a blank page.
Slides 33 and 34 show the paper’s test. The agent must climb the Minecraft tech tree: wooden tools, then stone, then iron, then diamond. The table counts prompting iterations (rounds of the write-run-verify loop) averaged over three runs, with a limit of 160. “N/A” means no run reached that level within the limit. The bracket is how many of the 3 runs got there.
| Method | Wooden | Stone | Iron | Diamond |
|---|---|---|---|---|
| ReAct, Reflexion | N/A (0/3) | N/A (0/3) | N/A (0/3) | N/A (0/3) |
| AutoGPT | 92 ± 72 (3/3) | 94 ± 72 (3/3) | 135 ± 103 (3/3) | N/A (0/3) |
| Voyager without the library | 7 ± 2 (3/3) | 9 ± 4 (3/3) | 29 ± 11 (3/3) | N/A (0/3) |
| Voyager | 6 ± 2 (3/3) | 11 ± 2 (3/3) | 21 ± 7 (3/3) | 102 (1/3) |
Read the iron column: 135 iterations for AutoGPT, 29 without the library, 21 with it. Read the diamond column: only Voyager with its library got there, in one run of three, after 102 iterations. The slide says it plainly: without the skill library this was never achieved. The library pays most where tasks build on earlier tasks.
Voyager stores code that runs in a game. Many agents work on websites instead, by clicking and typing. Agent Workflow Memory (AWM; Wang et al., 2024) keeps the workflow, a reusable list of steps with the particular values blanked out. The figure on slide 35 shows the loop. The agent tries a task. A check asks whether the task was solved correctly. If yes, the trajectory goes to an induction step, which extracts the common sub-routines and writes them down as workflows. If no, the run is thrown away. The saved workflows go into the agent’s system prompt as context for the next task, as slide 37 notes.
The induction prompt on slide 36 asks the model to find the common workflows: reusable sub-routines that repeat across tasks, with at least two steps, and with the details that change (an order number, a button label) replaced by a variable. The paper’s abstract reports that AWM improves success by 24.6% and 51.1% relative on two web-task benchmarks, Mind2Web and WebArena (sets of tasks such as booking or shopping on real sites), while using fewer steps. Slide 38 adds a picture of how quickly this happens: success climbs in a rapid learning phase over the first 40 or so queries, then settles into a stable phase.
To see the mechanism, run the induction yourself. Each row below is one trajectory on a toy order-lookup site. Turn trajectories on or off, and the device finds the steps they share, with the order numbers swapped for {id}. It uses a plain longest-common-subsequence match, a much simpler tool than the paper’s language model.
Switch trajectories on to feed them to induction. Run 4 failed, so leave it off at first, then turn it on to see the harm. At the end, press Redesign the site and replay the workflow.
Toy site and four toy trajectories of our own. The real AWM asks a language model to write the workflows and checks each run with an evaluator; here the common steps come from a longest-common-subsequence match, folded across the chosen runs two at a time.
With runs 1 to 3 on, the shared steps are the core of the job: open Orders, type the number, search, open the row. Run 2 had an extra scroll and run 3 had an extra menu click, and induction drops both, because they are not common. Turn on run 4 and the workflow shrinks to almost nothing. That is the reason for the success check. Failed runs teach the wrong routine.
Now redesign the site, so the button called Orders is renamed Sales, and replay. The saved steps point at something that no longer exists. A stored procedure is only as good as the world it was learned in, and the next chapter looks at that limit.
Chapter 4
Load a skill only when the task calls for it, and learn how to spot a stored procedure that has gone stale
Picture a workshop wall of drawers. Each drawer has a small label: “PDF forms”, “slide decks”, “spreadsheets”. You do not carry every tool in your hands all day. You read the labels, pick the drawer that fits the job, and open only that one. If the drawer holds a manual in a second booklet, you open the booklet only when you reach that step.
That is the design of a skill file, the form of procedural memory that most user-facing agents use today. Slides 39 and 40 show it with Anthropic’s Agent Skills.
A skill is a folder. Inside it is a main file named SKILL.md, and, if the skill needs them, other documents and small scripts. The slide shows a folder called anthropic_brand with SKILL.md, docs.md, slide-decks.md and apply_template.py. The main file has two parts, as the slide labels them. At the top is metadata, written in YAML frontmatter (a small block of key: value lines between two lines of dashes). It holds a name and a description. Below it is free-form content, Markdown text that tells the agent how to do the job: an overview, the brand colours, the typography.
SKILL.md--- name: Anthropic Brand Style Guidelines description: Applies Anthropic's official brand colors and typography to PowerPoint presentations. --- ## Overview This skill gives a pre-branded template and the brand rules. ## Colors Dark: #141413 (primary text and dark backgrounds) ...
Slide 40 follows one request through the context window. Many skills are installed. The agent’s system prompt carries only a short snippet from each, its name and description. The user asks to fill in a PDF. The model reads the labels, sees that the PDF skill fits, and decides to trigger it by reading SKILL.md with a shell command such as cat. The file’s text now enters the context. Inside it, a line points to forms.md for form-filling, so the model reads that file too, and then runs the work.
This is progressive disclosure: three levels, each opened only when needed. Level 1 is the label, always present. Level 2 is the body, loaded on a match. Level 3 is the extra files, loaded at the step that uses them. Notice what picks the skill. In Voyager, a vector lookup picked it. Here the model itself picks by reading descriptions. So the description is the retrieval key, and a vague description makes a skill that never triggers.
Try it. Choose a request and then add more installed skills. The device compares loading every skill into the window with loading in levels.
Pick a request. The agent matches it to a skill by its description. Drag the number of installed skills and compare the two bars against the window.
Illustrative sizes, ours: a 100-token label per skill, a 3,000-token body, a 2,000-token extra file, and a 128,000-token window. The match is the same word-overlap score as Chapter 3, on six named skills; the rest of the installed skills are filler that never match.
With 40 skills installed, loading everything costs 124,000 tokens (40 labels and 40 bodies), close to the whole 128,000 window, before the user has said a word. Loading in levels costs the labels plus one body. The label cost grows by 100 for each new skill, so you can install many skills and pay only for the ones you open.
Slide 41 shows two Minecraft screenshots, an environment and then a changed version of it, with a green tick on the first and three question marks on the second. The point, from a 2026 study by Cao and colleagues: procedural memory stores are not robust to dynamic environments. A skill remembers how a world used to work. In Chapter 3 you saw it: the workflow clicked a button that the redesign had removed.
Treat staleness as a failure with three parts. Symptom: the agent follows a stored procedure with confidence, and it fails on the very first step, or worse, on step six after earlier steps changed something. Measurement: give every skill a use count and a success count, and a date it was last verified. A skill that succeeded 19 times in 20 is healthy. The same skill at 4 in 10 over the last week has gone stale. Fix: when a step fails, let the model fall back to reasoning for the rest of the job, then write the corrected steps back into the file. The slide says that skill files “can also be updated”, and this is what that means.
For generalist, user-facing agents, the lecture calls skill files the common solution. They are plain text, a person can read and edit them, and the agent can edit them too. Our Agent Skills lesson goes deeper, and the OpenClaw skills lesson shows a second system built on the same idea.
Chapter 5
Follow MemGPT as it moves text between a small window and large stores, and see MemoryOS add three tiers with a heat score
Look at how your laptop copes with a program that needs more memory than it has. Fast memory (RAM) is small. The disk is big and slow. The operating system keeps what you are using in RAM and moves the rest to disk, then pulls pieces back when you need them. The program never knows. This trick is called virtual memory.
A language model has the same problem. Its context window is the fast, small memory. Everything else the agent has ever seen lives, at best, somewhere outside. MemGPT (Packer et al., 2024; our paper lesson covers it in depth) copies the operating-system idea, with one twist that the slide states as its key insight: give the LLM tools to manage its own memory.
MemGPT splits memory into main context, the prompt the model reads (in the paper, an 8,000-token window), and external context, everything outside it. The main context has three parts.
External context has two stores. Recall storage holds the complete message history, searchable by string or date (slide 44 labels it “string/date lookup”). Archival storage is a read-write vector database for any length of text (labelled “vector database”). A component called the queue manager writes every message to recall storage and handles the queue. A function executor runs whatever functions the model calls.
The model moves data by calling functions, as it would call any tool (Lecture 4). Slides 45 and 46 show four. working_context.append writes a new fact into working context, as when a user says it is their birthday and the model records it. working_context.replace edits a fact, as when the user says a boyfriend named James is now an ex. Similar functions write to archival storage. And two search functions bring text back: recall_storage.search("six flags") finds earlier messages, and archival_storage.search("nobel physics") returns results one page at a time (the figure shows “page 1/13”), so a big result cannot flood the window. There is no need to search working context, the slide notes, since it is already in the prompt.
One question remains: how does the model know when to save something? The queue manager tells it. When the prompt passes a warning count (the paper’s example is 70% of the window), the manager inserts a memory-pressure message into the queue: a notice that old messages will soon leave. That is the model’s cue to save what matters. If the prompt reaches the flush count (100% in the example), the manager evicts the oldest messages (the example is half the window), writes a new recursive summary from the old summary plus the evicted messages, and puts that summary in the first queue slot. The evicted messages are gone from the prompt, but they stay in recall storage for good.
Run it. The same stream of messages goes to a plain fixed window and to MemGPT. Your user gave a birthday in message 2 and a dog’s name in message 5. Add messages until the window fills, then ask.
Press Add a message and watch the bar fill. Facts sit in messages 2 and 5. The yellow line is the 70% warning, and the dashed line is the 100% flush.
The 8,192-token window, the 70% warning, the 100% flush and the eviction of half the window are the paper’s example settings. The 1,000-token system prompt, the 100-token working context, the 300-token summary, the 25 tokens per saved note, and the two facts are ours. A real summary is lossy, so the toy summary keeps no exact facts.
With the fixed window, the birthday is gone once enough messages push it out, and nothing can bring it back. With MemGPT it is never lost. If the model saved it on the warning, it sits in working context. If it did not, it sits in recall storage and a search finds it, at the price of one more function call. Turn the saving off and ask after a flush to see that second path.
Slide 47 shows the paper’s deep memory retrieval test, where the user asks about something from earlier sessions. Accuracy rises in each case once MemGPT is added. Accuracy is the share of answers that are right. ROUGE-L scores how much the answer’s wording overlaps the correct answer, from 0 to 1.
| Model | Accuracy | ROUGE-L |
|---|---|---|
| GPT-3.5 Turbo | 38.7% | 0.394 |
| GPT-3.5 Turbo + MemGPT | 66.9% | 0.629 |
| GPT-4 | 32.1% | 0.296 |
| GPT-4 + MemGPT | 92.5% | 0.814 |
| GPT-4 Turbo | 35.3% | 0.359 |
| GPT-4 Turbo + MemGPT | 93.4% | 0.827 |
The same slide has a second chart: when the task is to answer from a growing set of retrieved documents, the fixed-context models decline as more documents are retrieved, and MemGPT’s performance is unaffected by increased context length. The reason is that MemGPT pages results in and out of the window and does not need to hold them all at once.
MemoryOS (Kang et al., 2025) pushes the same idea to three tiers, drawn as a flow on slides 48 and 49. Short-term memory (STM) holds recent dialogue pages in a FIFO queue. When it is full, the oldest page moves to mid-term memory (MTM), which groups pages into segments by topic. Long-term persona memory (LPM) holds the user profile, a knowledge base of facts and the agent’s own traits.
What decides when a segment graduates from MTM to LPM? A heat score: the sum of how often the segment was retrieved, how many dialogue pages it holds, and a recency term that fades with time since the last retrieval. A segment whose heat passes a threshold moves its content into the persona. Segments with the lowest heat are evicted when MTM is full. Try the three terms.
Drag the three sliders. The bar shows heat as the sum of its three parts. When it crosses the line, the segment is promoted.
The formula is MemoryOS’s: heat = α · visits + β · pages + γ · e−Δt/μ, with μ = 107 seconds (about 116 days) and a promotion threshold of 5, the paper’s example values. We set α = β = γ = 1, which the paper leaves configurable.
A segment that is retrieved again and again, and covers many pages, earns its place in the persona. A single mention that is never touched again cools down and is eventually evicted.
Chapter 6
See how Reflexion and Generative Agents turn raw experience into short lessons, and how they decide which memory to read back
A chess player loses a game. A week later she remembers every move of it, about 60 of them. That log is of little use. What helps her is one sentence she wrote that evening: “I lose when I trade my bishops early.” The log is episodic memory. The sentence is a reflection, a lesson drawn from the log.
The third design pattern in the lecture adds this step. Before an agent stores a memory, it thinks about it. The slide title is “reflective memory consolidation”. To consolidate is to turn many small, fresh traces into a smaller, more useful whole.
The lecture starts with a refresher on Reflexion (Shinn et al., 2023; our paper lesson). Its loop has four parts. An actor model tries the task. An evaluator scores the attempt. A self-reflection model reads the failed attempt and the score, and writes a short note in plain words about what went wrong and what to do differently. The note goes into an episodic memory buffer. On the next trial, the actor reads that buffer first. Slide 51 shows this as a diagram, with the algorithm beside it.
See the data flow in the device below. It follows a real kind of question, from the HotPotQA benchmark: which magazine was started first, Arthur’s Magazine or First for Women? Step through three trials and read the prompt the actor sees each time.
Choose a trial. The box shows exactly what the actor reads, including the lessons stored from earlier trials.
The question and its true answer (Arthur’s Magazine began in 1844, First for Women in 1989) are real. The three reflections, the token counts and the trial outcomes are our illustration of the loop, not the paper’s logs.
Slide 52 shows what this is worth on HotPotQA. Three curves track the share of solved tasks over trials 0 to 4. A plain model with the correct supporting text stays level. Adding episodic memory of past trials helps a little, and level. Adding the reflection step makes the curve keep rising, from about 0.63 to about 0.74 (values read by eye from the slide’s chart). Raw memory of what happened is not enough. The lesson written about it is what changes the next attempt.
Generative Agents (Park et al., 2023; our paper lesson goes through it) puts 25 language-model characters into a small simulated town. They wake, work, gossip and plan a Valentine’s Day party, all from the same memory design. Slide 54 draws it. The agent perceives the world and writes each observation to the memory stream, a long list of natural-language records with timestamps. When it must act, it retrieves some memories, and acts. Two more loops feed the stream: reflect, which writes new lessons, and plan, which writes intentions.
The memory stream grows without end, and the window is small. So which memories come back? The paper scores every memory with three terms and adds them.
Each of the three is first rescaled to run from 0 to 1 across the candidates (min-max scaling), and in the paper every α is 1. Now play with it. The device holds seven observations of one character, Isabella, who runs a café, and scores them for a question you choose. All the numbers are toy numbers. The scoring is the paper’s.
Choose a question, then move the three weights. Each bar is built from the three terms. The top three memories get a number. Switch reflections on to add two higher-level lessons.
Toy memories, ages, importance ratings and relevance values are ours. The formula is the paper’s: recency decays by 0.995 per hour, each term is min-max scaled over the candidates, and the weights default to 1.
Try these. Set the weights to 0, 0, 1 for the first question and relevance alone picks the party notes. Set recency to 2 and the recent cleaning note moves into the top three, however little it has to do with the question. For the third question, switch on reflections. The two lessons beat every raw observation, because they are about the person and the raw notes are about events. That is the job of reflection.
The paper triggers a reflection when the summed importance of the latest events passes a threshold, 150 in their setup, which in practice means a few times a day. The agent asks the model what the most salient questions about its recent memories are, retrieves memories for each, and asks for high-level insights with citations back to the memories that support them. The reflection is stored in the same stream, so it can be retrieved like any other memory, and it can even be reflected on again.
Does it matter? The paper ran an ablation, a test that switches off one part at a time, and rated how believable the agents’ behaviour was (a TrueSkill score, where higher is better). Slide 56 shows it, and the numbers come from the paper’s text.
| Condition | Believability |
|---|---|
| Full architecture | 29.89 |
| No reflection | 26.88 |
| No reflection, no planning | 25.64 |
| Human crowdworkers acting as the agents | 22.95 |
| No observation, planning or reflection | 21.21 |
Each part adds believability, and the full design scores above the human crowdworkers in the study. The tradeoff, from the lecture’s recap table: abstraction improves reuse, but it can introduce conclusions that the evidence does not support. A reflection is a guess about the past, and a wrong one stored as fact will be believed.
Chapter 7
Watch memories get added, merged, deleted and prepared in the background, and count when thinking ahead pays off
A kitchen with no cleaning ends up unusable. Old milk, duplicate spoons, a label that says “flour” on a jar of salt. Memory stores rot the same way. Each new note might repeat an old one, contradict it, or add a detail to it. Nobody tidies up unless the design says who does.
The fourth pattern is memory maintenance: clean up, remove and update old memories. The lecture shows three examples. The first prepares memory before any question arrives. The second links and refines notes as they come in. The third decides, for each new fact, what to do with the old ones.
Sleep-time compute (Lin et al., 2025; the idea is also developed at Letta) lets an agent “think” about its context offline, between user requests. On slide 59 a raw context, such as “Chad likes the color blue. Chad likes red more than blue. Chad likes grey the most. Chad hates green”, goes through a sleep-time step and comes out as a rewritten context: “Their color preferences are: 1. Grey 2. Red 3. Blue 4. Green (hates).” The slide puts it as: sleep-time agents can rewrite the memories of a primary agent while it sleeps.
Why do this? When a question arrives later, most of the reasoning has already been done and stored. The paper finds that sleep-time compute reduces the test-time compute needed for the same accuracy by about 5 times on two reasoning tasks, and that scaling the offline work raises accuracy by up to 13% and 18% on them. When many related questions share one context, the cost of the offline work is shared among them, and the average cost per question falls by 2.5 times.
The catch is easy to miss: the offline work is paid up front, whether or not anyone asks. It wins only when enough questions arrive, and when the work anticipated them. Test it yourself.
The warm line is the cost per question when every question starts from the raw context. The purple line is the average cost when the context was prepared during sleep time. Drag both sliders.
Illustrative model, calibrated to the paper’s two headline ratios: answering from the raw context costs 10 units; the sleep-time work costs 20 units once and cuts a question it anticipated to 2 units (5 times less); a question it did not anticipate still costs 10. At 10 questions and 100% anticipated, that gives 2.5 times lower average cost. The paper also reports that the more predictable the questions, the better sleep-time compute works.
With one question, sleep time is a loss: 22 units against 10. By the third question it breaks even. At ten, with everything anticipated, it costs 4 per question. Drop the anticipated share to 20% and the advantage shrinks to almost nothing. Sleep-time compute is a bet on predictable use.
A-Mem (Xu et al., 2025) has the key idea on slide 61: build an agent just for memory management. It follows the Zettelkasten method, a way of keeping paper notes in which every note is small, has its own keywords, and points to related notes. When something new arrives, A-Mem builds a note, links it, and lets old notes change.
a note, as data{ "content": "Maya moved to Denver in October.", "time": "2026-10-14", "keywords": ["Maya", "Denver", "move"], "tags": ["location", "personal"], "context": "Maya's home city changed from Boston.", "links": ["note_0412"] }
Mem0 (Chhikara et al., 2025) runs as a background workflow. An extraction step reads the latest messages, with a running summary, and pulls out candidate facts. An update step then takes each candidate, fetches the most similar memories already in the store, and asks the model to choose one of four actions through a tool call: ADD (nothing similar exists, store it), UPDATE (add a complementary detail to an existing memory), DELETE (a stored memory is contradicted, remove it), or NOOP (the store already says this, do nothing). The paper reports a 26% relative gain in an LLM-judged score over OpenAI’s memory feature, and 91% lower p95 latency (the delay that 95 of 100 requests beat) and over 90% lower token cost than putting the whole conversation in the prompt.
Now be the update step. The store holds four memories. Five new facts arrive. For each one, choose the action, then see what Mem0’s rule would do.
Read the store, read the new fact, and choose. The store is then changed by the right action, so each fact lands on the result of the one before it.
Toy store and five facts of our own, with the four actions as the paper defines them. In Mem0 a language model makes each choice, after fetching the top similar memories from a vector store; here the right action is fixed in advance so you can check your own reasoning.
Notice the fourth fact. “Does not live in Boston anymore” does not say where she lives, but it makes a stored fact false, and a false memory is worse than a missing one. The new location comes in the fifth step, as an ADD.
Slide 66 recaps all four patterns in one table. Read it by columns: what is stored, when it is written, when it is read, and the main tradeoff.
| Pattern | What it stores | When it writes | When it reads | Main tradeoff |
|---|---|---|---|---|
| Learning procedures from experience | Reusable code, workflows or procedures | After useful trajectories, or by offline induction | When a related task needs a procedure | Reuse saves effort, but procedures go stale |
| Tiered memory hierarchy | Compact active information plus external detail | As information arrives and context pressure grows | Active memory always; external memory on demand | A smaller context needs reliable memory management |
| Reflective memory consolidation | Lessons and higher-level inferences | After feedback or accumulated observations | During relevant reasoning and planning | Abstraction aids reuse but can add unsupported conclusions |
| Memory maintenance | Revised facts, links, indexes and prepared representations | On new evidence, at insertion, or in background work | Through the maintained store | Better organisation costs compute and can lose information |
Chapter 8
Judge four benchmarks against four properties of a good memory test, and see how each one grew from the gap in the one before
You have built a memory system. A friend asks: does it work? You try a chat of ten messages and it remembers everything. Is that proof? No. Ten messages fit in any window. You try a hard question, but you cannot say what the right answer is, so you cannot score it. You try a long chat, but every question is easy to guess. None of these tests tells you anything.
The lecture asks what makes a memory benchmark worth running, and answers with four desiderata (things we want). A good test is realistic: the memory source (the “haystack”) and the questions should look like real use. It is long-context: there is no point testing memory on short conversations. It is challenging: if it is too easy, it cannot tell systems apart. And it is verifiable: we must know when the system succeeded or failed.
The slides then walk through four benchmarks in a chain. Each one fixes a weakness of the last. After each, the lecture gives a verdict, a green tick for a property met and a yellow square for one met only in part.
LoCoMo (Maharana et al., 2024) tests very long-term conversational memory. Its conversations come from two language-model agents that role-play two people, each with a persona and a timeline of life events. The agents use the Generative Agents design from Chapter 6: they keep a memory, reflect, and can share and react to images. Human annotators then edit the dialogues for consistency. Each conversation spans many sessions, and the benchmark asks several kinds of questions (question answering, summarising events, and generating a reply that fits the images).
The lecture’s key result is on slide 73: even when a model is given the right memories, it cannot always use them. A model that retrieves the right passages still answers some questions wrongly. Memory has two halves, finding and using, and failing at the second is no better than failing at the first.
Verdict (slide 74): challenging and verifiable are met, because the tasks are varied and adversarial and the questions have ground-truth answers. Long-context is partial, at 16.6 thousand tokens per conversation. Realistic is partial too, since agents talking to each other are not the users we care about. The two gaps the slide names: people hold many conversations, and their preferences change over time. And we could simulate chats with an assistant instead of between users.
PersonaMem (Jiang et al., 2025) is the benchmark behind the hero of this lesson. It builds a user persona, then a timeline of events in which preferences change, and simulates many sessions between that user and a chatbot. A question asks for something like a recommendation that fits the latest preference, and the answer is chosen from several options. The question types on the chart of slide 79 include recalling facts the user shared, tracking how a preference evolved, acknowledging the latest preference, and generalising the reasons behind a preference to a new scene.
The result on slide 79: memory and retrieval-augmented systems are essential, and Mem0 helps most with preference evolution and recent preferences. Verdict: long-context and verifiable are met (a conversation can reach almost a million tokens, and a multiple-choice answer has ground truth). Realistic is partial, because multiple choice is not how an agent will use memory. Challenging is partial, because multiple choice with distractors can be guessed. The next question on the slide: what if memory covered agent trajectories, not only conversations?
LongMemEval-v2 (Wu et al., 2026) moves from chat to action. The authors collected rollouts of the Codex agent (with GPT-5.2 and GPT-5-mini) on four WebArena environments, wrote questions by hand in five categories, and made sure that only a few trajectories could answer each one. Then they hid those few among a haystack of 100 to 500 trajectories that do not answer it. The question might be about a detail on a page the agent visited twenty tasks ago.
Slide 85 shows a result worth care. Memory based on a plain filesystem scored above retrieval-based memory. But the slide also notes that the two runs used different models, retrieval with a small Qwen3.5 9B and the filesystem with GPT-5.4-mini, so part of the gap is the model, not the memory. Hold this: you cannot rank memory designs unless the models are held fixed.
Verdict: long-context (the recap table gives 25 to 115 million tokens per question) and challenging (a few relevant trajectories in a huge haystack) are met, and so is verifiable. Realistic is partial: trajectories are closer to agent work, but the test is still questions about old observations, not solving a task.
MemoryArena (He et al., 2026) asks for the thing we actually want. An agent works through a chain of sessions, and each session’s subtask depends on what happened earlier. The four environments, from the figure, are bundled web shopping, group travel planning, progressive web search, and formal reasoning in maths and physics. The scoring is on the solution, whose constraints can be checked. Slide 91 gives the headline: memory controllers were the weakest method, with lots of headroom. Because the task is real and complex, failure cannot be blamed on memory alone. All four properties are met.
Compare the four on size, then read what each one takes from the four properties.
Choose a benchmark. The bars use a log scale, so each gridline is ten times the one before. Squares show the lecture’s verdict: green is met, yellow is partly met.
Sizes and counts are from the lecture’s recap table (slide 94): LoCoMo 28 sessions, about 16k tokens, 7,512 questions; PersonaMem 5 to 60 sessions, 26k to 951k tokens, 5,990 questions; MemoryArena 7 sessions, 40k+ tokens, 766 questions; LongMemEval-v2 100 to 498 sessions, 25M to 115M tokens, 451 questions. Verdicts are the lecture’s property slides (74, 80, 86, 92). The 1M-token line is our reference point, not the lecture’s.
Notice what the device shows when you step through. The size grows by about four orders of magnitude from LoCoMo to LongMemEval-v2. The verdicts improve, and the task moves away from asking about the past toward using the past.
Chapter 9
Face the three problems the lecture leaves open: what to forget, whom to trust with memory, and when not to use a memory
Think of a friend who remembers everything you ever said. At first it feels warm. Then you notice that they bring up a joke from three years ago at a funeral, repeat a secret to the wrong person, and when you ask about the weekend, they begin with your mother’s name. Remembering is not enough. A good memory forgets some things, protects others and knows when to stay quiet.
Slide 96 lists three open problems. Choosing what to remember and to forget: future relevance is unknown when the memory is created. Trust, privacy and user control: memory is an attack vector for agents, and user memories have privacy implications. Using memory correctly: there are many cases of over-personalisation from misused memories. We take them in order.
The slide 97 example, from Ma et al. (2026), is a short chat. A user asks the agent to help pick a time for a weekly check-in. The agent offers two slots. The user answers “Thursday”, then adds, half as a joke, that they do not recognise meetings before 10 as legally binding unless there are pastries. The slide asks: memory or joke? Which aspect to remember? No rule can tell you at write time. The joke may be the one detail that shapes the next ten scheduling chats.
The slide gives three costs that pull in different directions. Future relevance is unknown when a memory is created. Keeping everything raises retrieval, context and maintenance costs. And forgetting can remove useful evidence or unresolved commitments. A forget policy is the rule that decides what to drop when the store is full. Run the experiment below. Thirty memories arrive, the store can hold only some, and then nine questions about earlier memories come in.
Each cell is one memory. Purple cells are kept. A ring means a later question asks about it: green if the memory survived, red if it was forgotten. A small flag marks a promise made at the time. Choose a stream, a policy and a size.
Toy data of our own: 30 memories, an “importance” guessed at write time from a seeded random draw (the three promises, memories 3, 5 and 8, were rated low, as unremarkable at the time), and nine later questions. The cost line assumes 40 tokens of context per kept memory. The lecture’s point is the tradeoff, not these numbers.
Try the second stream with the newest-only policy. The promises from memories 3, 5 and 8 are gone, and so are questions about them. Try the importance policy: it did not know at write time that those three would matter. The third policy, newest plus open promises, rescues them at a small cost. But it works only because someone decided in advance that unresolved commitments are special. That is a design choice, not a law.
Now raise the number kept to 30. Everything is answerable. The cost line shows the price: each question now drags 1,200 tokens of memory into the window, most of it unrelated. The lecture’s summary of the tension is that a memory system must pay either in storage or in forgetting, and neither is free.
Anything the agent reads from memory becomes part of its prompt, and what is in the prompt shapes its actions. That makes memory an attack surface. AgentPoison (Chen et al., 2024; slide 98) shows how. An attacker slips a handful of malicious examples into an agent’s memory or retrieval store, with a carefully optimised trigger phrase. Normal questions behave normally, so the poison goes unnoticed. When a user instruction contains the trigger, the poisoned example is retrieved, and the agent copies it. In the paper’s driving example, a benign instruction produces the action “sudden stop”. The slide’s warning is for procedural memory especially: a stored procedure is something the agent is meant to follow.
Slide 99 (Shao et al., 2025) covers the other side, privacy. An agent acts in the world without fully understanding what you wish to keep private. The figure breaks a single message into the data type, the subject, the sender, the recipient and the principle under which it is sent, because the same fact can be fine to send to one person and a leak to another. Add memory, and the agent now holds many personal details that a careless action could expose.
Three habits follow, though none is fully solved. Record where each memory came from, so a poisoned one can be traced. Let the user see, edit and delete what the agent remembers. And keep memories scoped to a user, so one person’s facts never flow into another’s prompt.
The last problem is the quietest. Slide 100 (Hu et al., 2026) shows a user asking a general question about young voters and elections. The agent’s memory holds personal facts about the user, such as a focus on small healthy swaps in daily life. The reply drags that in with a forced comparison: just as small swaps add up, every young vote is a small win. The figure scores it with an over-personalisation score. The slide’s points: models are sometimes over-eager to use what is in their context; better retrieval or better training to ignore unimportant context can help, but neither is fully solved; and some users like personalisation more than others.
Decide for yourself. Each card gives a question and a retrieved memory. Choose whether the agent should use it.
Five cases of our own, in the spirit of the lecture’s example. Several are judgement calls: a user who likes personalisation might want more used.
The test to apply is short: does this memory change what a good answer should say? A gluten allergy changes a recipe. A focus on healthy snacks does not change an answer about elections. Retrieval finds memories that are related. It does not decide which ones are needed.
Chapter 10
Review the lecture on one page: the numbers, a design checklist, the core as code, and where to read next
The lecture’s summary slide ticks five boxes: motivating agent memory, the types of agent memory, agent memory architectures, evaluating agent memory, and challenges and open problems. This page gives you each in a form you can reuse.
An agent without memory loses its procedures, its knowledge and its progress (Chapter 0). Memory comes in four types: working (the context window), episodic (logs of what happened), semantic (facts) and procedural (skills), and each type can live in the weights or in the context (Chapter 1). For stores, you choose among a filesystem, a database and a graph by the kind of question you expect (Chapter 2). The four patterns then add four moves: keep what worked (Chapters 3 and 4), tier the memory so a small window can reach a large store (Chapter 5), reflect before writing (Chapter 6), and maintain the store in the background (Chapter 7). You check it with a benchmark that is realistic, long, challenging and verifiable (Chapter 8), and you stay honest about what to forget, whom to trust and when not to use a memory (Chapter 9).
| What | Number | Why it matters |
|---|---|---|
| Voyager, diamond tools | 102 iterations (1 of 3 runs) with the skill library; none without | A verified skill library compounds |
| Voyager vs AutoGPT, iron tools | 21 vs 135 prompting iterations | Reuse beats rediscovery |
| Agent Workflow Memory | +24.6% and +51.1% relative success on Mind2Web and WebArena | Induced workflows help web agents |
| MemGPT, GPT-4 deep memory retrieval | 32.1% to 92.5% accuracy | Self-managed tiers beat a fixed window |
| MemGPT queue manager | warn at 70%, flush at 100%, evict half the window | The model is warned before it loses text |
| MemoryOS heat | heat above 5 moves a segment to the persona | Frequent, rich topics become long-term |
| Generative Agents retrieval | recency 0.995 per hour, importance 1 to 10, relevance by cosine, all weights 1 | Three scores decide what returns |
| Generative Agents believability | 29.89 full vs 21.21 with no memory, planning or reflection | Reflection and planning each add |
| Sleep-time compute | about 5 times less test-time compute; 2.5 times lower average cost | Think ahead when questions are predictable |
| Mem0 | 26% relative gain; 91% lower p95 latency; over 90% fewer tokens | Maintained memory beats full context on cost |
| Benchmark sizes | LoCoMo about 16k tokens; PersonaMem up to 951k; LongMemEval-v2 25M to 115M; MemoryArena 766 questions | Tests grew four orders of magnitude |
This is a small, runnable sketch of the pieces in Chapters 6, 7 and 9. The embedding is a toy word count, and decide stands in for the language model that Mem0 asks. Swap both for real parts.
pythonimport math, time def embed(text): # toy embedding: word counts (use a real model) v = {} for w in text.lower().split(): v[w] = v.get(w, 0) + 1 return v def cosine(a, b): dot = sum(a[w] * b.get(w, 0) for w in a) na = math.sqrt(sum(x * x for x in a.values())) nb = math.sqrt(sum(x * x for x in b.values())) return dot / (na * nb) if na and nb else 0.0 class Memory: def __init__(self, text, importance=5, kind="semantic"): self.text, self.importance, self.kind = text, importance, kind self.emb, self.last_used = embed(text), time.time() def minmax(xs): lo, hi = min(xs), max(xs) return [0.0 if hi == lo else (x - lo) / (hi - lo) for x in xs] def retrieve(store, query, k=3, a=(1, 1, 1)): # Chapter 6: recency + importance + relevance if not store: return [] now, q = time.time(), embed(query) rec = minmax([0.995 ** ((now - m.last_used) / 3600) for m in store]) imp = minmax([m.importance for m in store]) rel = minmax([cosine(m.emb, q) for m in store]) score = [a[0] * r + a[1] * i + a[2] * v for r, i, v in zip(rec, imp, rel)] top = sorted(range(len(store)), key=lambda j: -score[j])[:k] for j in top: store[j].last_used = now # reading a memory refreshes its recency return [store[j] for j in top] def write(store, fact, decide): # Chapter 7: ADD | UPDATE | DELETE | NOOP near = sorted(store, key=lambda m: -cosine(m.emb, embed(fact)))[:5] action, target = decide(fact, near) # in Mem0, a language model decides if action == "ADD": store.append(Memory(fact)) elif action == "UPDATE": target.text, target.emb = fact, embed(fact) elif action == "DELETE": store.remove(target) def forget(store, cap): # Chapter 9: newest, plus open promises pinned = [m for m in store if m.kind == "commitment"] rest = sorted((m for m in store if m.kind != "commitment"), key=lambda m: -m.last_used) store[:] = pinned + rest[: max(0, cap - len(pinned))] def build_prompt(system, store, user_msg, budget_words): # Chapters 1 and 5 memories = [m.text for m in retrieve(store, user_msg)] prompt = system + "\nMEMORY:\n- " + "\n- ".join(memories) + "\nUSER: " + user_msg return prompt if len(prompt.split()) < budget_words else system + "\nUSER: " + user_msg
Read it once and name the chapter behind each line. retrieve is the three-term score. write is the four-way decision. forget is a policy with a pinned class. build_prompt is the context manager, falling back to no memory when the budget is tight.
Eight situations of our own, one per idea from Chapters 3 to 7. Real systems often combine patterns.
Lecture 3 built retrieval, the engine under most memory stores. Lecture 6 gave the design patterns for whole agents. This lecture added the part that lasts across sessions. Next, on Monday, the course turns to multi-agent systems, where several agents must share some of what they know. Homework 1 is due on 30 October.
Now press Present or Teach and explain one agent’s memory out loud, from memory: the four types, where each lives, how a new fact is resolved against the store, which memory comes back and why, and what you would forget. Then go back to the recipe at the top, set the question to session 40, and explain why the store that updated its facts still knows about your allergy.
This lesson re-teaches Lecture 7 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang. The ideas, slide order and benchmark verdicts are theirs; the words, devices and toy data are ours. The course’s own lecture slides carry the original figures. Readings: CoALA, MemGPT, Generative Agents.