The Problem: The Amnesiac Agent
Imagine an AI assistant that helps you every day but every morning asks your name, your preferences, and the project you're working on. Frustrating, right? That's exactly what happens with an agent without memory. It starts from scratch every conversation, forgets everything it's learned, doesn't capitalize on past mistakes, and retains none of your habits. Memory is what transforms a reactive agent into a partner that improves over time, the difference between an eternal intern and an experienced colleague.
Inspired by cognitive science, we distinguish four types of memory: short-term (the current conversation (like what you keep in mind while someone is talking to you), long-term (persistent knowledge retrieved as needed) like looking up information in your notes), episodic (your memories of past situations: "the last time I deployed on a Friday, it crashed"), and semantic (pure facts: "PostgreSQL uses port 5432 by default").

Short-Term Memory: The Context Window
How It Works
The most basic form of memory is the model's context window. It's the equivalent of your working memory during a conversation, you keep in mind what was just said to understand what follows. Technically, the entire conversation history is injected into the prompt with each model call:
- [System instructions to the model]
- [User message 1]
- [Agent response 1]
- [User message 2]
- [Agent response 2]
- ... (all of this fits in the model's context)
- [User message N, this is where we are]
The Limits of This Approach
- Limited size: a context window is measured in tokens, and a token averages about three quarters of an English word. A 200,000-token window therefore holds on the order of 150,000 words, a fat novel. That is a lot, and a long working session still overflows it eventually.
- Growing cost: the entire context is billed again on every call. A conversation that grows therefore costs more per turn, even when you only add one sentence.
- Lost in the middle: over long contexts, a model uses what sits at the very start and the very end of its input better than what sits in the middle. Information placed mid-context can be ignored even though it is present. The phenomenon is described in long context vs RAG.
Strategies for Managing Size
- Sliding window: keep only the last N messages, dropping the oldest ones. Simple but brutal, you potentially lose key information.
- Progressive summarization: periodically summarize the history into a compact block. You lose details but keep the essentials.
- Hybrid: a summary of the whole conversation, plus the last five to ten messages in full. This is the compromise used in practice: the summary keeps the thread, the recent messages keep the precision.
Every ten or twenty exchanges, ask the model for a structured summary: "summarise this conversation, keeping the decisions made, the preferences the user expressed, and the context needed for what follows." That summary replaces the detailed history in the prompt. It is the end-of-meeting minutes rather than the verbatim transcript.
One consequence not to lose sight of: the summary is produced by the same model, with no guarantee of fidelity. Whatever it omits is definitively lost for the rest of the session. Summarising means arbitrating, and the arbitration is delegated to a text generation.
Compaction, Now a Standard Setting
The periodic summary got a name in 2025: context compaction. Coding agents popularised it, because a working session on a repository quickly fills even a very large window. When the input nears the limit, Claude Code, Codex or Vibe have the model write a summary of the session (goal, decisions taken, files touched, what remains to be done), then start again from a fresh input containing only that summary and the latest exchanges.
Two developments followed. First, compaction moved server-side: since late 2025 and early 2026, the OpenAI and Anthropic APIs offer to trigger it automatically past a token threshold, without the developer writing it. Second, some models are now trained to work across several successive compactions; in November 2025 OpenAI presented a coding model designed to carry one task across multiple context windows this way. A gentler variant, context editing, only clears old tool results (a long command output read fifty turns ago) and leaves the rest intact.
The caveat in the box above applies to all these variants: whatever the summary leaves out is lost from then on. That is why coding agents pair compaction with a memory that never gets summarised: files.
Long-Term Memory: The Vector Database
The Central Idea
The context window is limited: you can't fit everything in it. The solution is to store past interactions and knowledge in an external vector database, then pull back only a few items when they are useful, chosen by semantic similarity. It is a library with a librarian: instead of carrying everything on you, you ask for "what concerns the user's export preferences" and receive the few closest records.
The similarity-search mechanism is the one used by retrieval-augmented generation, described in vector databases and retrieval methods. What changes here is what gets indexed: not a document corpus, but the agent's own traces.
# Save an important interaction
memory_store.add(
text="The user prefers JSON format for exports",
metadata={"type": "preference", "date": "2024-03-15"}
)
# Later, retrieve relevant memories
relevant_memories = memory_store.search(
"output format for export",
k=5 # Top 5 most relevant memories
)
Simple Alternative: Key-Value Storage
For structured information (user preferences, established facts), a simple dictionary often works better than vector search, faster, more predictable, no semantic ambiguity:
user_profile = {
"language": "english",
"expertise_level": "advanced",
"preferred_format": "JSON",
"recent_projects": ["API migration", "dashboard analytics"]
}
It's like having a clear, structured client file rather than digging through thousands of messages to find a preference.
Episodic Memory: Lessons Learned
Storing Complete Experiences
Episodic memory doesn't just store facts, it stores complete episodes: the starting situation, the actions attempted, the outcome obtained, and the lesson retained. It's the difference between knowing that "connection timeouts can cause errors" (semantic fact) and remembering that "the last time we had this error, it was a timeout and we fixed it by increasing to 30 seconds" (episode).
{
"episode": "Bug #423 resolution",
"date": "2024-03-10",
"context": "Database connection error",
"actions_taken": ["Check credentials", "Test network connection", "Discover too-short timeout"],
"outcome": "Resolved by increasing timeout to 30 seconds",
"lesson": "Always check connection timeouts first"
}
Reflexion (Shinn et al., 2023) is the reference work on this mechanism. The procedure: after a failure, the model is asked to write out what went wrong, why, and what it would do differently; that text is kept and placed back into the input of subsequent attempts.
The point to hold on to, because it is counter-intuitive: nothing is retrained. The model's weights do not change. The "lesson learned" is one more paragraph of text in the prompt. That is what makes the method cheap, and what bounds it, since everything thus "learned" occupies room in a context window that remains finite.

Semantic Memory: The Knowledge Base
Facts and Concepts
Semantic memory stores learned facts and concepts organized by domain, this is the agent's factual knowledge:
- Business rules (a refund requires an invoice less than 30 days old)
- Domain definitions and terminology
- Relationships between concepts (this service depends on that database)
- Standard procedures and task sequences
A Personal Knowledge Graph
The most powerful form of semantic memory is the knowledge graph: a network of entities connected by relationships. The agent builds and enriches it through its interactions. For example:
"Alice → works_for → TechCorp" and "TechCorp → makes → software": put those two relations into the model's input and you will usually get "Alice works in software," even though nobody wrote it. Beware the usual phrasing, though: the graph does not "reason." The graph makes it possible to retrieve, by walking relations, two facts that a text-similarity search would never have brought together; the model then produces the concluding sentence. The technique and its limits are covered in graph RAG.
File-Based Memory: CLAUDE.md, AGENTS.md and Skills
The form of memory that spread most widely in 2025 is nothing sophisticated: a text file the agent reads at the start of every session. A coding agent opens a repository, finds a CLAUDE.md file (for Claude Code) or AGENTS.md (the format shared by Codex, Cursor, Vibe and many others), and places it in its input before the first request. It holds what a new colleague ought to know: how to run the tests, the naming conventions, the commands never to run, the project's architecture.
The mechanism is often layered: a personal file ("answer me in French"), a file per project, sometimes one per subfolder, read from the most general to the most specific. AGENTS.md, launched in summer 2025 by OpenAI together with other vendors, became in December 2025 one of the three founding projects of the Agentic AI Foundation, under the Linux Foundation, alongside MCP.
Why the success, compared with the vector stores described above? Because a file can be read and corrected by hand. You see exactly what the agent "knows," you edit it in a text editor, you version it with the code, and a colleague can review the change. It is the transparency best practice from the end of this page, applied by construction. The downside: the whole file is reread every session, so it must stay short, and two identical files read by the same tool can double the instructions (a real bug described in DeepSeek Harness).
Two extensions complete the picture:
- skills act as procedural memory (know-how, the "implicit" branch of the diagram at the top of the page): instructions stored in folders, of which only the description is read permanently while the content is loaded on demand. The mechanism is described in agents: the landscape;
- the memory tool Anthropic has offered since September 2025 gives the model a directory of files where it can itself write, reread and delete notes from one session to the next. It is MemGPT's idea (below), with files instead of a database.
Memory in Consumer Assistants
Chat assistants all adopted memory between 2024 and 2026, through three mechanisms that often coexist:
- Saved memories: a list of short facts ("works in logistics," "prefers brief answers") inserted into the instructions of every new conversation. The user can view and delete them.
- Searching past conversations: when the question calls for it, the program searches the history, like a RAG whose corpus is your own exchanges, and places the relevant passages in the input.
- Background synthesis: between conversations, a process rereads the history and updates a portrait of the user, without waiting to be told "remember."
A short timeline:
| Assistant | Milestones |
|---|---|
| ChatGPT (OpenAI) | Saved memories in 2024; reference to the whole chat history in April 2025; overhaul announced on June 4, 2026 around a background synthesis OpenAI calls dreaming, first for paying subscribers in the US |
| Claude (Anthropic) | Search across past chats in August 2025; memory for business plans in September 2025, then for paid plans in October 2025; opened to free accounts on March 2, 2026, with a tool to import memories from another assistant |
| Le Chat, now Vibe (Mistral) | Memories in beta for all users on September 2, 2025, editable one by one, with import from ChatGPT; see Le Chat |
Two remarks. First, the ability to import your memories from one assistant to another (which Claude and Le Chat both highlighted) turns memory into a competitive battleground: what an assistant knows about you is the hardest thing to walk away from. Second, every mechanism inherits the flaws described on this page. Background synthesis is an automatic summary, hence an arbitration with no guarantee of fidelity; a fact saved a year ago comes back with the same authority as today's; and an automatically fed memory can record hostile text (see the box on the durable attack channel, below). That is why all these products offer a "temporary" chat that neither reads nor writes memory, and a page showing what has been retained.
Memory Architectures in Practice
The idea of giving neural networks external memory isn't new. As early as 2014, Neural Turing Machines proposed an architecture where the network learns to read from and write to an external memory matrix, like a differentiable computer. The network itself decides where to read and where to write via attention mechanisms, it's a direct ancestor of the memory systems we use today in agents.
Neural Turing Machines (Graves et al., 2014)MemGPT / Letta: OS-Inspired Memory
MemGPT proposes hierarchical memory management modeled on computer architecture:
- Random access memory (RAM): the active context window, immediate access, limited size
- Archival disk: persistent storage of practically unlimited capacity, but you have to query it
- Recall memory: an index for finding an item in the history efficiently
- Transfers are triggered by tool calls: what moves from context to archive, and back, is decided by function calls the model produces, that is, function calling applied to its own memory

The computer analogy carries a long way, including in its limits: like an operating system, this arrangement does not create capacity, it organises transfers between a small fast space and a large slow one.
In 2024 MemGPT became a company, Letta, spun out of the Berkeley lab where the project started. Its most notable idea since is sleep-time compute (April 2025): rather than reorganising memory during the conversation, which slows the answer, a second agent does it during idle time, rereading the context and preparing notes useful for likely questions. The paper reports, on reasoning tasks adapted for the occasion, equivalent accuracy with roughly five times less computation at answer time. In 2026 Letta refocused on a coding agent whose memory is versioned like code, which joins up with the file-based memory described above.
Sleep-time Compute: Beyond Inference Scaling at Test-timeMem0: Memory as a Cloud Service
Mem0 is an off-the-shelf memory layer that saves you writing the storage logic yourself. Per its documentation, it offers:
- automatic memory extraction from conversations
- deduplication, so a repeated fact is stored only once
- an interface reduced to three operations: add, search, update
- separation by user and by agent
These are vendor claims; we report them as such. The team published a paper in April 2025 that describes the mechanism (extract the salient facts from each exchange, compare them with existing memories to decide whether to add, update or delete, with a graph variant) and evaluates it on LoCoMo, a benchmark of very long conversations. The paper claims a 26% relative improvement over ChatGPT's memory according to a judge model, and more than 90% of tokens saved compared with sending the whole conversation. These are the vendor's own measurements on a single benchmark. The company raised $24 million in October 2025, a sign that the "memory layer" has become a market of its own.
Mem0: Building Production-Ready AI Agents with Scalable Long-Term MemoryHow to Measure a Memory
Two benchmarks serve as references. LoCoMo offers conversations of several hundred turns, spread across dozens of fictional sessions, followed by questions that require retrieving an old detail, placing an event in time or combining two memories. LongMemEval evaluates five abilities of an assistant: extracting a piece of information, reasoning across sessions, reasoning about time, taking an updated fact into account, and abstaining when the answer is not in the history. That last point matters: a memory that invents a recollection is worse than an empty one.
Evaluating Very Long-Term Conversational Memory of LLM Agents LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive MemoryPractical Implementation
Simple Pattern with Automatic Summarization
Libraries provide this setup ready-made. With LangChain 1.0 (October 2025), it takes the form of middleware (code that slots into the agent's loop):
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
model=main_model,
tools=[],
middleware=[
SummarizationMiddleware(
model=small_model, # a cheaper model is enough to summarise
trigger=("tokens", 4000), # summarise once history exceeds ~4,000 tokens
keep=("messages", 20), # keep the 20 latest messages verbatim
)
],
checkpointer=InMemorySaver(), # keeps the conversation from one call to the next
)
LangChain's old memory classes (ConversationSummaryBufferMemory and its cousins), found in many 2023-2024 tutorials, were deprecated before this release: the principle is the same, the interface has changed.
Hybrid Pattern (recommended)
The pattern that works best in production combines three levels:
- Short-term: the last 5 messages in the context (for conversation fluidity)
- Long-term: vector search of relevant past interactions (for historical context)
- Profile: user preferences stored as key-value pairs (for personalization)
This mirrors how humans function: you remember your conversation partner's last sentence (short-term), you can recall an anecdote they told you (long-term), and you know they prefer coffee over tea (profile).
Storing is trivial. The difficulty is retrieval: bringing back the right memories at the right moment. Too many off-topic memories and the model's input fills with noise competing with the useful information. Too few and the agent looks amnesiac. The two settings that matter most are the quality of the semantic search and the number of results returned, conventionally written k (as in top-k, the k nearest).
A point rarely raised, and worth raising. Whatever is written into long-term memory will be read back later and placed into the model's input. So if the agent automatically memorises what it encounters, hostile text read just once (in a document, an email, a web page) can be stored as a memory, then resurfaced in every later session.
What differs from an ordinary injection is persistence: a classic injection lasts one conversation, this one survives restarts and no longer needs the attacker. That is the technical reason behind two of the best practices below, explicit rather than automatic memorisation, and letting the user inspect and correct what is stored. The general mechanism is described in tool use patterns and prompt injection.
Best Practices
- Start simple: sliding window + summary solves 80% of problems. Only add complexity if justified by a real need.
- Explicit memory: prefer letting the user say "remember that..." rather than memorizing everything automatically, it's more predictable and transparent.
- Active forgetting: regularly delete memories that have become false or outdated. Nothing in the mechanism expires a memory on its own: a preference recorded a year ago will be placed into the input with exactly the same authority as today's information.
- Transparency: the user should be able to see and edit what's memorized. An agent with opaque memory creates distrust.
- Continuous evaluation: regularly test whether the agent retrieves the expected information. Retrieval quality degrades quietly as the store grows; without measurement, you only notice through the consequences.
1. With Reflexion, an agent fails, writes down a « lesson learned », then succeeds on the next attempt. What actually changed in the system?
2. A hostile text read once in an email gets recorded by the agent's automatic memory. Why is that worse than an ordinary prompt injection?
3. To contain a growing conversation, the history is replaced with a periodic summary. What is the price to pay, according to the page?
4. A knowledge graph contains « Alice works for TechCorp » and « TechCorp makes software ». The agent concludes that Alice works in software. Who did the « reasoning »?
5. According to the warning box, where does the real difficulty of agent memory lie?
6. Why did coding agents adopt text files such as AGENTS.md or CLAUDE.md rather than a vector store for their standing instructions?