Skip to content

Memory and Knowledge

Agent memory

Working, episodic, semantic memory

An LLM forgets everything the instant a call returns - it is stateless between turns. Memory is the machinery that lets an agent carry what it learned across turns and across sessions: a taxonomy borrowed from human cognition, and a write, read, reflect loop that keeps it useful over time.

Why agents need memory at all

A base model is a pure function: tokens in, tokens out, no side effects, no recollection. Whatever an agent "knows" during a run lives in exactly one place - the context window it was handed this turn. That window is the agent's only working memory, and it has two hard limits: it is volatile (cleared between sessions, and compacted mid-session to make room) and capacity-limited (you cannot just keep appending). Worse, quality degrades before the window even fills - Chroma's 18-model study measured this "context rot" on trivial tasks, well short of the token ceiling.[2]

So "remember more" cannot mean "stuff more into the prompt." Anthropic frames the real job as curating the smallest set of high-signal tokens that get the desired behavior, and fetching the rest just-in-time from outside the window.[1] Memory is that "outside": a persistent store the agent writes to and reads from, so a small window can behave like a large, long-lived mind. This is the same instinct behind context engineering - decide what belongs in the window - pushed across time instead of just across one turn.

The one-sentence definition

= an external, persistent store plus the read/write/reflect machinery that moves information between it and the context window - so knowledge survives the statelessness of the underlying model.

The taxonomy: human memory, mapped

The field did not invent a taxonomy - it borrowed cognitive science's. The dominant formalization is CoALA (Cognitive Architectures for Language Agents), and Letta, Mem0, and LangGraph all adopt it.[3] The top split is working (short-term) vs long-term; long-term then divides into three kinds that map cleanly onto how humans remember.[4]

Tap a node to see what it does.

The CoALA memory taxonomy. Working memory is the context window itself; long-term splits into episodic, semantic, and procedural, each mapped to a human-memory analogue. Frameworks like Letta, Mem0, and LangGraph implement both halves.
TypeHuman analogueWhat it holdsWhere it lives
Working / short-termShort-term memoryThe prompt + recent turns of this taskIn the context window - zero retrieval latency, but volatile
EpisodicRemembering eventsSpecific past interactions: what happened, when, in which sessionExternal store (vector DB / files)
SemanticKnowing that (facts)Durable facts: user preferences, world knowledge, configExternal store
ProceduralKnowing how (skills)Skills, rules, routines, policiesOften in the weights, or explicit in the system prompt / tool defs
The CoALA split: one volatile in-context layer above three durable, retrieved-on-demand long-term stores.

A fourth layer, sensory memory, maps to the learned embedding representations of raw inputs - transient pre-processing rather than something the agent reads back. For agent-building purposes the working / episodic / semantic / procedural split is the one that earns its keep.[5]

The loop: write, read, reflect

A taxonomy tells you what to store; the loop tells you how the store stays alive. Three operations run against long-term memory. Write and read are the obvious pair; reflect is what separates a real memory from a dumb log.

Tap a node to see what it does.

The write, read, reflect loop. Write pushes salient facts out of the window into the store; read pulls only the relevant few back in on demand; reflect is the store consolidating raw entries into higher-level, deduplicated knowledge.
  1. Write. Do not dump the whole transcript. An extraction step (usually a small LLM pass) pulls the salient facts from the new turn and persists them - Anthropic calls this structured note-taking: cheap durable memory the agent re-hydrates later.[1]
  2. Read. At each turn, retrieve just the few memories relevant to the current query - embed the query, run ANN vector search over the store, and inject the top matches. The store may hold thousands; only about 3 high-signal ones enter the window.
  3. Reflect. Periodically, the agent reasons over its own memories to write new ones: consolidate duplicates, resolve contradictions, and synthesize higher-level insights ("this user is a power user") that no single raw event stated.

Reflection is the dividing line

Read + write alone gives you a searchable journal. Reflection is what turns accumulated experience into knowledge - and it is exactly what a read-only retrieval system cannot do. It is also where memory meets self-correction: an agent that reflects on its history can notice and fix its own stale beliefs.

A concrete trace: read, then write-back

A returning user, session 5. The store already holds facts from earlier sessions.

  1. Query. "Book me the usual table for Friday." Embed it to a vector.
  2. Read. ANN search over this user's long-term memory returns the top matches: "prefers window seat at Luigi's, party of 2" (semantic, 0.83), "last 4 Friday bookings were 7:30pm" (episodic, 0.79), "vegetarian" (semantic, 0.61).
  3. Assemble. Working context = system prompt + those ~3 retrieved memories (not the whole store) + the current turn.
  4. Act. The model calls reserve(restaurant="Luigi's", time="19:30", seats=2, seat="window").
  5. Write-back. An extract-then-update pass records the new episode and leaves unchanged facts alone.
ADD   episodic -> "Session 5: booked Luigi's Fri 7:30pm, window, party of 2"
NOOP  on "vegetarian" (unchanged - no duplicate)
The write-back decision: add the new episode, leave the still-true semantic fact untouched.

Thousands of memories in the store, but only ~3 (about 150 tokens) ever entered the window. That is the whole game: small working set, big backing store, retrieval on demand - the memory version of the just-in-time principle.

How memory differs from RAG

Memory and RAG share the exact same retrieval substrate - embeddings + ANN search - which is why they are easy to conflate. But they point in opposite directions. Classic RAG is read-only retrieval over a corpus someone else curated; memory is read and write over a store the agent authors from its own experience, and keeps current.

RAG (read-only retrieval)Agent memory
DirectionRead onlyRead and write
Source of contentAn external corpus you indexedSelf-authored from the agent's own experience
LifetimeA mostly-static corpusPersists and evolves across sessions
UpdatingRe-index offline when docs changeWrites back live: ADD / UPDATE / DELETE
ReflectionNone - retrieval does not reasonSynthesizes new, higher-level memories
Same retrieval substrate, opposite direction: RAG reads a static corpus; memory reads and writes a store the agent keeps current.

In practice the line blurs - agentic RAG lets a model decide when and what to retrieve, and a memory system uses RAG-style retrieval on every read. The useful distinction is persistence + updating + reflection: RAG answers "what does the corpus say?"; memory answers "what have I learned, and is it still true?"

Frameworks: two ways to build it

Two designs dominate, and they sit at different altitudes. One gives the model low-level control of a memory hierarchy; the other runs an automatic pipeline around the model.

MemGPT / Letta - LLM as an OS

MemGPT ("Towards LLMs as Operating Systems") applies virtual-memory ideas to the context window.[7] The model is handed a hierarchy - main context (the window, like RAM), recall memory (a searchable log of past conversation), and archival memory (an external vector store) - plus tools to move data through it. It decides when to page out (main to archival), page in (archival to main), search recall, or even edit its own system prompt, all as function calls. A small window "feels" large. MemGPT productized into Letta (Postgres persistence, filesystem-backed memory blocks).

Mem0 - an extract-then-update pipeline

Mem0 sits between your app and the LLM and runs two stages on every exchange.[6] Extraction: an LLM pulls salient facts from new messages + context. Update: a second LLM decides, per candidate fact, one of ADD UPDATE DELETE NOOP against existing memories, keeping the store consistent (e.g. "moved from NYC to SF" is an UPDATE, not a duplicate ADD). On the LOCOMO long-conversation benchmark, Mem0 reports about 26% higher accuracy than OpenAI's memory, 91% lower p95 latency, and over 90% token savings vs stuffing the full conversation in context; a graph variant adds about 2%.[6]

Memory as a platform primitive (2025)

Memory is now shipping as a first-class API, not just a framework. Anthropic's memory tool is file-based CRUD in a developer-owned directory - entirely client-side, and it persists across sessions.[9] Paired with context editing (auto-clearing stale tool results), Anthropic reports +39% over baseline and 84% fewer tokens on a 100-turn eval - the write-out / read-back loop, built into the platform.[8]

The canonical example: Generative Agents ("Smallville")

The clearest demonstration of the full loop is the Generative Agents simulation - 25 agents living in a sandbox town, "Smallville," each with a memory architecture rich enough to produce believable behavior (one throws a Valentine's party and others actually show up and remember it).[4] It is a working reference design for all three operations.

  1. Memory stream (write). Every observation is appended to a long-term memory stream - a timestamped, natural-language log of what the agent saw and did. Pure episodic write.
  2. Scored retrieval (read). To act, the agent retrieves memories scored on three axes: recency (recent-weighted), importance (self-rated salience), and relevance (embedding similarity to the moment). Not just nearest-neighbor.
  3. Reflection (reflect). Periodically the agent synthesizes its recent memories into higher-level reflections - abstract inferences that themselves become new memories and steer future planning.

That importance-weighted retrieval and the reflection tree are the parts a plain vector search does not give you - and they are exactly the "reflect" edge of the loop made concrete.[4]

What breaks

Do

Pick the type deliberately: episodic for personalization, semantic for durable facts, procedural for skills/policies. Extract, do not dump - write salient facts, not raw transcripts. Version and expire - timestamp episodes; dedupe and prune on write so retrieval stays high-signal.

Do not

Let memory clash - a stale fact the user changed (old address, old preference) misleads the model, the exact failure Mem0's UPDATE/DELETE stage targets.[6] Grow it unbounded - naively appending everything exhausts the window and inflates cost/latency. Trust it blindly - memory is a read of past (possibly poisoned) content, a security surface, like retrieval.

Memory is an injection surface

Anything written to a durable store is re-read into context later. If an agent can be tricked into saving an attacker instruction as a memory, that instruction executes on a future turn. Treat writes as untrusted input, not just reads. The security lesson returns to this.

Check yourself

Match each long-term memory subtype to its human-memory analogue.

drop here

remembering what happened, tied to time

drop here

knowing that: accumulated facts

drop here

knowing how: skills and routines

An agent learns a user moved from NYC to SF, so it overwrites the old 'lives in NYC' fact instead of keeping both. Which capability distinguishes agent memory from plain read-only RAG?

Name the three subtypes of long-term agent memory (CoALA) and each one's human-memory analogue.

And what sits above all three? Try to state it, then check.

Lock it in

  • Memory exists because the model is stateless. The context window is the only working memory, and it is volatile and capacity-limited, so knowledge has to live in an external store.
  • The taxonomy is human memory, borrowed. Working (short-term, in-context) vs long-term, and long-term splits into episodic (events), semantic (facts), procedural (skills).
  • The loop is write, read, reflect. Extract salient facts out, retrieve the relevant few back just-in-time, and periodically reason over memories to synthesize new ones.
  • Reflection + updating is what memory adds over RAG. Same retrieval substrate, but memory persists, writes back, and reasons about itself; RAG is read-only.
  • Two builds: MemGPT/Letta gives the model OS-style paging control; Mem0 runs an automatic extract-then-update pipeline (ADD/UPDATE/DELETE/NOOP).

Primary source

Lilian Weng, LLM Powered Autonomous Agents

The single best read to pair with this lesson: it lays out the sensory / short-term / long-term taxonomy, the MIPS/ANN retrieval substrate, and walks through the Generative Agents (Smallville) memory stream, scored retrieval, and reflection in one place. For the formal taxonomy, follow it with the CoALA paper.

Sources

  1. 1.Anthropic, Effective Context Engineering for AI Agents
  2. 2.Chroma, Context Rot
  3. 3.Sumers et al., Cognitive Architectures for Language Agents (CoALA)
  4. 4.Lilian Weng, LLM Powered Autonomous Agents
  5. 5.Atlan, Types of AI Agent Memory
  6. 6.Chhikara et al., Mem0: Building Production-Ready AI Agents
  7. 7.Packer et al., MemGPT: Towards LLMs as Operating Systems
  8. 8.Anthropic, Context Management
  9. 9.Anthropic, Memory Tool (Claude Docs)