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.
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:
| Store | Cognitive Analog | Representation | Access Pattern |
|---|---|---|---|
| Episodic | Episodic memory | Event tuples + embeddings | Similarity / recency retrieval |
| Semantic | Semantic memory | Knowledge graph / vector DB | Structured query or embedding search |
| Procedural | Procedural memory | Tool definitions, few-shot chains | Exact lookup by task type |
| Working | Working memory | LLM context window | Sequential, token-limited |
Episodic Memory: Storage and Retrieval
Each experience is stored as a tuple:
Explanation: An episodic trace at time bundles the observation , action , reward or outcome , any additional metadata (e.g., task ID, user ID), and a timestamp — the minimal record of "what happened."
- : observation or environment state at step
- : action taken by the agent
- : scalar reward or structured outcome signal
- : auxiliary metadata (session ID, user context, tool results)
- : wall-clock or logical timestamp
Retrieval is performed by encoding the current query and scoring stored episodes:
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.
- : embedding function (e.g., `text-embedding-ada-002` or a local bi-encoder)
- : cosine similarity in embedding space
- : exponential decay with rate
- : scalar assigned at write time (could be or an LLM-judged salience score)
- : 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 , a consolidation function produces semantic entries:
Explanation: Semantic entries are generated by clustering related episodes and running a summarization or extraction function (typically an LLM call) over each cluster — distilling many specific events into a single general belief, fact, or preference. In practice, is computed with k-means or HDBSCAN over episode embeddings , and 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:
Explanation: The working context is populated by the top- most relevant episodes, top- 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] ```
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.
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.
Intuition
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.