Episodic memory: remembering past events and their outcomes

Episodic memory stores past events as situation, action, and outcome, then retrieves similar ones for new tasks. Use it when an agent meets recurring situations and earlier results can guide the next attempt.

Episodic memory in 60 seconds

  • What: a store of past events, each saved as situation, action, and outcome, that the agent can search later.
  • Why: the model has no recall of earlier runs. Without records, it repeats the same mistakes and rediscovers the same fixes.
  • How: write an episode when a task ends, retrieve the most similar episodes at the start of the next one, and add them to the prompt.
  • Best for: support, operations, and coding agents that meet recurring situations and where past outcomes are a useful guide.
  • Watch for: noisy or wrong episodes, stale lessons, private data kept too long, and a store that grows without limits.

Where this type fits

Episodic memory belongs to the long-term family of agent memory, next to semantic memory (facts) and procedural memory (how to do things). Where semantic memory says "this customer prefers email", episodic memory says "last time this customer wrote in about a late parcel, we offered a refund and they accepted". The Types of memory hub shows how the three fit together, and the CoALA framework (Sumers et al., 2023) uses the same split between working, episodic, semantic, and procedural memory.

The problem it solves

A language model (LLM) starts every call with a blank slate. Whatever it learned on Monday while fixing a stubborn deployment error is gone on Tuesday, unless something puts it back into the prompt. An agent that runs many tasks therefore behaves like a new employee on every shift. It tries the approach that failed yesterday. It asks the question the customer already answered last week. It spends tokens, and the user's patience, on work that was already done.

The usual first fix is to keep the whole chat history. That does not scale. Histories grow past the context window, cost money on every call, and bury useful moments among small talk. Session memory also ends when the session ends, so it cannot help with a different task tomorrow.

Episodic memory fixes this by keeping a compact record of each meaningful event and retrieving only the few that match the current situation. The agent then has something close to experience. It can say "the last two times this error appeared, restarting the worker did not help, but clearing the lock did". The benefit is largest where tasks repeat with variation, and where the outcome of an earlier attempt is informative.

How it works

  • Capture: when a task ends, or at a natural milestone, the agent writes one episode. It holds the situation (what was asked, in what context), the action taken, and the outcome (success, failure, cost).
  • Summarise: a model call turns the raw trace into a short, plain description. Raw traces are long and noisy, and short episodes embed and retrieve better.
  • Store: the episode is saved with an embedding, a timestamp, an importance score, a user or tenant id, and a time-to-live (TTL).
  • Retrieve: at the start of a new task, the agent embeds the current situation and fetches the most similar episodes. A score combining similarity, recency, and importance picks the final few.
  • Use: the selected episodes go into the prompt under a clear label, with the instruction to repeat what worked and avoid what failed.
  • Maintain: old, low-value, or contradicted episodes are merged, expired, or deleted on a schedule.
Episodes are written when a task ends and read when a similar situation appears.

The top row is the write path. It runs once per task, off the critical path where possible, so the user does not wait for it. The bottom row is the read path, and it runs at the start of each new task, so it must be fast. Both rows meet at the episode store, which is usually a vector index with metadata filters.

The Generative Agents paper (Park et al., 2023) describes a "memory stream" of experiences. It retrieves memories by recency, importance, and relevance, and it forms higher-level reflections from them. The same three signals are a good default for any episodic store. Relevance finds the right topic, recency prefers fresh facts, and importance stops trivial events from crowding out significant ones.

A worked example

Acme Logistics runs a support agent that handles delivery problems. A new ticket arrives: "Parcel 4471 shows delivered, but I never received it. I live in a flat." The agent embeds the situation and searches the episode store, filtered to Acme and to the last 180 days.

Three episodes come back. Episode A (score 0.91): a parcel marked delivered to a flat, and the agent offered an immediate refund. The customer was unhappy and wrote back twice. Episode B (score 0.88): the same pattern, and the agent asked the customer to check with neighbours and the building concierge first, then opened a carrier trace. Resolved in one reply. Episode C (score 0.64): a late parcel, unrelated. The agent keeps A and B and drops C because it falls under the 0.7 similarity threshold.

The prompt now includes: "Past similar cases. Case B resolved quickly by asking about neighbours and concierge first, then opening a carrier trace. Case A failed because an immediate refund did not address the customer's concern. Prefer the approach in case B." The agent follows B. The customer replies that the concierge had it. The agent closes the ticket and writes a new episode.

The episode written after the ticket closes (illustrative) (json)
{
  "id": "ep-20261124-0093",
  "tenant": "acme",
  "situation": "Parcel marked delivered, customer in a flat says not received",
  "action": "Asked about neighbours and concierge, opened carrier trace",
  "outcome": "success",
  "steps": 4,
  "cost_gbp": 0.02,
  "importance": 0.6,
  "created_at": "2026-11-24T10:12:00Z",
  "expires_at": "2027-05-23T10:12:00Z"
}

Building it

The sketch below records, scores, and retrieves episodes. Every external call is a placeholder. The limits are the important part: a similarity floor, a cap on retrieved episodes, and a TTL so the store cannot grow or go stale without bound.

Recording and recalling episodes with limits (illustrative) (python)
import time, math

# Placeholders: llm.generate(), embed(), and store (a vector index with filters).
MAX_EPISODES_IN_PROMPT = 3     # more than this crowds out the task itself
MIN_SIMILARITY = 0.70          # below this, an episode is more noise than help
TTL_SECONDS = 180 * 24 * 3600  # episodes expire; old lessons go stale
HALF_LIFE_DAYS = 30            # recency weight halves every 30 days

def record_episode(tenant, trace, outcome, cost):
    # Summarise first: short episodes embed and retrieve better than raw traces.
    summary = llm.generate(
        "In 2 sentences, give the situation and the action taken:\n" + trace)
    importance = score_importance(outcome, cost)   # 0..1, see below
    store.put({
        "tenant": tenant,                          # isolate tenants at the store
        "text": summary,
        "vector": embed(summary),
        "outcome": outcome,
        "importance": importance,
        "created_at": time.time(),
        "expires_at": time.time() + TTL_SECONDS,
    })

def score_importance(outcome, cost):
    # Failures and expensive runs teach more than easy successes.
    base = 0.8 if outcome == "failure" else 0.4
    return min(1.0, base + min(cost, 1.0) * 0.2)

def recall(tenant, situation):
    q = embed(situation)
    # Filter in the store so one tenant never sees another's episodes.
    hits = store.search(vector=q, filter={"tenant": tenant}, top_k=20)
    now, scored = time.time(), []
    for h in hits:
        if h["similarity"] < MIN_SIMILARITY or h["expires_at"] < now:
            continue
        age_days = (now - h["created_at"]) / 86400
        recency = math.pow(0.5, age_days / HALF_LIFE_DAYS)
        score = 0.6 * h["similarity"] + 0.2 * recency + 0.2 * h["importance"]
        scored.append((score, h))
    scored.sort(key=lambda x: x[0], reverse=True)
    return [h for _, h in scored[:MAX_EPISODES_IN_PROMPT]]

def build_prompt(task, episodes):
    lines = ["Past similar cases (may be outdated; use judgement):"]
    lines += ["- " + e["text"] + " Outcome: " + e["outcome"] for e in episodes]
    return "\n".join(lines) + "\n\nTask: " + task
Expiry and deletion (illustrative) (python)
def forget_expired():
    # Run on a schedule, for example nightly. Deleting is part of the design.
    store.delete(filter={"expires_at": {"lt": time.time()}})

def forget_user(tenant, user_id):
    # Honour deletion requests: episodes may contain personal details.
    store.delete(filter={"tenant": tenant, "user_id": user_id})

Design decisions

  • What counts as an episode: one task or one meaningful milestone, not every message. Default: one episode per finished task, plus one when an agent hits a failure it recovers from.
  • Storage: a vector index with metadata filters (tenant, user, outcome, date). Default: keep the text, the vector, and the structured fields together so you can filter before you rank.
  • Write path latency: summarising costs a model call. Default: write asynchronously after the task ends, so the user never waits for it.
  • Retrieval scoring: combine similarity, recency, and importance, as the Generative Agents work does. Default: weight similarity highest and tune the others against your own tasks.
  • Access control: episodes mix user data with agent behaviour. Default: scope every episode by tenant and, where needed, by user, and enforce the filter in the store, not in the prompt.
  • Retention and deletion: keep episodes for a fixed period with a TTL, and support deletion by user. Default: 90 to 180 days unless the domain needs longer.
  • Failure handling: if the store is down, run the task without episodes. Default: treat memory as an aid, never a hard dependency.

Measuring it

  • Retrieval hit rate: the share of tasks where at least one retrieved episode was judged useful by a reviewer. Compute it on a labelled sample of 100 tasks.
  • Lift on repeat tasks: compare success rate with and without episodes on tasks that resemble earlier ones. This is the number that proves the memory is worth its cost.
  • Harm rate: the share of tasks where an episode led the agent astray. Read these cases by hand, because they reveal wrong or stale episodes.
  • Steps and cost per task: average tool calls and tokens, before and after. Good episodes should shorten runs.
  • Store health: episode count, share expired, and retrieval latency at the 95th percentile.
Measuring lift from episodic memory (illustrative) (python)
def lift(tasks, run_agent):
    # run_agent(task, use_memory) returns True when the task succeeded.
    with_mem = sum(run_agent(t, True) for t in tasks) / len(tasks)
    without = sum(run_agent(t, False) for t in tasks) / len(tasks)
    return with_mem - without   # positive means memory helps on this task set

When to use it, and when not to

SituationUse this type?Why
Support agent that sees the same problem types dailyYesPast resolutions guide the next case and shorten handling time.
Coding or operations agent that meets recurring errorsYesA past failure and its fix is exactly the kind of event worth recalling.
Long tasks where a failed attempt should inform the retryYesEpisodes carry lessons across attempts without changing model weights.
Every task is unique and outcomes rarely repeatNoSimilar episodes will not exist, so retrieval returns noise.
You only need user preferences or stable factsNoSemantic memory is simpler and cheaper for facts.
Strict rules on keeping personal dataOnly with careEpisodes can hold personal details, so you need scoping, expiry, and deletion.

Trade-offs

DimensionEffectWhat to do about it
QualityBetter on repeat situations, worse if episodes are wrong or staleStore outcomes, expire old items, and label episodes as hints in the prompt.
LatencyOne extra search at task start, typically smallIndex with filters, keep top_k small, and cache frequent situations.
CostA summarising call per episode and extra prompt tokensSummarise briefly, write only meaningful episodes, and cap episodes per prompt.
ComplexityA new store, a write path, and maintenance jobsStart with one tenant-scoped index and a nightly clean-up job.
Failure modesCopying a bad past action, leaking data across usersFilter in the store, record failures as well as successes, and review samples.

Semantic memory keeps stable facts, such as a delivery address, while episodic memory keeps events with outcomes. Use both: facts tell the agent who it is helping, and episodes tell it what happened before. Procedural memory goes one step further. It turns repeated lessons into reusable instructions, so episodes that keep recurring are good candidates to be promoted into a skill.

A reflexive agent critiques its output within one task, while episodic memory carries lessons across tasks. The Reflexion paper (Shinn et al., 2023) shows the link: written reflections stored in memory improve later attempts without retraining.

What this means for your role

Common mistakes

Further reading

Episodic memory gives an agent experience, but only if the records are short, scoped, and kept fresh. Start small, measure the lift, and let the store earn its place.

Search topics

↑↓ to move · Enter to open · Esc to close