Sub topic 7
Episodic, semantic, and procedural memories
This chapter assumes you have read the earlier chapters on long-term memory and know the MemoryStore pattern: each memory is saved with an embedding, an owner, and a kind. Here you will learn what the three common values of kind mean, how each is written and read, and what goes wrong when they are mixed together.
Why split long-term memory by type
A long-term store holds text. Without structure, "Priya prefers Python", "the Friday deploy failed" and "always run tests before deploying" all sit in one pile. They differ in three ways:
- How they are created. Some come from a single sentence the user says. Others come from summarizing a whole task.
- How they age. A user's name stays valid for years. A record of a failed deploy is true forever as history, but it may stop being relevant.
- How the agent should use them. A fact is background knowledge. A past event is evidence. A rule is an instruction.
The taxonomy comes from cognitive psychology. Agent frameworks borrow it because it maps well onto engineering decisions about writing, retrieving, and expiring memories.
The three types
Semantic memory holds facts and preferences, detached from when you learned them. Examples: "The user's name is Priya." "The team deploys to staging first." These are short, declarative, and usually about the user or the world.
Episodic memory holds specific past events: what happened, when, and with what outcome. Example: "On 2026-11-20 the staging deploy failed because a migration was missing, and a rollback fixed it." Episodes carry a timestamp and often a result. They let an agent recall "last time we tried this".
Procedural memory holds how to do things: rules, workflows, and learned habits. Example: "Always run the test suite before deploying to staging." In agents, procedural memory is most often stored as text that is injected into the system prompt, such as instructions the agent has learned or been given. It can also be tool-use recipes or few-shot examples. It is not stored in the model's weights.
| Type | Holds | Typical write trigger | Typical read trigger | Ages how |
|---|---|---|---|---|
| Semantic | Facts, preferences | User states something stable | Query is about the user or topic | Gets replaced when the fact changes |
| Episodic | Events with time and outcome | End of a task or session | Similar situation comes up | Loses relevance, is summarized or expired |
| Procedural | Rules, workflows | User correction, or reflection on a failure | Start of a task, or matching task type | Gets revised as the process changes |
One event, three memories
Suppose a user says: "The Friday deploy to staging failed because I forgot to run the tests. From now on, always run tests first. Also, I prefer Python."
A careful writer extracts three separate items from this single message:
- Semantic: "The user prefers Python."
- Episodic: "The Friday deploy to staging failed because tests were not run."
- Procedural: "Always run tests before deploying to staging."
Storing the raw message instead is a common mistake. It makes retrieval noisy, because a query about Python also pulls in deploy details. It also makes updating hard. When the user later switches language, you cannot replace one fact if it is fused into a long paragraph.
Adding `kind` to the store
The store from the previous chapter already saves a kind. Two changes make it useful: validate the value on write, and let search filter by it. The example below is complete. It uses a toy word-count embedding over a small vocabulary so that it runs without any API.
import math
import time
KINDS = ("semantic", "episodic", "procedural")
VOCAB = ["deploy", "friday", "staging", "python", "tests",
"failed", "rollback", "priya", "prefers", "always"]
def embed(text):
"""Toy embedding: counts of known words. Replace with a real model."""
words = text.lower().replace(".", "").split()
return [float(words.count(w)) for w in VOCAB]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
class MemoryStore:
def __init__(self, embed):
self.embed = embed
self.items = []
def write(self, user_id, text, kind="semantic"):
if kind not in KINDS:
raise ValueError("unknown kind: " + kind)
self.items.append({
"user_id": user_id,
"text": text,
"kind": kind,
"vec": self.embed(text),
"created": time.time(),
})
def search(self, user_id, query, k=3, kind=None):
q = self.embed(query)
pool = [m for m in self.items
if m["user_id"] == user_id and (kind is None or m["kind"] == kind)]
pool.sort(key=lambda m: cosine(q, m["vec"]), reverse=True)
return pool[:k]
def render_memories(memories):
"""Group memories by kind so the model can tell facts, events, and rules apart."""
sections = {
"semantic": "Facts",
"episodic": "Past events",
"procedural": "Rules to follow",
}
lines = []
for kind, title in sections.items():
texts = [m["text"] for m in memories if m["kind"] == kind]
if texts:
lines.append(title + ":")
lines += ["- " + t for t in texts]
return "\n".join(lines)
store = MemoryStore(embed)
store.write("u1", "Priya prefers python with tests.", kind="semantic")
store.write("u1", "Friday deploy to staging failed and needed a rollback.", kind="episodic")
store.write("u1", "Always run tests before deploy to staging.", kind="procedural")
found = store.search("u1", "deploy to staging on friday", k=2)
print(render_memories(found))Running it prints:
Past events:
- Friday deploy to staging failed and needed a rollback.
Rules to follow:
- Always run tests before deploy to staging.The semantic memory scores zero against this query, so k=2 leaves it out. The grouped output shows the main benefit of keeping the label: the prompt can present a fact, an event, and a rule differently.
Reading each type differently
Treating all three the same on read is the second common mistake. Practical rules:
- Procedural memories are often loaded unconditionally or by task type. A rule like "never delete files without asking" must not depend on a similarity score that happens to be high enough. Filter with
kind="procedural"and load the whole small set, or match on task type. - Semantic memories are retrieved by topic similarity. Because they are short and stable, a low
k(2 to 5) usually suffices. - Episodic memories need recency and outcome. Similarity alone returns the most similar old event, which may be stale. Combine the similarity score with the age of the memory, and show the date in the prompt so the model can weigh it.
def episodic_score(similarity, created, now, half_life_days=30.0):
"""Blend similarity with a recency factor that halves every half_life_days."""
age_days = (now - created) / 86400
recency = 0.5 ** (age_days / half_life_days)
return similarity * (0.5 + 0.5 * recency)The 0.5 + 0.5 * recency term means an old episode loses at most half its score. A strongly relevant old event can still win over a weakly relevant recent one. Tune the half-life to how fast your domain changes.
Edge cases
- Ambiguous classification. "I always deploy on Fridays" can be a fact about habit or a rule. Pick by how you will use it. If the agent should act on it, store it as procedural. If it only describes the user, store it as semantic.
- Episodes that become facts. After five failed Friday deploys, the pattern "Friday deploys are risky" is more useful than five events. Periodically consolidate repeated episodes into one semantic or procedural memory, and expire the originals. The maintenance chapter covers this in more detail.
- Contradictions across types. A procedural rule ("deploy on Fridays") can conflict with a newer episode ("Friday deploys failed"). Store timestamps and let the prompt show them. Do not silently overwrite.
- Wrong label at write time. If an LLM classifies memories, it will sometimes err. Validate against the allowed
KINDS(aswritedoes), and log the labels so you can audit them. - Cross-user leakage. Filtering by
kinddoes not replace filtering byuser_id. Both filters apply insearch.
Exercise
A user says: "Yesterday my report script crashed on a missing column. Please always check the column names first. By the way, I work in the finance team." Write one memory for each of the three kinds, and say which one should be loaded into every session regardless of the query.
Show answer
Semantic: "The user works in the finance team." Episodic: "Yesterday the user's report script crashed because of a missing column." Procedural: "Check column names before running report scripts." The procedural memory should be loaded regardless of the query (or whenever the task type matches), because a rule that depends on a similarity score may be skipped when the query wording differs.
Exercise
Your agent retrieves the top 3 episodic memories by similarity alone, and it keeps citing an outdated failure from eight months ago, even though the problem was fixed. Name two changes that reduce this, and say what each changes.
Show answer
First, add a recency factor to the score (for example, a half-life decay as in episodic_score) so old events rank lower unless they are strongly relevant. Second, show each episode's date in the prompt, or consolidate and expire old episodes, so the model can see it is old or the stale event is no longer retrieved. The first changes ranking, and the second changes what the model sees or what is stored.