part II · chapter 6 of 17

Memory

How an assistant keeps what matters about you across conversations, and forgets what it should.

why it matters

Makes an assistant feel continuous, and draws the line between memory (about the user) and retrieval (about the world).

before this: chapter 5, Data engineering and retrieval

in this chapter · 10 sections
  1. 6.1Why a model forgets
  2. 6.2Memory is not retrieval
  3. 6.3Kinds of memory
  4. 6.4The memory lifecycle
  5. 6.5Choosing what goes in the prompt
  6. 6.6Keeping memories apart, private and correct
  7. 6.7Tools for memory
  8. 6.8Build it: an assistant that remembers you
  9. 6.9The maths underneath
  10. 6.10Where people go wrong

You tell an assistant you are vegetarian. Ten minutes later it suggests a chicken recipe. Close the app, open it tomorrow, and it has no idea who you are. Every one of those failures is a memory failure, and none of them is the model's fault. A model remembers nothing between calls. Anything that feels like memory is something your code saved, chose and sent back in. This chapter is about building that, well.

Each section follows the same five steps: an everyday picture, the idea in plain words, how it actually works, a line to say back to check yourself, and something small to try.

Why a model forgets

Picture it. A brilliant consultant with no long-term memory. Every morning they read the notes on their desk and then do excellent work. If the notes are wrong, missing or about someone else, the work is wrong, however brilliant they are.

In plain words. A model only knows two things: what it learned in training, and what is in the prompt you send right now. It keeps nothing from one call to the next.

How it works. A chat API is stateless (chapter 4). The conversation you see is your code resending every earlier message on every call. That works for one conversation, until it gets long: each turn costs more tokens, takes longer, and eventually overflows the . And it does nothing across conversations: close the tab and the list of messages is gone unless you stored it.

So "memory" in an AI application is three engineering jobs:

  1. Decide what is worth keeping from a conversation.
  2. Store it, safely, against the right user.
  3. Bring back the right pieces at the right moment, inside the prompt.

Say it back: the model never remembers; my code remembers for it, and the prompt is how the memory gets back in.

Try it. Call a model twice: first say your name, then in a separate call ask "what is my name?". Then send both turns in one call. The difference is all of memory, in miniature.

Memory is not retrieval

Picture it. A library and a diary. The library (retrieval, chapter 5) holds facts about the world, the same for everyone who walks in. The diary holds what happened between you and this one person.

In plain words. Retrieval finds knowledge in documents. Memory keeps what you have learned about a user and your conversations with them.

How it works. The two look alike under the hood: both store text, often with embeddings, and both search it and put the results in the prompt. They differ in what they hold and how they change:

RetrievalMemory
Aboutthe world: documents, policies, datathis user: preferences, history, decisions
Written byan ingestion pipelinethe conversation itself
Changeswhen documents changeevery session, sometimes every turn
Sharedacross users, filtered by permissionnever shared between users
Main riskout-of-date or missing factsremembering wrong, or leaking to someone else

A real assistant uses both: "your refund policy" comes from retrieval; "you prefer short answers and you already asked about order A1234" comes from memory.

Say it back: retrieval answers "what is true?"; memory answers "what do I know about you?".

Try it. For an assistant you use, write down three things it should know from documents and three it should know about you. If any item fits both lists, decide which store owns it.

Kinds of memory

Picture it. Your own memory works in layers. What someone said a second ago (you can repeat it word for word). Yesterday's lunch with a friend (an event). The fact that your friend is allergic to nuts (a fact you keep). How your friend likes their tea (a habit you have learned).

In plain words. Assistants use the same layers: the conversation right now, past events, lasting facts and learned preferences. Each is stored and used differently.

How it works.

  • Short-term (working) memory is the current conversation: the recent turns, kept in full. It lives in the prompt and is usually stored per session (in Redis or Postgres), so a page refresh does not lose it.
  • Long-term memory survives across sessions. It splits three ways:
    • Episodic: things that happened. "On Tuesday we drafted the launch email and chose the second subject line."
    • Semantic: facts about the user. "Works in Pune. Uses Postgres. Vegetarian."
    • Procedural: how they like things done. "Wants code in TypeScript. Prefers bullet points to paragraphs."

Each kind wants different handling. Semantic facts should be few, current and easy to correct. Episodes can be many, and are found by searching. Procedural preferences belong in every prompt, near the instructions, because they shape every answer.

Say it back: short-term is the conversation in the prompt; long-term is what I saved, as events, facts or habits.

Try it. Take a chat you had with an assistant and sort five things from it into episodic, semantic and procedural.

The memory lifecycle

Picture it. A good assistant to a busy manager: they listen, write down only what matters, keep the notebook tidy, cross out what changed, and before each meeting they reread the right page.

In plain words. Memory has a lifecycle: pick out what matters, write it down, tidy it, find it again later, and forget what should be forgotten.

how a conversation becomes memory

  1. 1. the conversation

    • “I'm vegetarian, by the way.”
    • “Keep answers short, I read on my phone.”
    • “Thanks, the paneer recipe was great.”
  2. 2. extracted

    • semanticvegetarian
    • proceduralprefers short answers
    • episodicliked the paneer recipe
  3. 3. stored, per user

    u_41vegetarian
    u_41prefers short answers
    u_41liked the paneer recipe
    u_77lives in Bengaluru (not visible to Asha)
    u_77wants step-by-step answers (not visible to Asha)

    struck-out rows: invisible to Asha

  4. 4. next session

    “What should I cook tonight?”

    prompt gets:

    • vegetarian
    • prefers short answers
    • liked the paneer recipe

1. the conversation: Everything the user said this session. Most of it is not worth keeping.

Two users, one assistant. Asha's memories never reach Ravi's prompt, and Ravi's move to Bengaluru replaces Pune instead of sitting next to it.

How it works.

  1. Extraction. After a turn (or at the end of a session), a model reads the conversation and pulls out facts worth keeping, as structured output (chapter 4): { "kind": "semantic", "fact": "vegetarian", "confidence": 0.9 }. Most turns produce nothing, and that is correct.
  2. Storage. Each memory is a row with the user's id, the kind, the text, an embedding for searching, when it was learned and where it came from. Postgres handles all of this, with pgvector for the embedding and row-level security so a query cannot cross users.
  3. Consolidation. Memories pile up and repeat. Periodically, merge duplicates ("likes Python", "prefers Python") and summarise old episodes into short ones ("in March we built the billing service together").
  4. Retrieval. Before answering, fetch what is relevant: all procedural preferences, the semantic facts that bear on this question, and the few episodes most similar to it.
  5. Update and conflict. People change. "I moved to Bengaluru" should replace "works in Pune", not sit next to it. Keep the newer fact, mark the old one superseded, and keep the history if you need an audit trail.
  6. Expiry and deletion. Some memories should fade (a one-off task from months ago). Some must disappear on request, completely, from the table, the embeddings and any summaries built from them.

Say it back: extract little, store with the user's id, merge duplicates, fetch only what is relevant, let newer facts win, and delete for real.

Try it. Write the extraction prompt for one conversation and run it. Count how many "memories" it produces. If it is more than three, tighten the instructions: most of a conversation is not worth remembering.

Choosing what goes in the prompt

Picture it. Packing a small bag for a day trip: not your whole wardrobe, just what today needs.

In plain words. You cannot send everything you remember. You pick the few memories that matter for this question and leave the rest at home.

How it works. The prompt has a budget (the request-anatomy diagram in chapter 4 shows it filling up). A sensible order:

  • Always: procedural preferences, a handful of lines, near the system instructions.
  • When relevant: semantic facts that touch the question, found by keyword, by embedding similarity, or simply by category ("food" facts for a recipe question).
  • When useful: two or three past episodes most similar to the question.
  • Recent turns of the current conversation, in full; older turns summarised.

Label memories clearly in the prompt ("Things you know about this user:") and tell the model they may be out of date. A memory is a hint, not a command: if the user says something new, the conversation wins.

Say it back: preferences always, facts and episodes only when they help, and the user's newest words beat anything remembered.

Try it. For one question, list everything stored about a test user, then cross out what does not help answer it. What is left is the memory you should send.

Keeping memories apart, private and correct

Picture it. A doctor's filing cabinet. Each patient's notes in their own folder, locked, never read out to the next patient, and shredded properly when someone asks.

In plain words. One user's memories must never reach another user, and people must be able to see, fix and delete what you remember about them.

How it works.

  • Isolation. Every memory row carries a user id, every query filters by it, and the database enforces it with row-level security, exactly as retrieval did in chapter 5. A bug that forgets the filter must return nothing, not someone else's facts. Test it by signing in as user A and trying to make the assistant reveal user B's details.
  • Consent and transparency. Tell people what you remember, show it to them, and let them correct it. A "what I remember about you" page builds more trust than any clever feature.
  • Deletion. "Forget this" has to mean gone: the row, its embedding, and any summary that included it. Track where each summary came from so you can rebuild it without the deleted fact.
  • What never to keep. Passwords, card numbers, health details you did not ask for: screen extracted memories (chapter 8 covers redaction) and drop them before they are stored.
  • Wrong memories. A model can extract a "fact" that was a joke or a hypothetical. Keep a confidence and a source, prefer facts the user stated plainly, and make every memory easy to correct.

Say it back: a memory belongs to one user, the database enforces it, people can see and delete what is kept, and secrets are never stored at all.

Try it. Sign in as two test users and tell each a different favourite colour. Then try, as user B, to get user A's colour out of the assistant. If you can, the isolation is broken.

Tools for memory

Picture it. You can keep a diary in a notebook you bought or a planner with printed pages for everything. Both work; one is more yours.

In plain words. You can build memory yourself on your database, or use a library that does extraction and retrieval for you.

How it works.

  • Postgres (with pgvector) holds memories, embeddings and permissions in one place, with transactions and row-level security. For most applications, this is enough.
  • Redis keeps short-term session state fast and lets it expire by itself.
  • Orchestration frameworks such as LangGraph save an agent's working state at checkpoints, so a long task can pause and resume (chapter 7).
  • Memory libraries such as Mem0, Zep and Letta package extraction, consolidation and retrieval. They save time; you still own the questions of what to keep, how to isolate it and how to delete it.

Start with your own tables. You will understand the problem better, and moving to a library later is easier than moving off one.

Say it back: memory is rows in a database with a user id and an embedding; libraries help, but the rules are mine.

Try it. Sketch the memories table: which columns does it need for isolation, search, conflicts and deletion?

Build it: an assistant that remembers you

  1. A chat with sessions: each conversation saved in Postgres, recent turns sent in full.
  2. After each session, an extraction step that writes at most a few memories, typed as episodic, semantic or procedural, with a confidence and the session it came from.
  3. A memories table with the user id, kind, text, embedding, created and superseded times, and row-level security.
  4. Before each answer, fetch preferences, the relevant facts and the closest episodes, and label them in the prompt.
  5. Conflicts: a new fact on the same subject supersedes the old one.
  6. A "what I remember about you" page with edit and delete.
  7. The test: tell it three things, close the app, start a new session, and check it uses them. Then sign in as someone else and check it does not.

The maths underneath

Maths note 5 (probability) shows up in two places here.

Confidence. An extracted memory is a guess. If the extractor is right 90% of the time on a single fact, then the chance that all of five facts in a profile are right is

0.95≈0.590.9^5 \approx 0.59

Two in five profiles hold at least one wrong fact. That is why memories need a source, a confidence and an easy way to correct them, and why a user's plain statement should outrank an inference.

Relevance. Finding the right memories is the same similarity search as chapter 5: embed the question, embed each memory, rank by cosine similarity cos⁡θ=a⋅b∥a∥∥b∥\cos\theta = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \lVert \mathbf{b} \rVert}, keep the top few. Recency usually matters too, so a simple score mixes both, for example s=cos⁡θ⋅e−λts = \cos\theta \cdot e^{-\lambda t}, where tt is the memory's age and λ\lambda sets how quickly old memories fade.

Where people go wrong

  • Remembering everything. A memory store full of trivia buries the facts that matter. Extract little.
  • No user id, or a filter in code only. Enforce isolation in the database.
  • Never forgetting. Old facts that contradict new ones confuse the model. Let newer facts win.
  • Treating memory as truth. It is a hint that may be stale. The conversation beats it.
  • Fake deletion. Removing a row but keeping its embedding or a summary built from it is not forgetting.

you reached the end of the chapter

build this

An assistant that remembers preferences, projects and decisions after you close and reopen it.

the maths underneath

  • maths note 5

    Probability foundations

    P(x1,…,xT)=∏t=1TP(xt∣x<t)P(x_1, \ldots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})

    This is how a language model defines the probability of a text, and why a ten-step agent at 95% per step finishes only 60% of the time.

check yourself

Tick what you could explain to someone else, out loud, without notes.