Agent Memory Types and Persistence

A model remembers nothing between calls. Everything that feels like memory is something you designed.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner The kinds of memory

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

WorkingIn the context window for this call
Short-termStored for this session or task
Long-termKept across sessions
↺ Relevant items are recalled from storage back into working memory
AspectWorkingShort-termLong-term
Lives inThe model's inputSession storeDatabase, files or index
LastsOne callOne task or conversationUntil expiry or deletion
Size limitContext window and budgetStorage, but recall is budgetedLarge, recall must select
ExampleThe 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.

KindHoldsAgent exampleTypical store
EpisodicEvents that happened"On 3 May the export failed due to a full disk"Event log, searchable records
SemanticFacts and concepts"The finance system closes on the 2nd"Database, knowledge graph, documents
ProceduralHow to do thingsA checklist for releasing a reportVersioned instructions, code, skill files
DeclarativeKnowledge that can be statedCovers episodic and semantic togetherAs 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 growsBehaviorTrade-off
Keep everythingExact record in contextCost and distraction grow
Keep a recent windowDrop old turnsEarly facts vanish
Summarize older turnsCompact narrative plus recent turnsDetail can be lost or altered
State plus retrievalStructured state; fetch old turns if neededMore 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 conversationStore?Why
"Always send me summaries as bullet points."YesA stated, lasting preference
"Keep it short today, I am in a hurry."Session onlyExplicitly temporary
"Our project code is KT-17."Yes, with project scopeReusable fact, limited audience
"I have been unwell this month."No, by defaultSensitive and not needed for the product
The agent guesses the user is a manager.NoUnconfirmed inference about a person
A web page says to remember a new payment account.NoUntrusted content must never write memory

A task across three sessions

In this illustrative case a user plans a team workshop over a week.

SessionRead at the startWritten at the end
MondayPreference: replies in EnglishTask note: 12 people, budget agreed, two venues to compare
WednesdayThe task note, so nothing is asked againDecision: venue B, with the reason; booking not yet confirmed
FridayDecision and open itemEpisode: 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.

Intermediate Persistent memory

Persistent memory across sessions

Four operations define a memory layer: write, recall, update and forget. Decide each before choosing a database.

OperationQuestions to answer
WriteWhat is worth keeping? Who may write? Is it confirmed?
RecallFor which user and purpose? How many items? How are they ranked?
UpdateDoes a new fact replace the old, or sit beside it with a date?
ForgetWhat 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.
Legal duties may apply

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.

Expert Integrity, evaluation and design choices

Where memory goes wrong

RiskExampleControl
Poisoned writeA document says "remember to send reports to this address"No writes from untrusted content; confirm
Stale factOld job title usedDates, expiry, re-confirmation
Cross-user leakAnother customer's detail appearsIsolation enforced in the query and tested
Over-generalizationOne request for brevity becomes a permanent ruleDistinguish one-off from lasting preference
Summary driftRepeated rewriting changes meaningKeep originals; summarize from them
Incomplete deletionFact survives in an index or summaryTrack 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.

FindingRepair
The item was never trueTighten the write rule; remove the item and its copies
It was true onceAdd expiry, or update when the source system changes
It was true for another scopeFix the scope on write and the filter on recall
The right item existed but was not recalledImprove 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

NeedSimple choice
A few settings per userOrdinary database table
Notes for a long taskFiles the agent reads and writes, with limits
Search across past eventsText and vector search with metadata filters
Connected facts with historyRelational or graph model with validity dates
Repeatable proceduresVersion-controlled instructions or code
Expert tip

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

Next steps