Chapter 15 of 32 · ~22 min read & lab+80 XP
Chapter 15 · Agentic AI

Long-Term Agent Memory: Episodic, Semantic & Procedural Memory Stores (Mem0/Letta)

How AI agents remember users across days and sessions: cognitive 3-tier memory (Working, Episodic, Semantic), the Mem0 write-consolidation loop (ADD / UPDATE / DELETE / NOOP), and Relevance + Recency + Importance retrieval scoring.

What Is It?

Long-Term Agent Memory persists information across sessions in three distinct stores: Semantic Facts (user preferences), Episodic Logs (past experiences), and Procedural Rules (learned habits).

Why Is It Required?

Without persistent memory, an agent forgets your preferences, tech stack, and past mistakes every time you open a new chat.

Everyday Analogy: A personal assistant's CRM notebook recording your favorite airline (Semantic), last trip's delay (Episodic), and your booking checklist (Procedural).
Why ML Engineers & Data Scientists Actually Need This

Long-term memory is what transforms a stateless chatbot that asks 'What language do you code in?' every morning into a truly personalized AI teammate!

ML / AI Engineer

A naive append-only vector DB quickly fills with contradictory stale facts ('Lives in NYC' AND 'Lives in Tokyo') — implementing the ADD / UPDATE / DELETE / NOOP consolidation step solves memory rot cleanly!

Data Scientist

Combining semantic cosine similarity with exponential recency decay (exp(-λ · Δt)) ensures recent project context outranks 6-month-old memories.

Interview & Debug Edge

Modern Agentic AI design question: 'Design a cross-session Long-Term Memory system for an AI assistant — how do you handle contradictory user updates and multi-tenant privacy?'

Step 0 · Test Your Gut Before Any Math!

When a user says 'I just moved from NYC to Tokyo', which operation should a Long-Term Memory Consolidator perform against the existing 'Lives in NYC' record?

What You Will Master in This Chapter
  • Distinguish Working Memory (live context), Episodic Memory (past trajectories & lessons), Semantic Memory (user facts & preferences), and Procedural Memory (refined prompts/skills)
  • Trace the Mem0 / Letta Write-Consolidation pipeline: extract facts → search existing memories → reconcile via ADD / UPDATE / DELETE / NOOP
  • Rank retrieved memories using Generative Agents composite scoring: α·Relevance + β·RecencyDecay + γ·Importance
  • Enforce strict per-user isolation, TTL/forgetting, and privacy deletion ('Forget my address') in production memory stores
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Working / Episodic / Semantic\text{Working / Episodic / Semantic}Say aloud:“cognitive memory tiers”
Plain-English Meaning
Live context window vs. past session experiences vs. durable user/world facts
Everyday Example
CoALA framework + Mem0 / Letta
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of your own brain: Working Memory is what you're holding in your head right now; Episodic Memory is remembering 'Last Tuesday's deploy broke because of an env var'; Semantic Memory is knowing 'I prefer TypeScript and live in Tokyo'. An AI agent uses the exact same 3 tiers — backed by a clean database that updates old facts when your life changes!

1. The 3-Tier Cognitive Memory Model (CoALA)

Everyday Story First (Zero Math Yet!)

Separating memory by type lets you store each tier in the optimal backend (RAM/messages for Working, vector+timestamp DB for Episodic, structured KV/graph for Semantic).

Cognitive 3-Tier Agent Memory Architecture (CoALA / Mem0 / Letta)1. Working MemoryLive LLM ContextCurrent chat & scratchpad2. Episodic MemoryPast Events & Runs'Last deploy failed on port 8080'3. Semantic MemoryStructured User Facts'User prefers TypeScript & pytest'
Cognitive 3-Tier Agent Memory: Working Memory (live context window), Episodic Memory (past sessions & lessons), and Semantic Memory (user facts & preferences stored in a vector/graph DB).

Bonus 4th Tier: Procedural Memory

Beyond Working, Episodic, and Semantic, Procedural Memory stores how to do tasks well — versioned System Prompts, reusable tool-use skills, and domain playbooks that improve over time!

2. Write Consolidation: ADD / UPDATE / DELETE / NOOP

Everyday Story First (Zero Math Yet!)

Click New Fact / Changed Fact / Chit-Chat in the mini-lab below to see how a Memory Consolidator decides whether to ADD, UPDATE, or skip (NOOP)!

Long-Term Memory Consolidation: Extract → Retrieve → ADD / UPDATE / DELETE / NOOP1. Extract Fact'Moved to Tokyo'2. Vector LookupFound: 'Lives in NYC'3. ReconcileDecision: UPDATE4. Commit DBZero stale conflicts ✓
Mem0 / Letta Write Pipeline: extract candidate facts → retrieve similar existing memories → decide ADD, UPDATE (overwrite stale fact), DELETE, or NOOP!

Async Background Extraction (Zero User Latency!)

Never block the user's chat response waiting for memory extraction! Run the Extract → Search → Reconcile pipeline asynchronously in the background right after streaming the reply to the user!

Animated Mini-Lab • 3.2

Long-Term Memory Write Consolidator

User: "I moved from NYC to Tokyo."
Action: UPDATE — Conflicts with 'Lives in NYC' → overwrite old fact so agent never uses stale city!

3. Composite Retrieval Scoring & Privacy Scoping

Everyday Story First (Zero Math Yet!)

Pure cosine similarity retrieves 1-year-old trivial comments over yesterday's urgent preference — composite scoring fixes that!

Generative Agent Memory Retrieval Score: α·Relevance + β·Recency + γ·ImportanceSemantic Relevancecos(q, mem)Recency Decayexp(−λ · Δt_hours)Importance Weightscore ∈ [1..10] / 10
Memory Ranking combines Recency (exponential decay), Semantic Relevance, and Importance — while conflict resolution overwrites outdated facts ('Lives in NYC' → 'Moved to Tokyo')!

Non-Negotiable Production Privacy Rules

  • Strict Tenant/User Partitioning: Every vector query MUST filter by WHERE user_id = auth_user_id at the DB index level!
  • User Transparency & Right-to-Forget: Let users view and delete stored memories ("Forget my home address" → DELETE).
  • Never store raw secrets (passwords, credit card numbers, API keys) in long-term memory!
Walk Through With Me · Interactive Worked Example

Worked Example: Ranking Two Memories with Recency Decay

Memory A (1 hour ago, rel=0.82, imp=0.8). Memory B (200 hours ago, rel=0.86, imp=0.5). Weights α=0.5, β=0.3, γ=0.2, decay λ=0.01/hr.

11. Score Memory A (Fresh & Important)Step 1 / 2

0.5(0.82)+0.3(e−0.01)+0.2(0.80)=0.41+0.297+0.16=0.8670.5(0.82) + 0.3(e^{-0.01}) + 0.2(0.80) = 0.41 + 0.297 + 0.16 = \mathbf{0.867}.

Teacher's Note: Freshness + importance push A to #1!
Pause & Check · Quick Intuition Pulse

In Mem0-style memory consolidation, what operation should fire when the user sends pure chit-chat like 'Okay, thanks!'?

Try It YourselfStandard

Why should Long-Term Memory extraction run asynchronously after replying rather than blocking before the LLM responds?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Letta gives the LLM explicit memory-editing tools (core_memory_replace, archival_memory_insert, archival_memory_search) so the agent itself manages its own OS-like RAM (context) and Disk (archival DB)!

Interactive Visual Lab
Lab Challenge: Watch all 4 steps of the 60 FPS 3-Tier Cognitive Memory Animator personalize an underspecified flight request.
Interactive Animation • 3.2 Deep Lab

3-Tier Cognitive Agent Memory (Working ↔ Semantic ↔ Episodic)

See how an agent resolves an underspecified request ('flight home') by pulling durable facts and past lessons.

Step 1 / 4
1. Working Memory (Input)
User: 'Book me a flight home for Friday.'
0%
1. Working Memory (Input)
Intuition Takeaway: Long-Term Agent Memory separates Working, Episodic, and Semantic stores, keeps facts conflict-free via async ADD / UPDATE / DELETE / NOOP consolidation, and retrieves via Relevance + Recency + Importance strictly scoped per user.
Where This Powers Real ML, Deep Learning & Generative AI

Personalized Coding, Coaching & Enterprise Assistants

Remembers user tech stack, coding conventions, past incident fixes, and preferences across months.

Production NumPy & PyTorch Code Patterns
from dataclasses import dataclass, field

# 3-Tier Long-Term Agent Memory Store: Semantic Facts, Episodic Logs & Procedural Rules
@dataclass
class AgentMemoryStore:
    semantic_facts: dict[str, str] = field(default_factory=dict)
    episodes: list[dict] = field(default_factory=list)
    procedures: list[str] = field(default_factory=list)

    def upsert_fact(self, key: str, value: str) -> None:
        self.semantic_facts[key] = value  # overwrite stale preference cleanly

    def log_episode(self, task: str, outcome: str) -> None:
        self.episodes.append({"task": task, "outcome": outcome})

    def retrieve_context(self, query: str) -> dict:
        hits = [e for e in self.episodes if any(w in e["task"].lower() for w in query.lower().split())]
        return {"facts": self.semantic_facts, "relevant_episodes": hits[-2:], "rules": self.procedures}

mem = AgentMemoryStore(procedures=["Always run pytest before committing."])
mem.upsert_fact("preferred_db", "PostgreSQL")
mem.log_episode("Deploy Cloud Run service", "Succeeded after setting --region=us-central1")
print(mem.retrieve_context("deploy service"))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Building an append-only memory vector DB with no UPDATE / DELETE conflict reconciliation.
Best Practice: Always reconcile candidate facts against existing similar memories before committing!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1Which memory tier stores durable structured user facts and preferences like 'User prefers TypeScript and lives in Tokyo'?

Apply What You Learned — Solve Matching Coding Problems