Skip to content

What is agent memory?

Mykhailo Poliarush

Definition

Agent memory is the part of an AI agent that stores information outside the model and brings it back when needed: the state of the current task within a session, and facts, past experiences and instructions across sessions. It lets an agent continue earlier work and remember users without keeping everything in the context window.

What types of agent memory are there?

A common set of names comes from cognitive science, by way of Cognitive Architectures for Language Agents (CoALA) by Theodore Sumers, Shunyu Yao, Karthik Narasimhan and Thomas Griffiths. The paper was last revised on March 15, 2024, so it is an older source, but LangChain's current memory docs still point to it. CoALA splits an agent's memory into one short-term store and three long-term ones:

Memory typeWhat CoALA puts in itWhat it looks like in a product agent
WorkingActive information for the current decision cycle: inputs, retrieved knowledge, active goalsThe current task's state and the messages in this session
EpisodicExperience from earlier decision cyclesLogs of past runs, resolved tickets, examples of what worked
SemanticThe agent's knowledge about the world and itselfFacts about a user or customer, product details, team conventions
ProceduralKnowledge in the model weights and in the agent's codeThe system prompt, tool definitions, the agent's own code

CoALA adds a warning about the last row. An agent can learn by writing to procedural memory, but that is "significantly riskier than writing to episodic or semantic memory, as it can easily introduce bugs or allow an agent to subvert its designers' intentions." An agent that rewrites its own instructions needs the strictest review of all.

What is the difference between short-term and long-term agent memory?

LangChain's Memory overview (last updated November 13, 2026) draws the line by recall scope:

  • Short-term memory is thread-scoped. It tracks one conversation or session as part of the agent's state, saved by a checkpointer so the thread can resume.
  • Long-term memory is shared across threads. It stores user-specific or application-level data, can be recalled in any session, and is organized in custom namespaces, such as a user or organization ID.

Short-term memory is saved outside the model too, but it only helps the agent when it fits in the context window, so long threads need trimming or summaries. Long-term memory lives outside the model, and it only helps when the right records are loaded back in at the right time. Choosing what to load is part of context engineering.

How does agent memory work?

A survey of agent memory research from 2022 through early 2026 (Memory for Autonomous LLM Agents, a single-author preprint posted March 8, 2026) formalizes memory as a loop of three steps: write, manage, read.

  1. Write. Decide what is worth storing. LangChain's docs describe two timings. Writing "in the hot path" makes a memory available at once, but can add latency and an extra decision to the agent's turn. Writing in the background keeps the main response fast, but if it runs too rarely, other sessions may not see the memory yet.
  2. Manage. Merge duplicates, resolve contradictions and retire stale records. The survey lists what this needs: temporal versioning that prefers the newest record, source attribution that ranks a user's statement above an agent's inference, contradiction detection that flags conflicts, and scheduled consolidation.
  3. Read. Retrieve the few records that matter for the current step and place them in the context.

Model providers have started to ship parts of this loop. Anthropic's Memory tool (tool type memory_20250818, available on Claude 4 and later models) lets Claude create, read, update and delete files in a /memories directory. It runs client-side: Claude requests each file operation and your application executes it against storage you control, such as a per-user directory or keys in a database. When the tool is enabled, Claude checks its memory directory before starting a task.

Example: a memory store that handles conflicts

This store applies three of the survey's management rules in a few lines: versions, source ranking and conflict flags. Every record is scoped to one user, keeps its source and date, and is never overwritten, so the history survives. A write filter rejects anything that looks like a card number or mentions an API key or password.

# memory_store.py: long-term agent memory with a write filter, per-user scope, versions and conflict flags.
import re

SECRET = re.compile(r"\b(?:\d[ -]?){13,16}\b|api[_-]?key|password", re.I)
RANK = {"user": 2, "inferred": 1}         # what the user said beats what the agent guessed

class MemoryStore:
    def __init__(self):
        self.records = {}                 # (user_id, key) -> every version ever written

    def write(self, user_id, key, value, source, on):
        if SECRET.search(value):
            return f"rejected {key!r}: looks like a secret"
        self.records.setdefault((user_id, key), []).append({"value": value, "source": source, "on": on})
        return f"stored {key!r} for {user_id} ({source}, {on})"

    def read(self, user_id, key):
        versions = self.records.get((user_id, key), [])  # another user's namespace is never searched
        if not versions:
            return None, ""
        best = max(versions, key=lambda v: (RANK[v["source"]], v["on"]))
        newest = max(versions, key=lambda v: v["on"])
        conflict = f" (conflict: newer {newest['source']} value {newest['value']!r} on {newest['on']})" \
            if newest["value"] != best["value"] else ""
        return best["value"], conflict

memory = MemoryStore()
print(memory.write("anna", "city", "Berlin", "inferred", "2026-03-02"))   # from an old invoice address
print(memory.write("anna", "city", "Krakow", "user", "2026-09-14"))       # "I moved to Krakow"
print(memory.write("anna", "city", "Berlin", "inferred", "2026-10-01"))   # agent re-reads the old invoice
print(memory.write("anna", "payment", "card 4111 1111 1111 1111", "user", "2026-10-02"))

for user in ("anna", "ben"):
    value, note = memory.read(user, "city")
    print(f"context for {user}: city = {value}{note}")

Output with Python 3.11 (python3 memory_store.py):

stored 'city' for anna (inferred, 2026-03-02)
stored 'city' for anna (user, 2026-09-14)
stored 'city' for anna (inferred, 2026-10-01)
rejected 'payment': looks like a secret
context for anna: city = Krakow (conflict: newer inferred value 'Berlin' on 2026-10-01)
context for ben: city = None

The agent's newest guess does not silently replace what Anna said, but the conflict travels into the context, so the agent can ask her instead of guessing. Ben's agent sees nothing of Anna's. A real store adds retrieval by meaning and an expiry policy; the ranking, the scope and the write filter are the parts worth keeping.

What can go wrong with agent memory?

  • Stale facts. Without explicit mechanisms such as versioning, the survey notes, an agent has no way to tell a 2024 address from a 2022 one.
  • Sensitive data. The survey lists what deployments need: encryption, per-user access scoping, automated PII redaction, retention policies and deletion that reaches every tier, including vector index entries and backups. Anthropic's docs add that for stronger guarantees than the model's own restraint, your handler should strip sensitive data before it writes a file.
  • Path tricks. A path such as /memories/../../secrets.env can escape the memory folder. Anthropic says to validate every path in every command.
  • Poisoned memories. Text an agent stores today can steer it next week. Treat memory as untrusted input; the AI agent security entry covers memory and context poisoning.
  • Failures you cannot place. When an answer is wrong, the cause may be retrieval, a write that never happened, detail lost in a summary, or the model's reasoning. The survey recommends logging every write, read, update and delete with timestamps.

When does an agent need long-term memory?

Add it when tasks or relationships outlive a session: an assistant that should remember a customer's setup, a coding agent that should keep a project's conventions, a long job that must survive a restart. Skip it for one-shot tasks such as classifying a ticket or extracting fields from a document, where memory adds a store to secure and a source of stale context without improving the answer.

Start simple. The survey's own recommendation is a context window plus one retrieval store, measured well, moving to tiered memory with learned control only when data shows it helps your workload.

What should you check before shipping agent memory?

  1. Every record has an owner, a source and a date, and reads are scoped to the current user or tenant.
  2. A write filter runs before storage, for secrets, personal data and instructions disguised as facts.
  3. Conflicts are surfaced, not resolved silently.
  4. Users can see and delete what the agent remembers, and deletion reaches indexes and backups.
  5. Memory operations are logged, so a wrong answer can be traced to a write, a read or the model.
  6. Tests cover memory across sessions: a fact stated in session one, changed in session two, recalled correctly in session three.

In the AI agents we build, retrieval comes with access rules, so each user's agent sees only what that user may see. Every run is traced step by step, so our engineers can replay a failure, fix it and add it to the eval set.

Sources

  1. Cognitive Architectures for Language Agents, arXiv 2309.02427 (Sumers, Yao, Narasimhan, Griffiths), 2024-03-15
  2. Memory overview, LangChain Docs, 2026-11-13
  3. Memory for Autonomous LLM Agents: Mechanisms, Evaluation, and Emerging Frontiers, arXiv 2603.07670 (Pengfei Du, preprint), 2026-03-08
  4. Memory tool, Claude Platform Docs (Anthropic), 2026-11

Frequently asked questions

Is agent memory the same as RAG?

No, although both can use the same kind of store. RAG retrieves from documents people wrote and maintain; agent memory is written while the agent works, from what users say and what the agent concludes, so it needs write rules, versioning and deletion that a document index usually does not.

Does a bigger context window remove the need for agent memory?

No. The window lasts for one request, and LangChain's memory docs note that most models given very long histories get distracted by stale or off-topic content, respond more slowly and cost more. Memory keeps the history outside and loads back only what the current step needs.

Where should agent memory be stored?

In storage your application controls, scoped per user or tenant: a database, a key-value store or a vector store. Anthropic's memory tool, for example, only requests file operations; your code decides where the files actually live.

How do you test agent memory?

With scenarios that span sessions rather than single prompts: state a fact, change it later, and check that the agent recalls the current value, keeps other users' data out, and forgets what was deleted. Research benchmarks are moving the same way, from static recall tests to multi-session agent tasks.

Building with AI agents? Talk to an engineer.