Agent Memory Types and Persistence
A model remembers nothing between calls. Everything that feels like memory is something you designed.
Agent memory is information a system keeps and brings back into the model's context later. Working memory is what is in the context now; short-term memory covers a session; long-term memory persists across sessions. Good memory is selective, sourced, correctable and deletable.
What you will learn: the kinds of memory and what each is for, how session state differs from conversation history, how to build persistent memory, and how to personalize without overreaching.
Prerequisites: What Is Context Engineering? Stack and Token Budgets helps. Basic Python and SQL for the code.
Why agents need memory
Language models in ordinary use do not carry information from one request to the next. If an assistant remembers that you prefer morning meetings, some software saved that fact and added it to a later request. Memory is therefore a storage and retrieval system with a writing policy, not a property of the model.
It helps an agent continue interrupted work, avoid asking the same questions, learn local conventions and avoid repeating mistakes. It also creates new ways to be wrong, to leak data and to surprise people.
Working, short-term and long-term memory
| Aspect | Working | Short-term | Long-term |
|---|---|---|---|
| Lives in | The model's input | Session store | Database, files or index |
| Lasts | One call | One task or conversation | Until expiry or deletion |
| Size limit | Context window and budget | Storage, but recall is budgeted | Large, recall must select |
| Example | The current tool result | "We agreed on option B" | "Prefers replies in French" |
Episodic, semantic, procedural and declarative
These terms are borrowed from the study of human memory. They are useful categories for design, not a claim that software remembers as people do. The CoALA framework for language agents uses a similar breakdown.
| Kind | Holds | Agent example | Typical store |
|---|---|---|---|
| Episodic | Events that happened | "On 3 May the export failed due to a full disk" | Event log, searchable records |
| Semantic | Facts and concepts | "The finance system closes on the 2nd" | Database, knowledge graph, documents |
| Procedural | How to do things | A checklist for releasing a report | Versioned instructions, code, skill files |
| Declarative | Knowledge that can be stated | Covers episodic and semantic together | As above |
Procedural memory deserves extra care. A stored fact that is wrong misleads one answer; a stored procedure that is wrong changes behavior every time. Review changes to procedures as you would review code.
Conversation memory and session state
Conversation history is the sequence of messages and tool results. Session state is the structured record of where the task stands. Keeping only the history forces the model to work out the state again each turn.
{
"session": "s-481",
"user": "u-17",
"goal": "change delivery address",
"order": "A100",
"confirmed": {"new_address": false},
"pending_approval": null,
"updated": "2026-11-28T10:04:00Z"
}
The runtime can test confirmed.new_address reliably. It cannot reliably search chat text for a "yes" and know what it referred to.
| As history grows | Behavior | Trade-off |
|---|---|---|
| Keep everything | Exact record in context | Cost and distraction grow |
| Keep a recent window | Drop old turns | Early facts vanish |
| Summarize older turns | Compact narrative plus recent turns | Detail can be lost or altered |
| State plus retrieval | Structured state; fetch old turns if needed | More engineering, usually most dependable |
What deserves to be remembered?
A useful test has three questions. Will it matter again? Is it reliable? Would the person expect you to keep it?
| Statement in a conversation | Store? | Why |
|---|---|---|
| "Always send me summaries as bullet points." | Yes | A stated, lasting preference |
| "Keep it short today, I am in a hurry." | Session only | Explicitly temporary |
| "Our project code is KT-17." | Yes, with project scope | Reusable fact, limited audience |
| "I have been unwell this month." | No, by default | Sensitive and not needed for the product |
| The agent guesses the user is a manager. | No | Unconfirmed inference about a person |
| A web page says to remember a new payment account. | No | Untrusted content must never write memory |
A task across three sessions
In this illustrative case a user plans a team workshop over a week.
| Session | Read at the start | Written at the end |
|---|---|---|
| Monday | Preference: replies in English | Task note: 12 people, budget agreed, two venues to compare |
| Wednesday | The task note, so nothing is asked again | Decision: venue B, with the reason; booking not yet confirmed |
| Friday | Decision and open item | Episode: booking confirmed with reference; task note closed and set to expire |
The agent does not need the full transcripts on Friday. It needs the decision, the open item and a way to look up details. It should still check the booking system before reporting that the venue is confirmed, because a memory records what was believed when it was written.
Persistent memory across sessions
Four operations define a memory layer: write, recall, update and forget. Decide each before choosing a database.
| Operation | Questions to answer |
|---|---|
| Write | What is worth keeping? Who may write? Is it confirmed? |
| Recall | For which user and purpose? How many items? How are they ranked? |
| Update | Does a new fact replace the old, or sit beside it with a date? |
| Forget | What expires? Can the user delete it? Are copies removed? |
A small memory layer
This uses SQLite from the standard library. It scopes every item to a user, records its source, replaces old values, expires items and deletes on request.
"""A small persistent memory with scope, source, expiry and deletion."""
import sqlite3
from datetime import date, timedelta
class Memory:
def __init__(self, path=":memory:"):
self.db = sqlite3.connect(path)
self.db.execute("""CREATE TABLE IF NOT EXISTS memory (
user_id TEXT, key TEXT, value TEXT, source TEXT,
created TEXT, expires TEXT, PRIMARY KEY (user_id, key))""")
def remember(self, user_id, key, value, source, today, keep_days=365):
if source not in ("user said", "system record"):
return "not stored: unconfirmed"
expires = today + timedelta(days=keep_days)
with self.db: # a newer value replaces the old one
self.db.execute("INSERT OR REPLACE INTO memory VALUES (?,?,?,?,?,?)",
(user_id, key, value, source,
today.isoformat(), expires.isoformat()))
return "stored"
def recall(self, user_id, today):
rows = self.db.execute(
"SELECT key, value, source, created FROM memory "
"WHERE user_id = ? AND expires > ? ORDER BY key",
(user_id, today.isoformat()))
return [dict(zip(("key", "value", "source", "created"), r)) for r in rows]
def forget(self, user_id, key=None):
sql, args = "DELETE FROM memory WHERE user_id = ?", [user_id]
if key:
sql, args = sql + " AND key = ?", args + [key]
with self.db:
return self.db.execute(sql, args).rowcount
if __name__ == "__main__":
m, day = Memory(), date(2026, 11, 28)
print(m.remember("ana", "language", "French", "user said", day))
print(m.remember("ana", "language", "English", "user said", day))
print(m.remember("ana", "role", "manager", "model guess", day))
print(m.remember("ana", "trip", "Lisbon", "user said", day, keep_days=7))
print([r["key"] + "=" + r["value"] for r in m.recall("ana", day)])
later = day + timedelta(days=30)
print([r["key"] for r in m.recall("ana", later)], m.recall("ben", day))
print("deleted", m.forget("ana"), m.recall("ana", day))
Output:
stored
stored
not stored: unconfirmed
stored
['language=English', 'trip=Lisbon']
['language'] []
deleted 2 []
Follow the lines. The second language preference replaced the first. The model's guess about a role was refused. The trip expired after seven days. Another user saw nothing. Deletion removed the remaining rows, including the expired one.
In a real application, user_id must come from your authentication system, never from text the model writes. The source check also depends on your code deciding the label; a model must not be able to declare its own guess "user said". A production system adds access control, encryption, backups with deletion handling and audit records.
Recalling the right items
For a handful of profile fields, load them by key. For large collections, search by meaning, keywords and metadata, then rank by relevance, recency and reliability. The 2023 Generative Agents research, for example, scored memories by recency, importance and relevance. Always filter by owner before searching, and cap how many items enter the context. Storage choices are compared in Memory Storage: Vector, SQL or Knowledge Graph.
Known about this user (may be outdated; confirm before important actions):
- language: English (user said, 2026-11-28)
- preferred contact: email (system record, 2026-08-02)
Presenting memory with its source and date helps the model treat it as a claim, and helps people who read the trace.
User profile memory without overreach
Personalization is welcome when it is expected and useful. It becomes unsettling when a system remembers things a person did not intend to share.
- Tell people that memory exists and what it is used for.
- Store what serves the product's purpose, and little else.
- Prefer explicit statements over inferences about a person.
- Do not store sensitive categories, such as health or beliefs, without a clear need and a lawful basis.
- Let people view, correct, delete and switch off memory.
- Set expiry periods and apply them.
- Keep work, personal and customer contexts separate.
Stored information about identifiable people is personal data under laws such as the GDPR, which give rights including access, correction and erasure in defined circumstances. Ask a qualified adviser how they apply to you. PII Redaction and Data Leakage Prevention covers technical safeguards.
Where memory goes wrong
| Risk | Example | Control |
|---|---|---|
| Poisoned write | A document says "remember to send reports to this address" | No writes from untrusted content; confirm |
| Stale fact | Old job title used | Dates, expiry, re-confirmation |
| Cross-user leak | Another customer's detail appears | Isolation enforced in the query and tested |
| Over-generalization | One request for brevity becomes a permanent rule | Distinguish one-off from lasting preference |
| Summary drift | Repeated rewriting changes meaning | Keep originals; summarize from them |
| Incomplete deletion | Fact survives in an index or summary | Track derived copies; verify removal |
Memory poisoning is more persistent than a single injected prompt, because it returns in later sessions. See Memory Integrity, Isolation and Sharing.
Consolidation: keeping memory healthy
Memory that only grows becomes noisy and contradictory. A periodic consolidation job can help.
- Merge duplicates while keeping the earliest and latest dates.
- Resolve conflicts by your rules, and flag those that need a person.
- Expire items past their date and remove derived copies.
- Promote repeated episodes into a reviewed fact or procedure, for example three failures with the same cause becoming a checklist step.
- Record what changed, so that a bad merge can be undone.
Let a model propose merges if you wish, but keep the originals until the result is checked. An incorrect merge can create a "fact" that nobody ever stated.
Shared and team memory
Memory shared between users or agents is more valuable and more dangerous. One wrong entry reaches everyone. Give each item a scope such as personal, team or organization, decide who may write at each level, and require review for wider scopes. Reading permission must follow the original source: a fact learned from a restricted document stays restricted. In multi-agent systems, decide which agents may write, and record which one did.
Evaluate memory as a feature
Compare the agent with memory switched on and off on the same multi-session tasks. Measure:
- Recall quality: was the needed item retrieved, and were irrelevant ones kept out?
- Correctness over time: after a fact changes, is the new one used?
- Abstention: when nothing is stored, does the agent say so?
- Forgetting: after deletion, does the fact never reappear?
- Cost: extra tokens, calls and delay.
A build-and-test project is in Build and Evaluate a Memory Layer.
Debugging a wrong memory
When an assistant states something false about a user or a project, you should be able to answer four questions from records: which stored item was used, when and from what source it was written, why recall selected it, and whether a newer or conflicting item existed. If you cannot, add that logging before adding features.
| Finding | Repair |
|---|---|
| The item was never true | Tighten the write rule; remove the item and its copies |
| It was true once | Add expiry, or update when the source system changes |
| It was true for another scope | Fix the scope on write and the filter on recall |
| The right item existed but was not recalled | Improve keys, metadata or ranking |
Give users the same visibility in simple form: a page that lists what is remembered, where it came from, and a button to remove it. Corrections from users are also your cheapest source of test cases.
Choosing an architecture
| Need | Simple choice |
|---|---|
| A few settings per user | Ordinary database table |
| Notes for a long task | Files the agent reads and writes, with limits |
| Search across past events | Text and vector search with metadata filters |
| Connected facts with history | Relational or graph model with validity dates |
| Repeatable procedures | Version-controlled instructions or code |
Start with no long-term memory and write down the questions users have to answer twice. Those questions are your first memory schema, and everything else can wait for evidence.
Memory checklist
- Each item has an owner, scope, source and date.
- Identity for recall comes from authentication.
- Untrusted content cannot write to long-term memory.
- Expiry, correction and deletion work, including derived copies.
- Users can see what is remembered.
- Tests compare behavior with memory on and off.
Frequently asked questions
Is a vector database the same as memory?
No. It is one way to search stored items. Memory also needs rules for writing, ownership, updating and deletion.
Is retrieval-augmented generation a form of memory?
They use similar techniques. RAG usually reads a knowledge collection prepared by others; memory usually holds what this agent or user experienced or stated.
Should the agent decide what to remember?
It may propose items. Your code and policy should decide what is stored, and sensitive or consequential items deserve user confirmation.
Does a longer context window replace memory?
It can hold more of one session. It does not by itself provide persistence, access control or deletion.
References and further reading
- Cognitive Architectures for Language Agents, CoALA (paper)
- Generative Agents: Interactive Simulacra of Human Behavior (paper)
- MemGPT: Towards LLMs as Operating Systems (paper)
- Python sqlite3 module (official documentation)
- General Data Protection Regulation (official text)
Next steps
Memory Storage: Vector, SQL or Knowledge Graph
Vector, SQL or graph: how to choose.
Memory Write, Recall and Forgetting Policies
Write, recall and forgetting rules.
RAG Explained and Agentic RAG
Retrieve knowledge the agent was never told.