Skip to content

Designing Memory for AI Agents: Short-Term, Long-Term, and Episodic

AI agent memory spans short-term context, long-term facts, and episodic records of past runs. How to design each layer and retrieve it safely.

TechnoKeen Engineering 8 min read Published
On this page

Language models are stateless. Everything an agent “remembers” is something your system chose to store and chose to put back into the context window. Designing agent memory is therefore a data design problem with three layers: short-term memory for the current task, long-term memory for durable facts, and episodic memory for what happened in past runs. Get the write and read rules right for each, and the agent feels consistent. Get them wrong, and it confidently repeats stale or poisoned information.

Key takeaways

  • Memory is not a feature of the model. It is a storage and retrieval system you build, with explicit rules for what gets written, when, and who can read it.
  • Short-term memory is context management: what stays in the window, what gets summarized, and what gets offloaded to tools.
  • Long-term memory should store small, attributed, updatable facts, not raw transcripts.
  • Episodic memory, records of past runs and their outcomes, is the most underused layer and often the most valuable for improving behavior.
  • Every memory write is a security boundary. Scope memory by tenant and user, record provenance, and support deletion from day one.

Why memory is an architecture decision

Consider an account management agent that helps a customer success team. On Monday, a user tells it that a client prefers invoices consolidated quarterly. On Thursday, a different user asks it to draft a renewal proposal for the same client. Whether the agent knows about the invoicing preference depends entirely on decisions your team made:

  • Was the preference written to memory at all, or did it live only in Monday’s conversation?
  • Was it stored as a fact about the client, or as a fact about Monday’s user?
  • Does Thursday’s user have permission to see it?
  • If the preference changed on Wednesday, which version wins?

None of these are model questions. They are schema, access control, and lifecycle questions, so memory belongs in the system’s data architecture, not in a plug-in added at the end.

The three layers

+---------------------------------------------------------------+
|  CONTEXT WINDOW (what the model actually sees this turn)       |
|   system prompt | task | recent turns | retrieved memories    |
+---------------------------------------------------------------+
        ^                    ^                       ^
        |                    |                       |
  SHORT-TERM            LONG-TERM                EPISODIC
  this task's state     durable facts            past runs
  - message buffer      - user/org prefs         - task + outcome
  - scratchpad          - entity facts           - what worked
  - tool results        - policies learned       - what failed
  lifetime: one run     lifetime: until updated  lifetime: retention policy
Layer Holds Written when Read when Typical store
Short-term Current conversation, intermediate results, plan Every step Every step In-process state, checkpoint store
Long-term Stable facts about users, entities, preferences A fact is confirmed or changes Task touches that entity or user Relational DB, key-value store, vector index
Episodic Summaries of past tasks, outcomes, corrections A run finishes or a human corrects it A similar task begins Document store with embeddings and metadata

Procedural memory, the instructions that shape how the agent works, belongs in versioned prompts and tool definitions that change through code review.

Short-term memory: managing the window

Short-term memory is everything the agent needs to complete the current task. For a short conversation, that is just the message history. For a long-running agent that makes dozens of tool calls, the window fills fast, and quality degrades well before it is technically full.

Practical techniques, roughly in order of how often we use them:

  1. Trim tool results at the source. A tool that returns a full API payload when the agent needs three fields wastes context on every call. Shape responses in the tool, not afterward. See Tool Design for AI Agents.
  2. Keep a structured scratchpad. Let the agent maintain a small, explicit state object (current plan, confirmed facts, open questions) rather than relying on it to re-read the whole history.
  3. Compact older turns. When the history passes a threshold, summarize older exchanges into a concise state description and keep only recent turns verbatim. Preserve anything the user explicitly stated as a requirement.
  4. Offload to files or stores. For long tasks, have the agent write intermediate artifacts to a file or database and re-read them by reference when needed.
  5. Checkpoint for durability. Persist short-term state so a run can resume after a crash or a human approval pause. Frameworks like LangGraph provide checkpointing for exactly this purpose.

The broader question of what belongs in the window at each step is the subject of Context Engineering: The Discipline Behind Reliable Agents.

Long-term memory: durable, attributed facts

Long-term memory lets an agent carry knowledge across sessions. The common mistake is to store raw conversation transcripts in a vector database and retrieve by similarity. That works in a demo and degrades in production: transcripts are noisy, contradictory over time, and expensive to retrieve from.

A better unit is the memory record: a small, self-contained statement with metadata.

from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from uuid import uuid4


class Scope(str, Enum):
    USER = "user"          # visible only to this user
    ACCOUNT = "account"    # visible to anyone with access to this customer account
    ORG = "org"            # visible across the tenant


@dataclass
class MemoryRecord:
    tenant_id: str
    scope: Scope
    subject: str                       # e.g. "account:acme-corp" or "user:u_123"
    content: str                       # one fact, stated plainly
    source: str                        # "user_stated" | "tool_observed" | "inferred"
    source_ref: str                    # message ID, tool call ID, or document ID
    confidence: float = 1.0
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    supersedes: str | None = None      # ID of the record this replaces
    expires_at: datetime | None = None
    id: str = field(default_factory=lambda: str(uuid4()))

Each field earns its place:

  • tenant_id and scope make isolation enforceable at query time, not just by convention.
  • subject lets you retrieve by entity first, then by similarity. Structured lookup beats semantic search when you know what you are asking about.
  • source and source_ref give provenance. A fact the user stated outranks one the agent inferred, and you can trace any memory back to where it came from.
  • supersedes handles change. When a preference updates, the new record points to the old one, so retrieval returns the current value while the history stays auditable.
  • expires_at prevents stale facts from living forever. Some facts, like “the client is mid-migration,” should decay.

Deciding what to write

There are two main approaches, and most systems use both:

  • Explicit writes. The agent has a remember tool and calls it when the user states something durable. This is transparent and easy to audit, but the agent will miss things.
  • Background extraction. After a run completes, a separate process reviews the transcript and proposes memory records. This catches more, but it needs a quality bar, and ideally a confidence threshold below which nothing is written.

Write less than you think. A useful rule: if a fact would not be worth a human writing in a CRM note, the agent should not store it either.

Retrieving the right memories

Retrieval quality matters more than storage volume. A practical ranking combines several signals. The Generative Agents paper from Stanford and Google researchers popularized combining relevance, recency, and importance, and the idea generalizes well beyond simulations:

import math

def score(record: MemoryRecord, similarity: float, now: datetime,
          half_life_days: float = 30.0) -> float:
    age_days = (now - record.created_at).total_seconds() / 86400
    recency = math.exp(-math.log(2) * age_days / half_life_days)
    source_weight = {"user_stated": 1.0, "tool_observed": 0.9, "inferred": 0.6}[record.source]
    return (0.6 * similarity + 0.25 * recency + 0.15 * record.confidence) * source_weight


def retrieve(store, tenant_id: str, user_id: str, subjects: list[str],
             query_embedding: list[float], k: int = 8) -> list[MemoryRecord]:
    now = datetime.now(timezone.utc)
    candidates = store.query(
        tenant_id=tenant_id,                       # hard filter, never optional
        visible_to_user=user_id,                   # enforces scope rules
        subjects=subjects,
        exclude_superseded=True,
        exclude_expired_before=now,
        embedding=query_embedding,
        limit=50,
    )
    ranked = sorted(candidates, key=lambda c: score(c.record, c.similarity, now), reverse=True)
    return [c.record for c in ranked[:k]]

The weights here are illustrative starting points, not recommendations. Tune them against an eval set of real retrieval cases. What matters is the structure: hard filters for tenancy, scope, and validity first; ranking second.

For memory that is really reference knowledge, such as product documentation or policy manuals, use a retrieval system designed for documents. That is a different problem with different tooling, covered in Agentic RAG: Moving Beyond Retrieve-Then-Generate.

Episodic memory: learning from past runs

Episodic memory records what happened: the task, the approach, the outcome, and any human correction. It is the layer most teams skip, and it is often where the biggest behavioral gains come from.

Consider an IT operations agent that triages alerts. Last month it spent many steps investigating a disk-space alert on a particular cluster before discovering that the cluster’s log rotation job had failed. If that episode is stored as a concise record (“disk alerts on cluster X: check log rotation job first; resolved by restarting the job”), the next similar alert can start from the known fix.

A good episode record includes:

  • Task signature: a normalized description that similar future tasks will match against.
  • Outcome: success, failure, or escalated, ideally verified by something other than the agent’s own claim.
  • Key steps: the few actions that mattered, not the full trajectory.
  • Corrections: what a human changed or rejected, and why.

Human corrections are the highest-value episodes you can capture. When a reviewer edits an agent’s draft or rejects a proposed action, storing that correction and retrieving it for similar future tasks gives you a lightweight feedback loop without retraining anything.

Only promote episodes with verified outcomes, since a failed approach labeled as success teaches the wrong lesson. Episodes also go stale when systems change, so add expiry.

Memory is an attack surface

Anything an agent writes to memory can be retrieved and acted on later, possibly by a different user in a different session. That creates risks a stateless agent does not have.

  • Memory poisoning. Malicious content in a document or email can instruct the agent to “remember” something false or harmful. If it gets written, it persists. Treat content derived from untrusted sources as lower confidence, and consider requiring explicit user confirmation before writing it. The OWASP Top 10 for LLM Applications covers prompt injection and data poisoning risks that apply directly here.
  • Cross-tenant leakage. A missing tenant filter on a single query can expose one customer’s data to another. Enforce tenancy in the data layer, not in the prompt.
  • Scope creep within a tenant. A note one user considered private should not appear in another user’s session. Default new memories to the narrowest scope.
  • Personal data obligations. Memory often contains personal data, so it carries the same retention and deletion obligations as your other systems. Build “forget this user” and “show me what you remember” as first-class operations.

A design checklist

  1. Define each memory layer, its store, and its lifetime before writing code.
  2. Make tenant and scope filters mandatory on every memory query.
  3. Store small, attributed facts with provenance, using supersession rather than overwrites.
  4. Add expiry to facts that naturally decay.
  5. Tune retrieval ranking on real cases.
  6. Capture human corrections as episodes.
  7. Treat writes from untrusted content as lower confidence or require confirmation.
  8. Ship “view” and “delete” operations for stored memories, and include retrieval in your evals.

FAQ

Do I need a vector database for agent memory?

Not always. Many long-term memories are best retrieved by structured lookup on subject, user, or account, which a relational database handles well. Vector search helps when you need to find memories by meaning, such as matching a new task to similar past episodes. Many teams use a database with vector support so both query types live in one place.

How is agent memory different from RAG?

RAG retrieves from a reference corpus, such as documents or knowledge base articles, that the agent reads but does not write. Memory is written by the agent or its surrounding system as it works, and it changes over time. The retrieval techniques overlap, but memory needs write rules, update handling, and per-user scoping that a static corpus does not.

Should the agent be able to edit its own instructions?

We advise against it in production. Letting an agent rewrite its system prompt or procedural rules makes behavior hard to audit and easy to manipulate. Capture lessons as episodic memories that are retrieved as context, and promote recurring lessons into the instructions through normal code review.

How do memories work in a multi-agent system?

Prefer explicit handoffs between agents and keep shared memory in a store owned by the coordinating agent. Workers read through scoped tools and write through validated operations. Our guide to multi-agent systems covers handoff design in more detail.

Working with TechnoKeen

TechnoKeen designs memory layers for production agents with tenancy, provenance, and deletion built in from the start. If your agents need to remember the right things and forget the rest, talk to our team or explore our glossary for related terms.

  • #agent memory
  • #context management
  • #agent architecture

TechnoKeen Engineering

TechnoKeen is an enterprise agentic AI company. Our engineers design, deploy, and govern AI agents for organizations in regulated and complex industries, and share what we learn in the field.

About TechnoKeen →

Keep reading

Agent Architecture 8 min read

Multi-Agent Systems: When One Agent Isn't Enough

Multi-agent systems split work across specialized AI agents. Learn when they beat a single agent, which topologies work, and the coordination costs to expect.

Ready to put agents to work?

Book a 45-minute executive briefing. We will review your priority workflows, current AI efforts, and risk posture, then outline a clear path to agents in production.