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
- A language model remembers nothing between calls; memory is what your code puts back into the prompt.
- Short-term memory keeps the recent turns word for word and folds older ones into a summary, inside a token budget.
- Long-term memory stores events (episodic), facts (semantic) and how-to steps (procedural), and recalls them by similarity.
- Write selectively, never store secrets, and supersede a changed fact instead of overwriting it, keeping each value's source.
- Partition storage by tenant and user, taken from authentication, never from the query.
- 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
flowchart LR
subgraph Prompt["What the model sees on this call"]
direction LR
S[System prompt<br/>+ summary of older turns]
R[Recalled long-term memories]
M[Recent messages, word for word]
end
STM[(Short-term memory<br/>this conversation)] --> S
STM --> M
LTM[(Long-term memory<br/>per tenant, per user)] -->|similarity search| R
DB[(Task state<br/>SQLite)] -->|current step| S
Model[Model] -->|proposes updates| Code[Your code]
Code -->|validated writes| LTM
Code -->|validated writes| DB
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
Sending the whole history climbs without end, while the managed history levels off just under its 300-token budget
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
Each question recalls the right kind: the Globex question scores the event highest, the how-to question the procedure
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
flowchart TD Q[recall scope=globex/carol, query=...] --> P[Open partition<br/>tenant=globex, user=carol] P --> S[Similarity search<br/>inside this partition only] S --> R[Results] A[(acme/alice partition)] -.-x S
Figure 5 · Chart
Acme's secret scores a perfect match to Carol's quoted query, yet it sits outside her partition and is never searched
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
sequenceDiagram
participant M as Model
participant C as Your code
participant D as SQLite
M->>C: propose {"step": "fetch_invoices", "status": "done"}
C->>D: read current step
D-->>C: fetch_invoices
C->>D: write status=done (transaction)
M->>C: propose {"step": "match", "status": "done"}
C-->>M: refused: current step is fetch_payments
Note over C,D: crash, restart
C->>D: next_step?
D-->>C: match
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
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 paperIt 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 paperResearcher'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.