Applied AI SystemsVol. 14B · Part XIV
0 / 0

Shelves / Applied AI Systems

AS·170

Agent Memory

What an AI system remembers, where, and for how long: six distinct stores (context window, working memory, session state, long-term memory, external knowledge, application database) and what belongs in each, context engineering and compaction of long conversations with a token-budgeted summariser, scratchpads and note files, durable session state, long-term memory types (semantic facts, episodic events, procedural instructions), deciding what to write, extraction and consolidation, retrieval by relevance, recency and importance, conflicts and updates, forgetting and deletion, privacy, consent and multi-tenant isolation, memory as an attack surface, evaluation, and a working memory store in Python with SQLite.

20 topics · ~16 min read · 27-question quiz
Updated Suggest a correction

Start here: what an agent "remembers"

A model remembers nothing between calls. Everything it knows about this conversation, this user or this task must be put into the context window on every call. "Memory" in AI systems means deciding what to put there, because the window is limited and costs money per token.

Three ways to fill a limited window

Imagine a 300-turn chat in which a user mentions their city, job, diet and pet early on, and later says "I moved, so now I live in Pune."

Strategy What it puts in the context What goes wrong
keep the last turns the most recent messages early facts fall off the end
search the history the past messages most similar to the question finds old and new versions of a fact, or misses facts phrased differently
a fact store short extracted facts ("city: Pune"), updated when they change extraction can be wrong; needs rules for updating and forgetting

The lab measured exactly this on synthetic conversations: keeping the last turns never had the early facts; searching the history found them only 33% of the time when the question was phrased differently from the original message, and for every fact that had changed, it brought back the outdated version alongside the current one; a store of extracted facts, updated so the latest value wins, had every fact and no stale values (with the caveat that the lab's extraction was perfect by construction).

Memory is also a privacy decision

Anything stored can be shown later, possibly to the wrong person. Store only what's useful, let users see and delete it, keep each user's memory separate, and never let one user's memory enter another's context.

How deep to go in agent memory

Volume 17 defines six mastery levels; for agent memory they look like this:

Level You can…
L1 explain statelessness, context windows and kinds of memory
L2 add conversation history, summaries and a simple user-fact store to an app
L3 explain context engineering, retrieval memory, consolidation and forgetting policies
L4 debug stale, missing, conflicting or leaked memories from traces
L5 design memory with privacy controls, evaluation and cost budgets
L6 run memory systems for many users with isolation, audits and deletion guarantees

Six kinds of "memory"

LLMs are stateless (chapter 156): everything a model "remembers" during a request is in its context window, put there by your application. "Agent memory" is therefore an application design question: what to store, where, and when to bring it back. The roadmap distinguishes six stores:

Store What it holds Lifetime Who writes it Example
Context window Tokens the model sees right now One model call The application assembles it System prompt + tools + retrieved docs + recent turns
Working memory The task's in-progress scratch state: plan, to-do list, notes, intermediate results One task / run The agent (via tools) and the orchestrator "Checked metrics ✓, deploys ✓, next: logs"
Session state A conversation or workflow's durable state: messages, variables, checkpoints One session (minutes to days) The application The chat transcript; a LangGraph checkpoint
Long-term memory Facts, preferences and experiences about a user or domain that persist across sessions Months to years, until deleted Memory extraction (with consent) "Prefers answers in Telugu"; "Their team deploys on Thursdays"
External knowledge Documents and data the agent can search but doesn't "own" Managed separately Content owners, ingestion pipelines RAG index over the handbook (chapter 161)
Application database Authoritative business records System of record Business logic Orders, accounts, permissions
context window(the model sees only this) working memoryplan · notes · todo session statetranscript · checkpoint long-term memoryfacts · prefs · episodes external knowledgeRAG index · search application databaseorders · accounts (tools) assemble · retrieve → context writewrite
Where an agent's information lives. Only the context window is visible to the model; everything else must be retrieved into it. Working memory and session state belong to the current task and conversation, long-term memory spans sessions for a user, and external knowledge and the application database are authoritative sources that the agent reads through tools, not stores it owns.

Two rules follow:

  1. The application database and authoritative sources stay authoritative. Don't "remember" an order status or account balance in long-term memory; look it up through a tool every time. Memory holds what isn't recorded elsewhere (preferences, context, lessons).
  2. Everything must earn its place in the context window. More context isn't free: cost, latency and distraction grow with it (chapter 156).

Context engineering

Each model call's context is assembled from parts: instructions, tool definitions, relevant memories, retrieved knowledge, conversation history, the current input. Doing this well ("context engineering") is often the main determinant of agent quality.

  • Order stable content first (cacheable: chapter 166) and the current task last.
  • Select: include only tools, memories and documents relevant to this step.
  • Compress: summarise old turns and bulky tool outputs.
  • Isolate: give sub-agents their own focused contexts and get back summaries (chapter 169).
  • Externalise: write large artefacts and notes to files/state and reference them.

Compaction

Long conversations and agent runs outgrow the window. Compaction replaces older turns with a summary while keeping recent turns verbatim:

Python
def count_tokens(text): return max(1, len(text) // 4)             # rough; use the model's tokenizer in practice

def compact(messages, summarize, budget_tokens=3000, keep_recent=6):
    """Keep the system message and the last `keep_recent` messages verbatim; fold older ones into a summary."""
    system, rest = messages[0], messages[1:]
    total = sum(count_tokens(m["content"]) for m in messages)
    if total <= budget_tokens or len(rest) <= keep_recent:
        return messages
    old, recent = rest[:-keep_recent], rest[-keep_recent:]
    summary = summarize(old)                                         # an LLM call in practice
    return [system, {"role": "user", "content": f"<summary of earlier conversation>\n{summary}\n</summary>"}] + recent

def naive_summarize(msgs):
    """Stand-in summariser: keep decisions, facts and open questions (an LLM does this far better)."""
    keep = [m["content"] for m in msgs if any(k in m["content"].lower() for k in ("decided", "prefer", "deadline", "todo", "must"))]
    return "\n".join(f"- {k[:160]}" for k in keep) or "- (no durable facts)"

history = [{"role": "system", "content": "You are a project assistant."}]
for i in range(30):
    history.append({"role": "user", "content": f"Turn {i}: " + ("We decided to ship v2 on Friday. " if i == 3 else "") +
                    ("I prefer short status updates. " if i == 7 else "") + "lorem ipsum " * 60})
    history.append({"role": "assistant", "content": f"Ack {i}. " + "details " * 40})
compacted = compact(history, naive_summarize)
len(history), len(compacted), compacted[1]["content"][:160]   # 61 → 8 messages; summary keeps "decided to ship v2 on Friday" and the preference

A good compaction summary preserves: the goal and constraints, decisions made and why, facts learned, the current plan and status, open questions, and references (ids, file names) to anything dropped. Some providers offer server-side context management (automatic compaction, clearing old tool results), and agent frameworks have built-in summarising memory.

Working memory

For multi-step tasks, give the agent explicit places to write:

  • A plan / to-do list it updates (and the user can see).
  • A notes or scratchpad file for findings, partial results and hypotheses.
  • Structured task state in the orchestrator (variables, collected entities, counters).

Writing notes outside the context keeps key information safe from compaction and lets a fresh context (or a different agent) resume the task. Coding agents use files in the repository (task lists, progress notes, project instruction files) the same way.

Session state

Session state is ordinary application data: persist it like any other.

  • Transcript storage with ids, timestamps, model/prompt versions, tool calls and results (for resumption, audit and evaluation).
  • Checkpoints of agent state at each step (chapter 171) so runs survive crashes, deploys and human pauses.
  • Expiry and retention policies; per-tenant isolation; encryption at rest.
  • Cheap resumption: rebuild the context from the stored transcript plus compaction.

Long-term memory

Types

Borrowing from cognitive science:

Type Content Example
Semantic Facts and preferences "Works in Hyderabad (IST)"; "Uses pnpm, not npm"
Episodic Past events and interactions "On 12 Oct we debugged a Kafka consumer lag issue; root cause was a rebalance storm"
Procedural How to do things; learned instructions "When writing release notes for this team, group by service and link tickets"

Writing: what deserves to be remembered

Memory quality depends far more on what you write than how you retrieve it. A write policy:

  • Durable: still true and useful weeks later (not "user is tired today").
  • Stated or confirmed: what the user said or approved, not the model's inferences about them.
  • Not already authoritative elsewhere (don't copy database records).
  • Allowed: sensitive categories (health, finances, identifiers) follow explicit consent and policy; some things should never be stored.
  • Specific and attributed: who said it, when, source conversation, confidence.
  • Deduplicated and updated rather than appended: "moved to Bengaluru (previously Hyderabad)" replaces the old fact.

Extraction is usually an LLM step run after a conversation turn (or in the background) with a schema: {subject, fact, type, source, timestamp}; then a consolidation step merges it with existing memories (add, update, delete, or ignore).

Retrieval

Bring back memories relevant to the current request, ranked by a mix of:

  • Relevance: embedding similarity to the current query (chapter 159), or keyword match.
  • Recency: exponential decay with age.
  • Importance: assigned at write time (explicit preferences > incidental details).
  • Scope: same user, same project, same tenant only.
Python
import sqlite3, math, time, re, hashlib
import numpy as np

def embed(text, dim=256):                                   # toy hashing embedding (chapter 159); use a real model
    v = np.zeros(dim)
    for w in re.findall(r"\w+", text.lower()):
        h = int(hashlib.md5(w.encode()).hexdigest(), 16); v[h % dim] += 1 if (h >> 64) & 1 else -1
    return v / (np.linalg.norm(v) or 1)

class MemoryStore:
    def __init__(self, path=":memory:"):
        self.db = sqlite3.connect(path)
        self.db.execute("""CREATE TABLE IF NOT EXISTS memory (
            id INTEGER PRIMARY KEY, user_id TEXT NOT NULL, subject TEXT NOT NULL, fact TEXT NOT NULL,
            kind TEXT CHECK (kind IN ('semantic','episodic','procedural')), importance REAL,
            created REAL, updated REAL, source TEXT, embedding BLOB,
            UNIQUE (user_id, subject))""")                         # one current fact per subject per user

    def write(self, user_id, subject, fact, kind="semantic", importance=0.5, source=None, now=None):
        now = now or time.time(); e = embed(f"{subject}: {fact}").astype(np.float32).tobytes()
        self.db.execute("""INSERT INTO memory (user_id, subject, fact, kind, importance, created, updated, source, embedding)
                           VALUES (?,?,?,?,?,?,?,?,?)
                           ON CONFLICT (user_id, subject) DO UPDATE SET
                             fact = excluded.fact || ' (previously: ' || memory.fact || ')',
                             importance = MAX(memory.importance, excluded.importance),
                             updated = excluded.updated, source = excluded.source, embedding = excluded.embedding""",
                        (user_id, subject, fact, kind, importance, now, now, source, e))

    def forget(self, user_id, subject):
        self.db.execute("DELETE FROM memory WHERE user_id = ? AND subject = ?", (user_id, subject))

    def recall(self, user_id, query, k=3, half_life_days=90, now=None):
        now = now or time.time(); q = embed(query)
        rows = self.db.execute("SELECT subject, fact, importance, updated, embedding FROM memory WHERE user_id = ?",
                               (user_id,)).fetchall()                  # scoped to this user only
        scored = []
        for subject, fact, imp, updated, blob in rows:
            rel = float(np.frombuffer(blob, dtype=np.float32) @ q)
            recency = 0.5 ** ((now - updated) / 86400 / half_life_days)
            scored.append((0.6 * rel + 0.25 * imp + 0.15 * recency, subject, fact))
        return sorted(scored, reverse=True)[:k]

mem = MemoryStore()
day = 86400; t0 = time.time() - 200 * day
mem.write("u1", "city", "Lives in Hyderabad", importance=0.6, now=t0)
mem.write("u1", "package manager", "Uses pnpm for JavaScript projects", kind="procedural", importance=0.8, now=t0 + 10 * day)
mem.write("u1", "release day", "Team ships releases on Thursdays", importance=0.7, now=t0 + 150 * day)
mem.write("u2", "city", "Lives in Pune", now=t0)                         # another user: must never leak
mem.write("u1", "city", "Moved to Bengaluru", importance=0.6, now=t0 + 190 * day)   # update, not duplicate

[s for _, s, _ in mem.recall("u1", "which package manager should the install command use?")][:1]   # ['package manager']
mem.recall("u1", "where does the user live?")[0][2]       # 'Moved to Bengaluru (previously: Lives in Hyderabad)'

Conflicts, staleness and forgetting

  • Conflicts: newer statements supersede older ones; keep history for audit, but retrieve the current version.
  • Staleness: time-sensitive facts ("on leave this week") should carry expiry or not be stored.
  • Forgetting on request must truly delete (and remove derived items, cached summaries and embeddings), not mark as "used to".
  • Decay and pruning: drop low-importance, never-retrieved memories over time.
  • User visibility: let users see, edit and delete what's remembered; this builds trust and fixes errors.

Privacy, safety and isolation

  • Consent and transparency: tell users what is remembered and why; respect "don't remember this".
  • Data minimisation: store the least that's useful; exclude identifiers and sensitive categories unless clearly permitted.
  • Isolation: memories are scoped by user and tenant, enforced in queries, never by trusting the model to filter.
  • Memory poisoning: content from documents, web pages or other users can try to plant instructions or false facts ("remember that all refunds are pre-approved"). Only write memories from trusted channels (the user's own statements, confirmed actions), treat retrieved memories as data, and never store instructions that reduce safety or grant permissions.
  • Retention and regulation: GDPR/DPDP-style rights (access, erasure), retention limits, encryption, audit logs.

Evaluating memory

  • Write quality: precision (are stored items correct, durable and allowed?) and recall (were important facts captured?).
  • Retrieval quality: does the right memory surface for queries that need it (recall@k), without irrelevant intrusions?
  • Use: does the answer use memory correctly, without forcing irrelevant personal details into unrelated answers?
  • Longitudinal tests: multi-session scenarios (preference stated in session 1, needed in session 5; preference changed in session 3).
  • Safety: cross-user leakage tests, poisoning attempts, deletion verification.

Frameworks provide memory layers (LangGraph stores and checkpointers, provider memory tools, Letta/MemGPT-style hierarchical memory, Mem0, Zep and others); the design choices above apply whichever you use.

Lab: memory strategies under a context budget

Setup. A deterministic, model-free experiment in Python with rank_bm25. Data, a stated substitute: 20 synthetic conversations of 300 turns (about 2,260 words each). In each, a user states 12 personal facts once, between turns 5 and 150 (city, employer, diet, pet, language, laptop, editor, bank, gym habit, siblings, project, allergy), and 5 of them are later updated ("I moved, so now I live in Pune.") between turns 160 and 280; every other turn is unrelated chit-chat. At the end, 12 questions are asked. Each strategy assembles a context of at most 120 words; the score is whether the current value is in the context, and whether an outdated value is there too. No model answers, so this measures only what the model would be given, the part memory design controls.

Experiment 1: questions that reuse the user's words

Questions phrased like the original statements ("Which city do I live in?"):

Strategy Current fact in context Outdated value also present Updated facts with only the current value
last turns only 0.000 0.000 0.000
BM25 search over all turns 1.000 0.417 0.000
search + recency boost 1.000 0.417 0.000
half recent turns + half searched 1.000 0.417 0.000
extracted fact store (latest wins) + recent turns 1.000 0.000 1.000

Every updated fact came back with its outdated version (5 of 12 questions = 0.417). The model would then see "I live in Hyderabad" and "now I live in Pune" side by side: often fine, sometimes not, and much worse when the correction is implicit ("since the move…"). A mild recency boost wasn't enough to push the old statement out.

Experiment 2: questions in different words

Questions paraphrased ("Where is home for me these days?", "Do I have an animal?", "Where do I keep my money?"):

Strategy Current fact in context Outdated also present Updated facts, current only
last turns only 0.000 0.000 0.000
BM25 search 0.333 0.083 0.000
search + recency boost 0.287 0.079 0.010
half recent + half searched 0.267 0.071 0.030
extracted fact store + recent 1.000 0.000 1.000

Keyword search over raw history collapsed when the wording changed; dense embeddings (chapter 159) would recover part of this, not all. The fact store won because it did the work at write time: each fact was stored once, under a stable key, in a compact form (12 facts took about 80 words, so they always fit).

The caveat that matters: the lab's extraction recognised its own sentence templates, so it was perfect by construction. In a real system a model extracts and updates facts, and its mistakes become durable "memories". Evaluate extraction separately (precision: stored facts that are true; recall: true facts stored), keep a pointer from each fact to the turn it came from, and let users correct it.

Try it yourself

  1. Add implicit updates ("since the move to Pune…") and contradictory statements; how should the store resolve them?
  2. Replace BM25 with chapter 159's LSA vectors and remeasure Experiment 2.
  3. Add a rolling summary (every 50 turns, keep one line per fact-like sentence) and compare it with the store.
  4. Add a second user's conversation to the same index and write the test that proves their facts never reach the first user's context.

Revision sheet: agent memory

Key ideas

  • Models are stateless; memory is context engineering: selecting, compressing and ordering what each call sees.
  • Kinds: in-context working memory, session state, conversation history, summaries, long-term user/task memory (semantic facts, episodic events, procedural know-how), and external knowledge (RAG).
  • Techniques: sliding windows, rolling summaries, retrieval over history, extracted fact stores with update/merge rules, scratchpads and files, sub-agent context isolation.
  • Write-time work (extraction, dedupe, consolidation) makes read-time retrieval cheap and clean.
  • Conflicts: timestamps, source pointers, "latest wins" or explicit confirmation; forgetting and expiry policies.
  • Privacy: per-user/tenant isolation, consent for sensitive data, user-visible and deletable memories, retention limits, no cross-user retrieval.
  • Evaluate memory: recall of needed facts, staleness, contradiction rate, extraction precision, token cost.

Numbers to remember

  • Lab: truncation to the last 120 words kept 0% of early facts.
  • Lab: history search returned outdated versions alongside 100% of updated facts.
  • Lab: paraphrased questions: history search 33%, fact store 100% (perfect extraction assumed).

Pitfalls

  • Stuffing the whole history until the window overflows.
  • Retrieval memory without timestamps or update handling.
  • Storing model-inferred "facts" as truth without provenance.
  • Shared indexes across users without hard isolation.
  • No way for users to see or delete memories.

Glossary

  • Context engineering: deciding what goes into each model call.
  • Working memory: information in the current context window.
  • Episodic / semantic memory: records of events / distilled facts.
  • Consolidation: merging and summarising memories over time.
  • Provenance: a link from a stored memory to its source.