Episodic and Semantic Memory for Agents

Episodic memory stores specific past experiences as retrievable events (the "what, where, when" of an agent's history), while semantic memory encodes general facts and conceptual knowledge distilled from many experiences — together they give AI agents the ability to learn from interaction history and generalize across contexts. This distinction, borrowed from cognitive neuroscience, is now foundational to building long-horizon agents that can personalize behavior, avoid repeating mistakes, and accumulate knowledge over extended deployments. The counterintuitive fact: most LLM-based agents today have neither — their apparent "memory" is simply a long context window, which is stateless between sessions and fundamentally different from the structured, queryable memory stores that make biological and modern agentic systems genuinely adaptive.

The core insight

An agent without persistent memory is a goldfish — brilliant within one conversation, amnesiac the next. The key insight is that episodic memory lets an agent ask "have I seen something like this before?" by retrieving concrete past events, while semantic memory lets it ask "what do I generally know about this domain?" by consulting distilled world-knowledge. When both are wired into a retrieval-augmented loop, the agent can simultaneously leverage specific precedents and general principles — which is precisely what expert human problem-solvers do. The "aha moment" is realizing that memory is not just storage: it is a structured retrieval mechanism that shapes what context the agent reasons over at every step.

How It Works

Memory Taxonomy for Agents

An agent's memory system can be decomposed into four stores, two of which map directly onto the cognitive distinction:

StoreCognitive AnalogRepresentationAccess Pattern
EpisodicEpisodic memoryEvent tuples + embeddingsSimilarity / recency retrieval
SemanticSemantic memoryKnowledge graph / vector DBStructured query or embedding search
ProceduralProcedural memoryTool definitions, few-shot chainsExact lookup by task type
WorkingWorking memoryLLM context windowSequential, token-limited

Episodic Memory: Storage and Retrieval

Each experience is stored as a tuple:

1
et=(st, at, rt, ot, τt)\quad e_t = (s_t,\, a_t,\, r_t,\, o_t,\, \tau_t)

Explanation: An episodic trace at time tt bundles the observation sts_t, action ata_t, reward or outcome rtr_t, any additional metadata oto_t (e.g., task ID, user ID), and a timestamp τt\tau_t — the minimal record of "what happened."

  • sts_t: observation or environment state at step tt
  • ata_t: action taken by the agent
  • rtr_t: scalar reward or structured outcome signal
  • oto_t: auxiliary metadata (session ID, user context, tool results)
  • τt\tau_t: wall-clock or logical timestamp

Retrieval is performed by encoding the current query qq and scoring stored episodes:

2
score(et,q)=λ1cos⁡ ⁣(ϕ(et), ϕ(q))+λ2⋅recency(τt)+λ3⋅importance(et)\quad \text{score}(e_t, q) = \lambda_1 \cos\!\bigl(\phi(e_t),\, \phi(q)\bigr) + \lambda_2 \cdot \text{recency}(\tau_t) + \lambda_3 \cdot \text{importance}(e_t)

Explanation: The relevance of a stored episode is a weighted combination of semantic similarity to the current query, how recently it occurred, and an importance score (e.g., high-reward events or user-flagged memories) — mirroring how humans preferentially recall vivid or recent events.

  • ϕ(⋅)\phi(\cdot): embedding function (e.g., `text-embedding-ada-002` or a local bi-encoder)
  • cos⁡(⋅,⋅)\cos(\cdot,\cdot): cosine similarity in embedding space
  • recency(τt)=exp⁡(−α(T−τt))\text{recency}(\tau_t) = \exp(-\alpha (T - \tau_t)): exponential decay with rate α\alpha
  • importance(et)\text{importance}(e_t): scalar assigned at write time (could be ∣rt∣|r_t| or an LLM-judged salience score)
  • λ1,λ2,λ3\lambda_1, \lambda_2, \lambda_3: mixing weights, tunable per application

Semantic Memory: Distillation from Episodes

Semantic memory is built by periodically consolidating episodic traces into general statements. Formally, given a corpus of episodes E={e1,…,eN}\mathcal{E} = \{e_1, \ldots, e_N\}, a consolidation function C\mathcal{C} produces semantic entries:

3
S=C(E)={fθ(ei,…,ej)  ∣  (i,…,j)∈Clusters(E)}\quad \mathcal{S} = \mathcal{C}(\mathcal{E}) = \bigl\{ f_\theta(e_i,\ldots,e_j) \;\big|\; (i,\ldots,j) \in \text{Clusters}(\mathcal{E}) \bigr\}

Explanation: Semantic entries are generated by clustering related episodes and running a summarization or extraction function fθf_\theta (typically an LLM call) over each cluster — distilling many specific events into a single general belief, fact, or preference. In practice, Clusters(E)\text{Clusters}(\mathcal{E}) is computed with k-means or HDBSCAN over episode embeddings {ϕ(ei)}\{\phi(e_i)\}, and fθf_\theta is an LLM prompted to extract durable facts (e.g., "User prefers concise answers," "Database schema uses snake_case").

Working Memory Integration

At inference time, the agent assembles its context window by retrieving from both stores:

4
Wt=TopKepisodic(qt, k1)∪TopKsemantic(qt, k2)∪ProcedureMatch(qt)\quad \mathcal{W}_t = \text{TopK}_{\text{episodic}}(q_t,\, k_1) \cup \text{TopK}_{\text{semantic}}(q_t,\, k_2) \cup \text{ProcedureMatch}(q_t)

Explanation: The working context is populated by the top-k1k_1 most relevant episodes, top-k2k_2 most relevant semantic facts, and any matching procedural templates — injecting only the most pertinent long-term memory into the finite context window rather than everything. This selective injection keeps prompt length tractable while giving the LLM backbone access to relevant history and world-knowledge.

PyTorch / LangChain Implementation Sketch

```python import numpy as np from dataclasses import dataclass, field from typing import List, Optional import torch import torch.nn.functional as F @dataclass class Episode: observation: str action: str outcome: str embedding: Optional[torch.Tensor] = None timestamp: float = 0.0 importance: float = 1.0 class EpisodicMemoryStore: def __init__(self, embed_fn, alpha: float = 0.01, lambdas: tuple = (0.6, 0.2, 0.2)): self.episodes: List[Episode] = [] self.embed_fn = embed_fn # callable: str -> torch.Tensor self.alpha = alpha # recency decay rate self.lam = lambdas # (similarity, recency, importance) self.T = 0.0 # logical clock def write(self, obs: str, action: str, outcome: str, importance: float = 1.0): self.T += 1.0 emb = self.embed_fn(f"{obs} {action} {outcome}") ep = Episode(obs, action, outcome, emb, self.T, importance) self.episodes.append(ep) def retrieve(self, query: str, top_k: int = 5) -> List[Episode]: if not self.episodes: return [] q_emb = self.embed_fn(query) # [D] stack = torch.stack([e.embedding for e in self.episodes]) # [N, D]

# Cosine similarity sim = F.cosine_similarity(stack, q_emb.unsqueeze(0)) # [N]

# Recency score timestamps = torch.tensor([e.timestamp for e in self.episodes]) recency = torch.exp(-self.alpha * (self.T - timestamps))

# Importance importance = torch.tensor([e.importance for e in self.episodes]) scores = (self.lam[0] sim + self.lam[1] recency + self.lam[2] * importance / importance.max()) top_idx = scores.topk(min(top_k, len(self.episodes))).indices return [self.episodes[i] for i in top_idx]

class SemanticMemoryStore: """Stores distilled facts as (text, embedding) pairs.""" def __init__(self, embed_fn): self.facts: List[str] = [] self.embeddings: List[torch.Tensor] = [] self.embed_fn = embed_fn def add_fact(self, fact: str): self.facts.append(fact) self.embeddings.append(self.embed_fn(fact)) def retrieve(self, query: str, top_k: int = 3) -> List[str]: if not self.facts: return [] q_emb = self.embed_fn(query) stack = torch.stack(self.embeddings) sim = F.cosine_similarity(stack, q_emb.unsqueeze(0)) top_idx = sim.topk(min(top_k, len(self.facts))).indices return [self.facts[i] for i in top_idx] ```

researcher · Endel Tulving | b. 1927 – 2023 | Episodic vs. Semantic Memory Distinction

Tulving was an Estonian-Canadian cognitive psychologist at the University of Toronto whose 1972 paper "Episodic and Semantic Memory" first formally separated these two memory systems — a distinction so influential it shaped both cognitive neuroscience and, decades later, AI agent architecture. His specific contribution was the operational claim that episodic memory is autonoetic (self-referential, time-stamped) while semantic memory is noetic (context-free, general) — exactly the distinction modern agent systems encode as "event stores" versus "knowledge bases." Surprising fact: Tulving famously self-experimented, injecting himself with a radioactive tracer to participate in PET scanning studies of his own memory systems at age 67.

researcher · John Hopfield | b. 1933 | Associative Memory Networks

Hopfield, a physicist at Princeton and Caltech (and 2024 Nobel laureate in Physics), introduced Hopfield Networks in 1982 as a mathematical model of associative memory — storing patterns as energy minima and retrieving them via gradient descent on an energy landscape. His contribution to this topic is foundational: modern dense retrieval and attention mechanisms are direct descendants of Hopfield's energy-based retrieval, with the 2020 "Modern Hopfield Networks" paper showing that the softmax attention update rule is a Hopfield retrieval step. Surprising fact: Hopfield trained as a physicist studying solid-state matter and came to neural networks by accident while consulting for Bell Labs on a completely unrelated problem.

Figure
Agent Memory Architecture
Agent Memory System Architecture Working Memory (LLM Context Window) volatile · token-limited · fast LLM Backbone generates action / response Episodic Memory event tuples + embeddings time-stamped · specific "What happened when?" Semantic Memory distilled facts · knowledge context-free · general "What is generally true?" Procedural Memory tool specs · chains · skills action-oriented "How do I do X?" retrieve retrieve write consolidation / distillation
Figure
Episodic Retrieval Scoring
Episodic Retrieval Score Decomposition Query q_t φ(q_t) → embedding λ₁ · Similarity cos(φ(eₜ), φ(q)) semantic match λ₂ · Recency exp(-α(T - τₜ)) time decay λ₃ · Importance |rₜ| or LLM-judged salience weight score(eₜ, q) → TopK

Intuition

The Mental Model

Imagine a seasoned doctor seeing a new patient. They draw on two completely different types of knowledge simultaneously: specific past cases ("I had a patient three years ago with these exact symptoms who turned out to have X — let me retrieve that case") and general medical knowledge ("beta-blockers contraindicate asthma — this is a stable fact I learned from textbooks and a thousand cases"). The first is episodic; the second is semantic. A junior doctor with the same textbook knowledge but no case history is weaker precisely because they lack episodic memory. Now imagine the doctor has amnesia and forgets every patient after the session ends — that is what an LLM agent with only context window "memory" is like. The power of combining both systems is that specific episodes provide grounding and precedent while semantic memory provides generalizable principles — together they produce judgment, not just recall.

Historical Development

Origins · 1 minhow this was discovered
History
1972
Endel Tulving formally distinguishes episodic from semantic memory in "Episodic and Semantic Memory" (in Donaldson & Tulving, eds.), establishing the cognitive science foundation the AI field would later import.
1982
John Hopfield introduces Hopfield Networks as energy-based associative memory, providing the first mathematical treatment of content-addressable memory storage and retrieval in neural systems.
1986
McClelland & Rumelhart's PDP models explore complementary learning systems — fast episodic encoding vs. slow semantic consolidation — anticipating the complementary learning systems (CLS) theory.
1995
Complementary Learning Systems (CLS) theory (McClelland, McNaughton, O'Reilly) proposes the hippocampus stores episodes while neocortex consolidates semantic knowledge during sleep — directly inspiring modern agent memory consolidation pipelines.
2017
The Transformer architecture (Vaswani et al., Attention Is All You Need) provides the scalable self-attention mechanism that makes dense retrieval from large memory stores computationally tractable.
2020
Ramsauer et al. show in "Hopfield Networks is All You Need" that modern Hopfield Networks with softmax energy functions are mathematically equivalent to transformer attention — unifying associative memory theory with the dominant AI architecture.
2022
The MemGPT precursor work and early ReAct (Yao et al.) frameworks demonstrate LLM agents that can invoke external memory tools, treating memory as a callable API rather than implicit context.
2023
Park et al. publish "Generative Agents" (Stanford), demonstrating 25 LLM-backed agents with episodic memory streams, reflection synthesis (a form of consolidation), and emergent social behavior — the first large-scale demo of dual-store memory in deployed agents.
2024
Mem0, Zep, and production agent frameworks (LangGraph, AutoGen) ship persistent episodic + semantic memory layers as first-class primitives, standardizing the practice across industry deployments.

Why It Matters

Real-World Impact
Generative Agents (Stanford, 2023)Each of 25 simulated social agents maintains an episodic memory stream of all observations, a periodic reflection step that distills semantic generalizations from recent episodes, and a retrieval score matching equation [2] above — enabling emergent behaviors like planning a party and remembering past social interactions across 2-day simulations.
MemGPT / UM-MemoryTreats the LLM context window as RAM and external vector stores as disk, implementing explicit `memory_store` and `memory_retrieve` tool calls so the agent can manage what stays in context across arbitrarily long sessions — directly addressing the context-window-as-memory fallacy.
ChatGPT Memory (OpenAI, 2024)Implements a user-level semantic memory layer that distills facts from conversations ("user prefers bullet points," "user's daughter is named Emma") and injects them into future system prompts — a commercial semantic memory store operating at scale across hundreds of millions of users.
GitHub Copilot WorkspaceMaintains a semantic memory of repository-level conventions, architectural patterns, and past code review decisions, retrieved at PR-generation time to ensure consistency with project norms — semantic memory serving as a long-term style guide.
Customer Service Agents (Sierra, Intercom Fin)Combine episodic memory (full ticket history per customer) with semantic memory (product knowledge base) to enable agents that recall past interactions ("you called about this three months ago") while also drawing on accurate product facts — directly reducing repeat contacts and escalations.
Voyager (Wang et al., 2023)A Minecraft agent that stores procedural and episodic memory of acquired skills (e.g., "crafting a diamond pickaxe takes these steps") in a skill library, enabling progressive competence accumulation that purely context-based agents cannot achieve — demonstrating lifelong learning via externalized memory.
AutoGen Multi-Agent SystemsIn multi-agent AutoGen deployments, shared semantic memory stores allow specialist agents (coder, critic, planner) to maintain a common knowledge base updated by each agent's contributions, enabling emergent team coordination without a central controller.

Prerequisites

What This Leads To

Before this