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.
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).
Without persistent memory, an agent forgets your preferences, tech stack, and past mistakes every time you open a new chat.
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!
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!
Combining semantic cosine similarity with exponential recency decay (exp(-λ · Δt)) ensures recent project context outranks 6-month-old memories.
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?'
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?
- 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
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)
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).
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
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)!
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!
Long-Term Memory Write Consolidator
3. Composite Retrieval Scoring & Privacy Scoping
Pure cosine similarity retrieves 1-year-old trivial comments over yesterday's urgent preference — composite scoring fixes that!
Non-Negotiable Production Privacy Rules
- Strict Tenant/User Partitioning: Every vector query MUST filter by
WHERE user_id = auth_user_idat 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!
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.
.
In Mem0-style memory consolidation, what operation should fire when the user sends pure chit-chat like 'Okay, thanks!'?
Why should Long-Term Memory extraction run asynchronously after replying rather than blocking before the LLM responds?
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)!
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.
Personalized Coding, Coaching & Enterprise Assistants
Remembers user tech stack, coding conventions, past incident fixes, and preferences across months.
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"))
UPDATE / DELETE conflict reconciliation.'User prefers TypeScript and lives in Tokyo'?