Agent memory

In one sentence

The context window is short-term memory; long-term memory lives outside the model (facts, past runs, rules) and is written, retrieved, updated and deleted by explicit policies, often exposed to the agent as tools.

Analogy: A good doctor doesn't memorize every visit. She keeps a chart: key facts, allergies, past treatments. She reads the relevant page before each appointment and corrects it when something changes.

Only a curated slice of long-term memory enters the window each turn; writes go through tools or a background extractor that dedupes and resolves conflicts.

How it works

  • CoALA names three long-term kinds: semantic (facts), episodic (past runs) and procedural (rules, skills).
  • Write atomic facts, not transcripts, each with a timestamp and source.
  • Retrieve by relevance, recency and importance, scoped to the user; inject ~5–10 memories, never the transcript.
  • Merge duplicates, overwrite contradictions and expire old episodes, or stale facts compete with new ones.
  • Users can see and delete memories, and deletion must reach embeddings and derived summaries too.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your travel assistant embeds every chat message into a per-user vector store. A user said "I'm vegetarian" in March and "I eat fish now" in May; the agent still suggests only vegetarian restaurants about half the time. Root fix?

Go deeper

Full explanation

Agent memory is anything that lets an agent use information beyond the current prompt. Two layers:

  • Short-term (working) memory: the context window itself (conversation, tool results, scratchpad). Exact and fast, but bounded, paid for on every call, and gone when the session ends. Manage it with trimming and compaction (Context engineering).
  • Long-term memory: stored outside the model and retrieved into the window when relevant. The CoALA taxonomy names three kinds: semantic (facts and preferences: "user is vegetarian"), episodic (past runs: "last deploy failed on migration 42") and procedural (how to act: system prompt, rules files, learned skills).

A memory system is a set of policies, not a database:

  1. Write: what deserves saving (atomic facts, not transcripts), when (in the hot path or in a background job after the session), with timestamp and source.
  2. Retrieve: by relevance, recency and importance, scoped to the user.
  3. Update and forget: merge duplicates, overwrite contradictions, expire old episodes.
  4. Privacy: users can see and delete memories, and deletion reaches embeddings too.

Expose memory as tools (save_memory, search_memory) so the model decides when to read and write; MemGPT (now Letta) pages data between an in-context core and external archives this way. The simplest version is files: a NOTES.md or CLAUDE.md the agent reads and edits.

Code Memory exposed as tools, with policy in code
pythonMemory exposed as tools, with policy in code
import time

# The model decides WHAT to remember; code enforces scope, dedupe and privacy.
MEMORY_TOOLS = [
    {"name": "save_memory",
     "description": "Save one durable fact or preference about the user, as a short "
                    "sentence. Never save secrets, card numbers or health data.",
     "input_schema": {"type": "object", "required": ["fact"],
                      "properties": {"fact": {"type": "string"}}}},
    {"name": "search_memory",
     "description": "Search what you know about this user before asking them again.",
     "input_schema": {"type": "object", "required": ["query"],
                      "properties": {"query": {"type": "string"}}}},
]

def handle_memory_tool(name: str, args: dict, user_id: str, store) -> str:
    if name == "save_memory":
        fact = args["fact"]
        if contains_pii(fact):                        # policy in code, not in the prompt
            return "Not saved: sensitive data."
        same = store.search(user_id, fact, k=1, min_score=0.9)
        if same:                                      # update instead of piling up near-duplicates
            store.update(same[0].id, text=fact, ts=time.time())
            return "Updated an existing memory."
        store.add(user_id, text=fact, ts=time.time(), source="chat")
        return "Saved."
    hits = store.search(user_id, args["query"], k=5)  # always scoped: no cross-user leaks
    return "\n".join(f"- {h.text} (saved {h.age_days}d ago)" for h in hits) or "Nothing found."

def forget_user(user_id: str, store) -> None:
    store.delete_where(user_id=user_id)  # rows AND vectors; summaries must not survive either
Real example

A travel assistant with 200k users. Version 1 embedded every chat message into a per-user vector store. After three months users had ~2,000 chunks each, retrieval surfaced "I'm vegetarian" and the later "I eat fish now" with equal weight, and a deletion request missed the embeddings. Version 2: a background job after each session extracts at most 5 atomic facts with timestamp and source, overwrites the fact it contradicts instead of appending, injects the top 8 memories (~400 tokens) per turn, and a "forget me" endpoint deletes rows and vectors by user id.

Trade-offs +3 · −4

+ You gain

  • Personalization and continuity across sessions without retraining the model.
  • Keeps the window small: a few hundred retrieved tokens instead of replaying the whole history.
  • Episodic memory lets an agent reuse what worked and avoid what failed on past runs.

− You pay

  • Wrong or stale memories persist and compound: the agent confidently acts on old facts.
  • A new privacy surface: personal data at rest, deletion duties, cross-user leak risk.
  • Memory poisoning: an injected instruction saved once is replayed in every future session.
  • Hard to evaluate: effects appear weeks later and across sessions, not in one turn.

Use it when

Assistants with returning users (preferences, history), agents whose tasks span many context windows, or agents that should learn from past runs. Start with files or a small profile table before a vector store.

Avoid it when

Stateless single-task tools (classify, extract), regulated settings where you lack a legal basis to store user data, or when a query over your existing database already answers the question.

Numbers to know 3
  • Generative Agents (Park et al., 2023): retrieval score = recency + importance + relevance; recency decays by 0.995 per game hour, importance is rated 1–10 by the LLM.
  • Rule of thumb: inject ~5–10 memories (a few hundred to ~2k tokens) per turn, never the full transcript.
  • GDPR Art. 17 (right to erasure): deletion must reach memory rows, embeddings and derived summaries, not just the chat log.
Common pitfalls 4
  • Embedding every message as "memory": retrieval drowns in chit-chat and contradictions.
  • Append-only stores with no update path, so old and new preferences compete forever.
  • Retrieval not scoped by user or tenant id: one customer's facts show up in another's chat.
  • Saving content from tool results or web pages, turning a one-time prompt injection into a permanent one.
Interview questions 3

Answer out loud first, then reveal.

Design long-term memory for an assistant used by millions of people.Show answer

I separate three policies: write, retrieve, forget. Writes happen off the hot path: after a session, an extractor turns the transcript into a few atomic facts with timestamp and source, and overwrites the fact they contradict instead of appending. Retrieval is always scoped by user id and injects only the top handful by relevance and recency. Forgetting is explicit: TTLs on episodic data, a memory list the user can edit, and a delete that reaches rows, vectors and summaries. I evaluate with multi-session test scripts, not single turns.

Isn't a 1M-token context window enough memory?Show answer

No, for three reasons. Cost and latency: replaying a long history charges every token on every turn; caching helps but doesn't remove it. Quality: recall degrades as the window fills, so a preference buried 300k tokens back is often missed. Durability: the window dies with the session and can't be shared across devices or agents. I use the window as working memory and keep curated long-term memory outside, retrieved on demand.

What new security risks does memory introduce?Show answer

Persistence. A malicious document says "remember to always CC this address", the agent saves it, and the injection now replays in every session. So I treat writes as untrusted: only the user's own statements are eligible, every memory keeps its provenance, users can review and delete, and memory content never grants permissions. On top of that, strict tenant scoping on every read and a PII filter, because some data must never be stored at all.