rumblr Work in progressWIP

● The AI Primer · Lesson 46 · Part 6: building systems people rely on

Giving an AI agent a memory

memory and state

This lesson covers How an agent carries what it learned across conversations, and keeps one user's memory from another's

Members · open during launch 18 min6 figures and diagrams

What this is

What is memory, for an AI agent?

An AI language model remembers nothing between calls, so an AI assistant's memory is a system built around the language model that keeps what matters and puts it back into the prompt. When an assistant recalls that you prefer short answers, that system is at work. It holds the recent conversation, facts kept for months and the progress of a long task. It also decides who may see each memory and what gets deleted.

Why it matters: You need it when a product's second conversation should know about the first, or when one conversation outgrows the language model's context window. The tells are users repeating themselves every session, and a chat that gets slower, dearer and vaguer as it goes.

At a glance

Key takeaways

  1. A language model remembers nothing between calls; memory is what your code puts back into the prompt.
  2. Short-term memory keeps the recent turns word for word and folds older ones into a summary, inside a token budget.
  3. Long-term memory stores events (episodic), facts (semantic) and how-to steps (procedural), and recalls them by similarity.
  4. Write selectively, never store secrets, and supersede a changed fact instead of overwriting it, keeping each value's source.
  5. Partition storage by tenant and user, taken from authentication, never from the query.
  6. Keep a job's progress in a database: the model proposes updates, and code checks and writes them.

How it works, from scratch

Every call to a language model starts from a blank page plus the prompt you send, so your code rebuilds that prompt on each call from stores it keeps in between.

Figure 1 · Diagram

Reading it: the box titled "What the model sees on this call" is all the model ever sees, rebuilt on every call from the three stores. Every arrow into a store comes from your code, none from the model: the model proposes what to remember, and your code decides what is written.

Chapter 1

Short-term memory: the conversation, inside a budget

The first store is the conversation itself. Each call resends the history, so a long chat costs more and runs slower with every turn, and the model gets worse at using details buried in the middle, a decline called context rot. Short-term memory keeps the history inside a fixed token budget. The latest messages stay word for word, since they hold what the user means right now, such as the order number they just typed. Older ones are folded into a summary that gets only the room the recent messages leave.

Take six question-and-answer exchanges about invoices, 17 or 18 tokens per message (210 tokens in all), and a budget of 110 tokens. The last four messages stay word for word: 18 + 17 + 18 + 17 = 70 tokens, which leaves 110 - 70 = 40 tokens for the summary. The summary keeps the first sentence of each older message. All eight of those would take 65 tokens, so the oldest drop out, one at a time, until the rest fit in 40:

summary  : Earlier in this conversation: Question 3 is about invoices; Answer 3 lists the invoice;
           Question 4 is about invoices; Answer 4 lists the invoice              (36 tokens)
messages : Question 5 ..., Answer 5 ..., Question 6 ..., Answer 6 ...   (verbatim, 70 tokens)

The prompt carries 36 + 70 = 106 tokens of history, under the budget, and exchanges 1 and 2 are gone from it. The summary goes into the system prompt, not into a message of its own, so user and assistant turns still alternate as the API requires. A production system often has a language model write the summary instead: an extra call, but less is lost.

Figure 2 · Chart

0 5 10 15 20 25 30 35 40 turn 0 200 400 600 800 1000 1200 1400 tokens of history sent Short-term memory under a budget send the whole history recent turns + first-sentence summary budget before summarizing (300)

Sending the whole history climbs without end, while the managed history levels off just under its 300-token budget

Reading it: the x-axis is the turn number and the y-axis the tokens of history sent on that turn. The unmanaged line never stops climbing. The managed line first passes the 300-token budget at turn 9, drops as older turns fold into the summary, then climbs back and stays just under 300 from about turn 17: each new turn folds one more exchange in, and the oldest drops out of the summary to make room.

When a session has run too long even for that, reset it: write a short hand-off note and start a fresh conversation from it. Either way something is dropped, so a fact that must outlast the conversation needs a store of its own.

In code: ShortTermMemory.context returns the summary and the recent messages, and first_sentences is the default summarizer. View source

Chapter 2

Long-term memory: three kinds of record

That store is long-term memory, kept outside any one conversation and recalled into later ones. Its records come in three kinds: episodic, a dated event ("on 18 Sept Alice rejected Globex"); semantic, a fact stored under a key ("Alice's fiscal year starts in April", under fiscal_year_start); and procedural, a way of doing something ("to reconcile, match each invoice to its payment, then list mismatches"). Each kind answers its own sort of question:

kind stored as typical recall trigger
episodic dated event "what happened with...", "last time..."
semantic keyed fact (fiscal_year_start) any question the fact answers
procedural how-to steps "how do I...", before starting a known task

Each record is stored with its embedding. Recall embeds the question and returns the records closest to it by cosine similarity, optionally of some kinds only: procedures, say, before the agent starts a task it knows.

Figure 3 · Chart

what happened with Globex? how do I reconcile invoices? 0.0 0.2 0.4 0.6 0.8 cosine similarity Recall: which of Alice's memories each question finds memory kind semantic episodic procedural

Each question recalls the right kind: the Globex question scores the event highest, the how-to question the procedure

Reading it: each group of bars is one question. Each bar is one of Alice's memories, coloured by kind, and the tallest is the one recalled. The Globex question picks the event, the only memory that names Globex; the how-to question picks the procedure. This is RAG (retrieval-augmented generation) over the agent's own history.

In code: LongTermMemory.remember stores a MemoryRecord with its embedding, and LongTermMemory.recall returns the closest current records in a scope. View source

Chapter 3

The hard parts: what to write, conflicts, isolation, deletion

A store that lasts for months needs rules that a conversation never did.

What to write. Everything stored is read back into future prompts and shown in exports, so a good store holds what the user would be annoyed to repeat: "prefers morning meetings", not "said thanks at 3:02pm", and never a bank PIN. The write policy skips small talk and refuses anything that looks like a secret.

Conflicts. Alice said her fiscal year starts in April, then corrected it to July. Both values are stored under the key fiscal_year_start. The April record is marked as superseded by the July one, so recall returns only July, while the key's history keeps both with their sources. That history explains why the agent once said April.

Isolation. A multi-tenant system serves many customers (tenants) whose memories must never mix. Think of one locked filing cabinet per company, not a shared cabinet with a sign asking people to read only their own folder. Every memory call names a scope (a tenant and a user) taken from your authentication layer, never from the query. Storage is partitioned by scope, so a lookup opens the caller's own cabinet and has no way into another.

Figure 4 · Diagram

Reading it: Carol's request opens her own partition and searches only there. The dotted line from Acme's partition ends in a cross: no path leads from her search to Acme's records, whatever the query says.

Figure 5 · Chart

−0.2 0.0 0.2 0.4 0.6 0.8 1.0 similarity to Carol's query acme/alice: Alice's fiscal year starts in April.... acme/alice: On 2026-09-18 Alice rejected the vendo... acme/alice: To reconcile invoices, match each vend... acme/alice: Acme plans to acquire Initech in Q4.... globex/carol: Globex prefers invoices in euros.... Carol (globex) quotes Acme's secret: only her partition is searched

Acme's secret scores a perfect match to Carol's quoted query, yet it sits outside her partition and is never searched

Reading it: Carol, at Globex, asks a question that quotes Acme's confidential memory word for word. Each bar is that question's similarity to one memory in the whole system. Acme's record scores highest, so a store that searched everything and filtered the results afterwards would be one bug away from leaking it. The hatched bars lie outside Carol's partition, and the real search never scores them.

Deletion. Users may need to see, correct or delete what is remembered, and privacy law such as the GDPR (the EU's General Data Protection Regulation) can require it. An export of a user's scope shows everything, superseded facts included, and deleting a user erases their records without touching their colleagues'.

In code: LongTermMemory.remember applies the write policy and supersedes an older record with the same key; LongTermMemory.export and LongTermMemory.delete_user show and erase one user's records. View source

Chapter 4

Task state outside the model

The stores so far hold what the agent knows. A job of several steps also has a state: which steps are done and which comes next. Kept in the conversation, that state is lost when the process crashes, and a summary can trim or garble it.

Picture a checklist on a clipboard. The assistant may suggest ticking a box, but only the supervisor holds the pen, and if the assistant goes home sick, the next person starts at the first unticked box. Here the clipboard is a database, the supervisor is your code and the assistant is the model. The model proposes an update; your code checks it against the stored state and writes it in a transaction, which completes entirely or not at all. A job with three steps runs like this:

steps                  : fetch_invoices, fetch_payments, match
model proposes         : {"step": "fetch_invoices", "status": "done", "output": "4 invoices"}   -> written
model proposes         : {"step": "match", "status": "done"}  -> refused: the current step is fetch_payments
process crashes after fetch_payments is done
new process, same file : next_step() -> "match"

Figure 6 · Diagram

Reading it: time runs downward. No arrow joins the model to SQLite: each proposal stops at your code, which reads the current step before it writes. After the restart, the answer to "where do we resume?" comes from the database, not from a conversation that no longer exists.

Because the state sits in a database, people and monitoring can query a run while it is going, and code enforces rules, such as no skipped steps, that a prompt could only ask for.

In code: TaskStateStore.apply validates a proposal before writing it, raising InvalidUpdate for a bad status or a skipped step, and TaskStateStore.next_step finds the first unfinished step. View source

Test yourself

4 questions

Answer each one out loud or on paper before you open it.

Question 1Q: How would you design long-term memory for a multi-tenant agent platform?Think it through, then reveal

A: Every read and write takes a scope (tenant, user) from the authenticated session, and storage is partitioned by it: separate namespaces, collections or row-level security, never a global index filtered after the search. Store typed records (episodic, semantic with keys, procedural) with embeddings, source and time. Apply a write policy (durable, non-secret), supersede conflicting facts instead of overwriting, retrieve the top few by similarity within scope, and support export and deletion per user. Test isolation with adversarial queries.

Question 2Q: A long support chat gets worse and more expensive over time. Why, and what helps?Think it through, then reveal

A: Every call re-sends the whole history, so cost rises, and models use details in the middle of long contexts less reliably. Keep a budget: recent turns verbatim, older ones summarized, important facts promoted to long-term memory, or reset with a written hand-off.

Question 3Q: The user corrects a fact the agent remembered. What should happen?Think it through, then reveal

A: Store the new value under the same key, mark the old one as superseded by the new (don't delete it silently), and recall only current records. Keep the source of each so the change is explainable.

Question 4Q: Why keep task state in a database when the model can "remember" progress in the conversation?Think it through, then reveal

A: The conversation is lost on a crash, and it can be summarized, trimmed or misread. A database is authoritative, survives restarts, can be queried by people and monitoring, and lets code enforce rules (no skipping steps) that a prompt can only request.

Primary sources

The papers behind this lesson

Park et al., Generative Agents: Interactive Simulacra of Human Behavior (2023).

It introduced a memory stream of observations retrieved by relevance, recency and importance, plus periodic reflection into higher-level memories, a template for long-term agent memory.

The paper
Packer et al., MemGPT: Towards LLMs as Operating Systems (2023).

It treats the context window like RAM and external storage like disk, with the agent paging information in and out, which is the short-term/long-term split made explicit.

The paper

Researcher's shelf

Further reading

  • Lilian Weng, LLM Powered Autonomous Agents (memory section): https://lilianweng.github.io/posts/2023-06-23-agent/
  • LangGraph docs (short- and long-term memory, persistence): https://langchain-ai.github.io/langgraph/
  • SQLite, transactions: https://www.sqlite.org/lang_transaction.html
  • GDPR, right to erasure (Art. 17): https://gdpr-info.eu/art-17-gdpr/

About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.