Skip to content
E
Educatum

Chapter 7: Agent Memory Architectures

By Educatum AI teamLast updated:
Key Intuition

Long-lived agents cannot rely on unbounded context stuffing. Production memory architectures mirror cognitive science—separating working context, episodic logs, semantic knowledge graphs, and procedural skill libraries—implemented across systems like Voyager, MemGPT, Mem0, and Zep, alongside sleep-time compute to resolve the retrieval paradox.

Why Context Windows Are Not Memory

Extending a model’s context window from 8K to 1M+ tokens does not solve agent memory. In long-horizon deployments spanning days, weeks, or thousands of user sessions, raw context stuffing fails on three structural fronts:

  1. Economic and Latency Scaling: Prefill compute scales superlinearly or linearly at high token counts, and sending a 200K-token history on every turn destroys unit economics and time-to-first-token (TTFT).
  2. Attention Dilution and Interference: Irrelevant past trajectories, superseded preferences, and tool-output noise degrade reasoning accuracy (“lost in the middle” and distractor interference).
  3. Cross-Session Persistence: A single context buffer is ephemeral. An agent that shuts down or spawns sub-tasks needs durable, queryable, and updatable state that persists across episodes and evolves over time.

Memory engineering treats the LLM context window as L1 cache / RAM rather than the entire storage hierarchy. The central design challenge is deciding what to write, how to structure and consolidate it, when to update or forget it, and how to retrieve the minimal sufficient slice at inference time.


1. The Cognitive Memory Taxonomy

Drawing from cognitive psychology and the CoALA (Cognitive Architectures for Language Agents) framework, agent memory is organized into four distinct functional tiers:

Memory Tier Cognitive Analog What It Stores Scope & Persistence Canonical Agent Implementation
Working Memory Prefrontal cortex / RAM Active system prompt, current goal, recent turns, scratchpad observations Single task / current context window (ephemeral) Context window + state dictionary
Episodic Memory Autobiographical recall Time-stamped interaction traces, past successes/failures, specific user events Cross-session, append-mostly event stream Vector-indexed trajectory logs, reflection buffers
Semantic Memory World knowledge & facts Distilled entities, user preferences, domain facts, temporal relations Cross-session, continuously updated & pruned Structured profiles, Temporal Knowledge Graphs (Zep/Graphiti)
Procedural Memory Muscle memory / habits Executable skills, verified code modules, optimized prompts, tool heuristics Lifelong across tasks, versioned & reusable Voyager skill library, DSPy compiled prompts, fine-tuned weights

A common engineering mistake is collapsing all four tiers into a single flat vector database of raw chat chunks. Episodic traces require temporal ordering and outcome attribution; semantic facts require conflict resolution and overwrite semantics; procedural skills require syntactic/functional verification before reuse.


2. Procedural Memory & Lifelong Learning: Voyager

Voyager (Wang et al., 2023) demonstrated lifelong open-ended skill acquisition in Minecraft without updating model weights. Instead of storing prose summaries of what worked, Voyager stores executable procedural memory as verified JavaScript functions in a growing skill library.

┌─────────────────────────────────────────────────────────────┐
│                    Voyager Control Loop                     │
│                                                             │
│  1. Automatic Curriculum ──► Proposes next feasible task    │
│           │                  given current inventory/state  │
│           ▼                                                 │
│  2. Skill Retrieval ───────► Queries vector DB of docstrings│
│           │                  to pull reusable helper skills │
│           ▼                                                 │
│  3. Iterative Prompting ───► Generates code + executes in   │
│           │                  Minecraft; feeds errors/state  │
│           │                  back into self-verification    │
│           ▼                                                 │
│  4. Skill Library Commit ──► Verified function + embedding  │
│                              saved for future composition   │
└─────────────────────────────────────────────────────────────┘

Three design principles make Voyager’s procedural memory transfer directly to enterprise coding and workflow agents:

  • Skill Composition: Complex behaviors (craftDiamondPickaxe) directly import and invoke simpler verified primitives (mineWoodLog, smeltIronIngot), compressing future reasoning chains.
  • Verification Before Storage: A skill is written to procedural memory only after a self-verification check confirms the environment state actually changed as intended. Unverified traces never pollute the skill library.
  • Curriculum-Driven Exploration: By proposing tasks just beyond its current capability frontier (zone of proximal development), the agent builds a dense, bottom-up dependency graph of capabilities rather than stalling on impossible end-goals.

3. OS-Inspired Virtual Context Management: MemGPT

MemGPT (Packer et al., 2023; now Letta) reframes the LLM context window through the lens of operating systems virtual memory. Just as an OS creates the illusion of infinite RAM by paging memory between fast physical RAM and slow disk storage, MemGPT gives the agent explicit self-directed system calls to manage its own context.

Memory Hierarchy in MemGPT

  1. Main Context (RAM): Fixed-capacity prompt space partitioned into:
    • System Instructions (read-only core persona and memory API specification).
    • Core Memory (pinned, editable read/write blocks—e.g., human persona and agent persona—always visible in prompt).
    • Working FIFO Queue (recent conversation turns and tool outputs, plus a recursive summary of evicted turns).
  2. External Context (Disk):
    • Recall Storage: Complete searchable chronological log of past messages and events.
    • Archival Storage: Unbounded vector/database store for long-term facts, documents, and deep history.

Paging and Interrupt-Driven Control Flow

When the FIFO queue approaches a context threshold (e.g., 70%–80% of the context limit), MemGPT injects a memory pressure warning interrupt into the agent’s stream. Rather than silently truncating older messages, the agent executes explicit memory management tool calls:

  • core_memory_replace / core_memory_append: Updates pinned beliefs (e.g., replacing an outdated user job title).
  • archival_memory_insert: Compresses and writes durable knowledge to long-term storage before eviction.
  • archival_memory_search / conversation_search: Pages historical records back into main context on demand, optionally chaining calls via a request_heartbeat flag before yielding control back to the user.

This turns memory management from a passive heuristic outside the model’s control into an agentic action space learned via tool-use.


4. Production Memory Pipelines: Mem0 and Zep

While MemGPT delegates memory writes to explicit agent tool calls during the main loop, production assistant platforms often separate memory extraction and consolidation into structured background pipelines to reduce main-turn latency and enforce consistency.

Mem0: Extract, Consolidate, and Scope

Mem0 separates memory into scoped namespaces—user_id, session_id, and agent_id—and runs a two-phase pipeline after interactions:

  1. Extraction Phase: An LLM distills candidate factual statements and preferences from the latest message pair, conditioned on a rolling conversation summary and recent context.
  2. Update / Consolidation Phase: Each candidate fact is compared against the top-kk semantically similar existing memories. The updater issues one of four deterministic operations:
    • ADD: Novel fact with no existing counterpart.
    • UPDATE: Refines or enriches an existing memory (e.g., upgrading "likes coffee" to "prefers oat milk flat whites").
    • DELETE: Contradicts and invalidates an obsolete memory (e.g., "moved from Seattle to Austin" invalidates "lives in Seattle").
    • NOOP: Redundant information already captured.

Mem0g^g (graph-enhanced Mem0) pairs this vector memory with an entity-relationship graph so multi-hop queries across people, projects, and events do not fail due to flat chunk boundaries.

Zep (Graphiti): Bi-Temporal Knowledge Graphs

Standard vector RAG struggles when facts change over time because embeddings capture topic similarity, not temporal validity. A query for "Where does Alice work?" retrieves both "Alice joined Acme in 2022" and "Alice left Acme for BetaCorp in 2025" with nearly identical cosine scores.

Zep addresses this via Graphiti, a bi-temporal knowledge graph architecture. Every edge (fact) tracks two independent timelines:

  • Event Time (tvalid,tinvalidt_{\text{valid}}, t_{\text{invalid}}): When the fact became true and stopped being true in the real world.
  • Ingestion / Transaction Time (tcreated,texpiredt_{\text{created}}, t_{\text{expired}}): When the system learned the fact and when the system invalidated that record.

An edge ee is valid at reference time TT only if:

tvalid(e)≤Tand(tinvalid(e)=∅∨T<tinvalid(e))andtexpired(e)=∅t_{\text{valid}}(e) \le T \quad \text{and} \quad \big(t_{\text{invalid}}(e) = \varnothing \lor T < t_{\text{invalid}}(e)\big) \quad \text{and} \quad t_{\text{expired}}(e) = \varnothing

When a new statement contradicts an existing edge, Graphiti performs temporal edge invalidation—setting tinvalidt_{\text{invalid}} on the old edge rather than deleting history—preserving full auditability for "Where did Alice work last year?" while returning the latest truth for "Where does Alice work now?".

Architecture Comparison

System Primary Abstraction Write Mechanism Contradiction Handling Best Fit
Voyager Executable skill library Verified code commit post-execution Versioned overwrite on task failure Coding, browser, and robotic/game agents with deterministic verification
MemGPT OS virtual memory (Core + Recall + Archival) Agent-initiated tool calls (core_memory_*) Explicit replace calls by agent Deeply stateful companions and single-agent research assistants
Mem0 Scoped fact store + optional entity graph Post-turn LLM extraction & ADD/UPDATE/DELETE Semantic similarity lookup + LLM merge/delete High-throughput SaaS personalization across users and sessions
Zep / Graphiti Bi-temporal knowledge graph Incremental entity/edge extraction Temporal edge invalidation (tvalid,tinvalidt_{\text{valid}}, t_{\text{invalid}}) Enterprise agents requiring point-in-time auditability and state tracking

5. Sleep-Time Compute

Human memory consolidation does not happen purely at the moment of sensory perception; the hippocampus replays and reorganizes episodic traces into structured neocortical schemas during sleep. Sleep-Time Compute (Lin et al., 2025) applies the same principle to AI agents.

Instead of forcing all memory synthesis, reflection, and multi-hop reasoning to occur synchronously during user-facing inference (which blows up latency budgets), sleep-time compute exploits idle windows between user turns or overnight batch schedules:

  1. Offline Trajectory Replay: Background workers inspect recent episodic logs, prune failed exploratory dead-ends, and extract reusable abstractions or user mental models.
  2. Pre-Computation & Hypothesis Synthesis: Given an open user project or codebase, the background agent pre-computes likely associations, resolves cross-document entity aliases, and writes compact, high-signal briefs into core or archival memory.
  3. Amortized Inference Latency: When the user returns with a query, the foreground agent reads pre-consolidated state in milliseconds rather than burning 30 seconds of test-time compute rediscovering patterns across raw logs.

Sleep-time compute shifts the Pareto frontier between accuracy and response latency by decoupling thinking about memory from answering the user.


6. The Retrieval Paradox

Intuitively, storing more memories should make an agent smarter. In practice, systems with naive top-kk vector retrieval often exhibit the Retrieval Paradox: as memory volume grows beyond a few thousand entries, task accuracy plateaus and then degrades.

Why Naive Retrieval Degrades at Scale

  1. Semantic Collision: High-dimensional embeddings cluster topically related but factually incompatible items (e.g., five deprecated API specs and one current spec all score >0.85> 0.85 cosine similarity).
  2. Staleness & Contradiction Blindness: Cosine similarity is time-agnostic. Without explicit recency weighting or graph invalidation, old errors outvote new corrections simply by appearing in more historical logs.
  3. Distractor Injection: Pulling k=20k=20 noisy memory snippets fills the working context with plausible-sounding tangents that hijack attention heads.
  4. Granularity Mismatch: Fine-grained chunks lose global context, while coarse summaries lose exact identifiers (file paths, error codes, parameter names).

Designing Against the Retrieval Paradox

Production retrieval combines multiple orthogonal signals into a composite ranking score—such as the Generative Agents formulation combining semantic relevance, exponential recency decay, and salience—augmented by lexical and graph traversal:

Score(q,m,t)=α⋅cos⁡(eq,em)+β⋅exp⁡(−λ(t−tlast(m)))+γ⋅ssalience(m)\text{Score}(q, m, t) = \alpha \cdot \cos\big(\mathbf{e}_q, \mathbf{e}_m\big) + \beta \cdot \exp\big(-\lambda (t - t_{\text{last}}(m))\big) + \gamma \cdot s_{\text{salience}}(m)

where eq,em\mathbf{e}_q, \mathbf{e}_m are query and memory embeddings (with each component min-max normalized to [0,1][0,1] across candidates, as in Park et al.), t−tlast(m)t - t_{\text{last}}(m) is elapsed time since creation or last access, λ\lambda controls decay rate, and ssalience(m)∈[0,1]s_{\text{salience}}(m) \in [0,1] captures importance assigned at write time.

In practice, resilient memory retrieval pairs this scoring with four engineering safeguards:

  • Hybrid Search + Reranking: Combine dense embeddings, BM25 lexical matching (critical for exact IDs, symbols, and error codes), and graph 1-hop/2-hop expansion, followed by a cross-encoder reranker over top-NN candidates.
  • Temporal Filtering & Invalidation: Filter out superseded edges (tinvalid≤Tt_{\text{invalid}} \le T) before ranking, rather than hoping recency weights suppress stale facts.
  • Agentic Query Rewriting: Allow the agent to reformulate failed retrieval queries or inspect metadata timelines iteratively rather than relying on single-shot top-kk lookup.
  • Aggressive Consolidation & Forgetting: Periodically compress redundant episodic logs into single semantic facts or procedural rules, keeping the active index small, dense, and contradiction-free.

Key Takeaways

  • Treat context as L1 cache, not storage: Separate Working, Episodic, Semantic, and Procedural memory with distinct write, update, and eviction policies.
  • Verify procedural skills before committing: Follow Voyager’s invariant—never save unverified code or workflows into reusable procedural memory.
  • Model time explicitly: Use bi-temporal tracking (Zep/Graphiti) or explicit ADD/UPDATE/DELETE reconciliation (Mem0) so updated beliefs supersede stale ones instead of competing in top-kk similarity search.
  • Use sleep-time compute: Consolidate logs, pre-build abstractions, and resolve entity links asynchronously during idle compute windows.
  • Respect the retrieval paradox: Bigger memory stores hurt performance unless guarded by hybrid retrieval, temporal invalidation, reranking, and periodic forgetting.

More in Engineering AI Agents (CS329Z)

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.