AI Agents with Memory: Short-Term, Long-Term and Episodic

Building AI Agents with Memory: Short-Term, Long-Term, and Episodic Memory Patterns

A language model forgets everything between API calls. That statelessness is fine for a one-shot chatbot, but it breaks the moment you build an agent that plans over hours, calls tools, and picks up where it left off yesterday. The industry answer is to give agents memory — and builders have converged on three patterns borrowed from cognitive psychology: short-term working memory, long-term semantic memory, and episodic memory. Each one fixes a different failure mode. This guide explains what each pattern stores, how to implement it, and where it breaks down, with code you can adapt.

What “Memory” Means for a Stateless Model

A model only sees what is in its prompt. So agent memory is really three mechanisms for getting the right information into the prompt at the right time:

  • Short-term memory: what is sitting in the current context window right now — recent messages, tool outputs, the active plan.
  • Long-term memory: durable knowledge stored outside the model and retrieved when relevant — user facts, documentation, learned preferences.
  • Episodic memory: a record of what happened in past sessions — dated events the agent can recall and learn from.

Think of the context window as RAM and the stores as disk. The engineering problem is the same as in any computer: decide what goes where, and when to move things between them.

Short-Term Memory: The Working Context

What lives in short-term memory

Short-term memory holds everything the agent needs for the task at hand: the conversation so far, tool call results, intermediate reasoning, and the current plan. As long as the task fits in the context window, this is the only memory you need. Problems start when it doesn’t.

The classic failure is the long tool loop. Each tool result appends tokens, the oldest context gets pushed out (or you hit the limit outright), and the agent loses track of the original goal. Short-term memory management is about keeping the working set small and relevant.

Compaction: summarizing before the window fills

The standard technique is compaction — when the conversation passes a token threshold, summarize the older portion into a compact state and keep going. Here is a minimal pattern:

MAX_TOKENS = 100_000
RESERVE = 20_000

def maybe_compact(messages):
    if count_tokens(messages) < MAX_TOKENS - RESERVE:
        return messages
    keep = messages[-10:]  # recent turns stay verbatim
    older = messages[:-10]
    summary = llm.summarize(
        "Summarize this agent transcript. Preserve: the user's goal, "
        "decisions made, tool results that are still relevant, and open items.",
        older,
    )
    return [{"role": "system", "content": "Session so far:n" + summary}] + keep

Two details matter. First, summarize at fixed intervals rather than waiting for the limit — you want the summary written while the full detail is still available. Second, tell the summarizer exactly what to preserve; a generic summary drops the decisions and keeps the chatter. What survives compaction is what the agent can still act on.

Long-Term Memory: Durable Knowledge Across Sessions

Vector-store semantic memory

Semantic memory stores facts and knowledge the agent can search by meaning. The pipeline is familiar: chunk documents or notes, embed them, store the vectors, and retrieve the top matches for the current query.

def remember(text, source):
    chunks = split(text, max_tokens=400, overlap=40)
    for c in chunks:
        store.insert(text=c, embedding=embed(c), source=source)

def recall(query, k=5):
    hits = store.search(embedding=embed(query), top_k=k)
    return [h for h in hits if h.score > 0.7]

This works well for documentation, project notes, and accumulated know-how. It works poorly for precise facts that need exact retrieval — “the production database password” should live in a vault, not a vector store. Set a similarity threshold and return nothing rather than returning weak matches; a retrieval miss the agent can see is better than a plausible-sounding wrong answer it cannot.

Structured memory: facts that need a schema

Some memory deserves a table, not a vector. User preferences, account identifiers, project configuration — stable facts with known keys. A simple key-value or relational store beats embeddings here because retrieval is exact.

The practical rule: write facts explicitly, retrieve them exactly, and search the rest semantically. When the agent learns something stable (“the user deploys with Docker Compose on a single VPS”), write it to the fact store with a timestamp. When it needs background (“how did we handle the last migration?”), search the vector store. Mixing the two — embedding facts you later need verbatim — is how agents confidently misremember.

Episodic Memory: Remembering What Happened

Episodes are not facts

Facts are timeless: “the user prefers Postgres.” Episodes are dated: “on Tuesday the deploy failed because a migration lock was held by a stale worker, and the fix was to kill the worker before retrying.” Episodic memory is what lets an agent say “we have seen this before” instead of debugging the same failure twice.

Recording and retrieving episodes

Record an episode when something worth remembering happens: a failure and its resolution, a decision and its rationale, an unusual outcome. Each episode gets a timestamp, a short summary, and the details.

def record_episode(summary, detail, outcome):
    episodes.append({
        "timestamp": now(),
        "summary": summary,      # one line, searchable
        "detail": detail,        # full context
        "outcome": outcome,      # "resolved" / "open" / "failed"
    })

def recall_episodes(query, days=30):
    scored = []
    for ep in episodes:
        relevance = similarity(embed(query), embed(ep["summary"]))
        recency = decay(days_since(ep["timestamp"]))  # e.g. exp(-days/14)
        scored.append((0.7 * relevance + 0.3 * recency, ep))
    return [ep for s, ep in sorted(scored, reverse=True)[:3] if s > 0.5]

The recency weighting is a heuristic, not science — a failure from three months ago can matter more than one from yesterday. Weight resolved episodes higher than open ones, and always show the timestamp to the agent so it can judge staleness for itself.

Putting It Together: A Reference Agent Loop

Here is how the three patterns combine in a working agent loop:

def agent_step(user_input):
    short_term = load_conversation()          # working context
    short_term = maybe_compact(short_term)
    facts = fact_store.get_relevant(user_input)      # long-term, exact
    docs = vector_store.recall(user_input)           # long-term, semantic
    past = recall_episodes(user_input)               # episodic
    prompt = assemble(facts, docs, past, short_term, user_input)
    action = llm.decide(prompt)
    result = execute(action)
    write_back(short_term, result)   # update working memory
    maybe_record_episode(result)     # episodic, only if notable
    return result

Write-back discipline is what separates a working memory system from a junk drawer. Rules that hold up in practice: only write what future sessions will plausibly need, deduplicate against existing entries before inserting, and attach a timestamp and source to everything. Memory that cannot be dated or sourced is a liability.

Failure Modes Worth Designing Against

Retrieval misses. The agent asks the wrong question or the store holds the wrong chunk. Mitigation: hybrid search (keyword plus vector), and let the agent see when retrieval returned nothing so it can rephrase instead of hallucinating.

Stale memory contradicting current facts. A preference recorded a year ago may no longer hold. Mitigation: timestamps on every memory, periodic re-confirmation of old facts, and a conflict rule — newer explicit statements override older stored ones.

Memory poisoning. Anything the agent reads from the outside world — web pages, user uploads, tool outputs — can end up in memory. Treat retrieved memory as data, never as instructions. If your agent acts on remembered content, sanitize and scope it the same way you would any untrusted input.

Which Pattern for Which Job

  • Single-session task, fits in context: short-term memory only. Add compaction if tool loops run long.
  • Returning users and stable facts: add a structured fact store. Cheapest win per line of code.
  • Large knowledge base, docs, notes: add vector-store semantic memory with a similarity floor.
  • Recurring operations, debugging, support: add episodic memory so the agent recognizes repeats.

Start with compaction and a fact table — that covers most agents. Add semantic search when the knowledge base outgrows manual curation, and episodes when sessions start repeating themselves. Each layer adds failure modes of its own, so add them in the order the pain actually appears.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.