Memory
Memory is not a database you bolt on. It is a set of policies about what survives a turn, what survives a session, and what should have been forgotten already.
5.1Short-term and long-term memory fail in different ways
Practitioners speak of agent memory as one engineering problem, but its two halves break under opposite pressures and call for opposite defences. Short-term memory is the conversation buffer: the messages, tool calls, and results physically present in the context window on the current forward pass. It fails by exhaustion. As a session grows the buffer exceeds the limit and something has to go, and whatever policy removes it deletes information that was, until that moment, perfectly accurate. The characteristic failure is an agent that knew a fact ten turns ago and now behaves as though it never existed, usually with no signal that a deletion occurred.
Long-term memory is the persisted store written and read across sessions. It fails by staleness rather than exhaustion. Capacity is effectively unbounded so nothing is silently dropped; instead, records that were true when written survive after the world changes. The user who moved cities still has a record naming the old one, and retrieval surfaces it with the same confidence it surfaces everything else. The engineering consequence is direct: short-term memory is defended by budgeting and eviction policy, long-term memory by write discipline, conflict resolution, and invalidation. A team that builds a careful retrieval pipeline and no invalidation path has solved the easier half.
MemGPT organises this split by borrowing from operating systems, treating the context window as physical memory and everything outside it as disk. Main context holds system instructions, which are read-only and pinned; working context, a small writable region for facts the agent has decided it must always have; and a queue of recent turns. External context holds recall storage, the full message history, and archival storage, a general store the agent explicitly deposits into and searches.
The paging discipline is where this differs from a truncating chat loop. A queue manager watches token utilisation, and at roughly seventy per cent it inserts a message telling the model that eviction is imminent. That warning exists so the agent can write anything important into working or archival storage before the buffer is cut. At the flush threshold it evicts about half the window, moves it to recall storage, and regenerates a summary that folds the evicted turns into the previous summary. Because each round consumes the prior summary rather than the original text, detail loss compounds — the summary after five rounds is a summary of a summary, and nothing in the mechanism preserves specificity across generations.
That compounding deserves a defence rather than a shrug. Summarisation is lossy in a biased direction: it preserves narrative and discards particulars. Identifiers, exact numbers, file paths, version strings, and error codes are precisely the tokens a summariser treats as noise and precisely the ones a later turn needs. An agent debugging a deployment will compress the episode to a sentence about a configuration issue and lose the pod name it was actually looking at. The standard mitigation is a sliding window with an anchored prefix: the system prompt, tool schemas, original task statement, and a small block of durable facts are declared immune to eviction and re-emitted verbatim, while compaction operates only on the tail.
A second constraint is easy to overlook and expensive to discover in production. Providers cache the key and value tensors for a prompt prefix and charge less for cached tokens, but the cache requires an exact prefix match. Any edit near the front invalidates everything after it. If the system injects retrieved memories high in the prompt and re-ranks them each turn, every turn produces a fresh prefix and pays full price. Append retrieved content near the end, below the stable blocks, and order retrieved items deterministically — by identifier rather than by descending relevance — which costs almost nothing in answer quality and preserves cache hits whenever the retrieved set is unchanged.
| TIER | LOCATION | WRITTEN BY | FAILURE MODE |
|---|---|---|---|
| System instructions | Main context | Developer; read-only to the agent | Drift as rules accumulate |
| Working context | Main context | The agent, by tool call | Fills up; something must be evicted |
| Message queue | Main context | Runtime, append-only | Eviction and lossy summarisation |
| Recall storage | External | Runtime, automatic | Invisible unless search finds it |
| Archival storage | External | The agent, explicitly | Stale entries retrieved confidently |
5.2Memory as tool-based action
Most retrieval systems place memory management outside the model. Middleware embeds the incoming turn, queries an index, selects the top results, and splices them into the prompt before the model sees anything. The model consumes whatever the pipeline decided was relevant, with no way to say the retrieved material is wrong, no way to ask for something else, and no way to record a fact it just learned. Exposing memory operations as ordinary function calls inverts this: the model decides when to read and when to write, alongside its domain tools.
The function surface is small. Writes to in-context memory are an append and a targeted replace. Choosing replace over a general rewrite is deliberate — a substring substitution fails loudly when the target string is absent, surfacing a stale assumption, whereas a full-block regeneration silently rewrites content the model was not asked to touch and invites hallucination during the rewrite. Reads are a search over conversation history and a separate search over deposited knowledge. Keeping those two searches distinct matters, because one answers what was said before and the other what the agent knows, and merging them lets conversational chatter drown out curated facts.
Two control-flow details make this an autonomous loop rather than a single lookup. A function can request that control return to the model immediately after it completes, which lets the agent chain operations: search, read the result, recognise the query was wrong, search again with better terms, then answer. Without chaining the agent gets one retrieval attempt per turn and the first query has to be right. And errors from memory operations, including attempting to write to a full block, are returned to the model as observations rather than raised to the operator, so the agent can respond by replacing a stale line instead of failing.
The trade should be stated plainly rather than sold. Pipeline retrieval is more reliable in the narrow sense that it always runs, with predictable latency, and never forgets to look something up. Tool-based memory is less reliable in that sense, because the agent may not call the function when it should. What it buys is inspectability. Every operation appears in the trace as a named call with arguments and a result, so a wrong answer can be attributed: the agent never searched, searched with a poor query, retrieved the right record and ignored it, or retrieved a record that was itself wrong. Those four failures have four different fixes, and a pipeline that splices context invisibly makes them nearly indistinguishable.
Provenance on writes is what keeps a self-editing store from decaying. Every record should carry the source turn that produced it, a timestamp, the writing actor, and a marker distinguishing what the user asserted from what the agent inferred. Memory errors are almost always traceable to a bad write rather than a bad read, and a store of bare assertions gives no way to find where a wrong fact came from or what else the same faulty inference produced. Provenance also makes selective invalidation possible: if a tool returned bad data at a known time, every record pointing at that call can be revoked in one operation. Enforce the fields in the write function rather than requesting them, because a model asked politely will comply most of the time, and most of the time is not a property you can build invalidation on.
def archival_insert(text, source_msg_id, kind, confidence):
assert kind in ("stated", "inferred", "tool_result")
if not source_msg_id:
return "ERROR: source_msg_id required; write rejected"
store.put({
"text": text,
"source": source_msg_id,
"kind": kind,
"confidence": confidence,
"written_at": now(),
"written_by": current_agent_id(),
})
return "ok" # errors return to the model, not the operator5.3The file system as externalised memory
An agent that already has read, write, list, and search tools has a complete memory system available without additional infrastructure. A file system provides durable storage with unbounded capacity, a hierarchical namespace, byte-exact retrieval, and search primitives that predate every vector database by decades. If the agent operates on files anyway, memory requires no new component, no embedding model, no index to keep in sync, and no separate failure domain.
The property that makes this work is the separation between capacity and consumption. A directory tree holds gigabytes while the window holds a few hundred thousand tokens, and the agent bridges the gap by reading only what it needs. Listing a directory costs a few dozen tokens and says what exists. Searching for a term costs a few hundred and says where the material lives. Reading one file costs whatever that file costs. This is progressive disclosure applied to memory, and it has a property a vector store lacks: the agent can list, search, read a header, decide it picked the wrong file, and try another, all within a single turn.
Directory structure functions as a hand-built index, and its quality determines whether search is needed at all. A path that encodes project and document type lets the agent construct the location rather than search for it. This is a semantic index maintained by convention, and a human can read it, correct it, and reason about its coverage. The convention has to be specified in the system prompt and then followed, because an agent left to invent paths will produce notes, notes-two, and final-notes-v3 within a week.
Files the agent wrote and files a human wrote are different kinds of object and belong in different places. Human-authored files are ground truth — specifications, source, configuration — and if the agent believes something contradicting them, the agent is wrong. Agent-authored files are hypotheses recording what it concluded at a moment, from evidence it may have misread. The dangerous case is a generated note that has aged into apparent authority: an assertion written in March, read in August, describing a service that has since changed. Physical separation under a distinct root is the cheapest defence, with a dated header in every generated file so a later read has grounds to re-verify.
Scratchpads sit at the short-lived end and serve a purpose durable notes do not. A scratchpad holds intermediate state during a long task — files still to process, findings so far, a plan with items checked off — and its value is that it survives compaction. When the buffer is summarised and the details of the early steps compress to a sentence, the scratchpad still holds them verbatim. This makes long tasks robust against context loss in a way no summarisation policy can match, because the summariser never touched the file. Scratchpads should be explicitly ephemeral and deleted at task end, or they accumulate into stale plans that the next search surfaces as though current.
Search over files is retrieval without an index, and its properties differ from embedding search in ways that decide when each applies. Exact matching finds an error code or a function name with perfect precision and no recall for paraphrase; it cannot find the function that handles sales tax if the code names it differently. Embedding search inverts both properties, handling paraphrase well and identifiers badly, since they tokenise into fragments carrying little semantic signal. A file system therefore wins when the corpus is small enough to enumerate, when queries are identifier-shaped, when content changes often enough that reindexing is a burden, when a human needs to edit the memory directly, and when byte-exact fidelity matters. A vector store wins when enumeration is infeasible and the question's vocabulary does not match the answer's.
Version control extends a file-based memory with history, addressing staleness from a different direction than invalidation. A memory directory under version control records, for every fact, when it entered, what change introduced it, and what the previous value was. Reverting a bad write becomes one operation rather than a reconstruction, and the audit trail satisfies the provenance requirement from the previous section with no additional schema. The limits are that history grows without bound and that concurrent writes from parallel agents are handled poorly, which pushes multi-agent designs toward per-agent subdirectories with an explicit merge step.
| QUERY SHAPE | FILE SYSTEM | VECTOR STORE |
|---|---|---|
| Exact identifier or error code | Perfect precision | Unreliable; identifiers tokenise poorly |
| Conceptual paraphrase | Fails unless vocabulary matches | Strong; this is the design case |
| A hundred documents | Enumerable; no index to maintain | Index overhead exceeds the benefit |
| A million documents | Search becomes slow and noisy | Approximate nearest neighbour scales |
| Content edited by humans | Native; diffs and review work | Reindex on every edit |
| History of what changed when | Version control answers directly | Needs a separate versioning layer |
5.4Structured memory paradigms
The storage structure determines which questions are cheap, and none is cheap on every question. A key-value profile answers point lookups in constant time and is trivially editable and auditable, which is why most production personalisation systems have one; it answers nothing about relationships or history, and degrades when the key space is open-ended. An entity graph makes multi-hop questions tractable and contradiction detectable, since two edges asserting different values for the same relation are visibly in conflict, at the cost of extraction — every incoming fact must be resolved to entities and relations, and both steps add latency and error.
An episodic log stores events in order, which makes it the natural structure for what happened and what changed, and the only one supporting reconstruction of state at a past moment. Answering an aggregate question requires scanning, so asking what a user generally prefers means reading a thousand events and synthesising. A vector store answers fuzzy similarity over large corpora at low latency and answers negation, aggregation, and time-range filtering badly or not at all. Systems needing several query shapes end up composing structures rather than choosing one.
The most-cited concrete design for episodic memory with scored retrieval comes from the Generative Agents work, and it is specified precisely enough to reimplement. Each memory holds a description, a creation timestamp, and a last-access timestamp. Retrieval scores every candidate on three components. Recency applies exponential decay, with a factor of 0.995 per simulated hour since the memory was last retrieved. Importance is assigned once at write time by asking the model to rate the memory's significance from one to ten, with the prompt anchoring one at mundane events and ten at life-changing ones. Relevance is embedding similarity to the query. The three are normalised and summed, with all three weights set to one in the paper's implementation.
The importance term is easy to omit and costly to omit. Without it, retrieval is recency plus similarity, and such a system surfaces the most recent thing said about a topic in preference to the most consequential thing ever said about it. Rating significance at write time means the cost is paid once per memory rather than once per query, which is what makes a model-scored term affordable at all.
Reflection addresses the fact that a stream of raw observations contains no generalisations. The agent tracks the accumulated importance of events since its last reflection, and when the sum crosses a threshold — 150 in the paper, firing two or three times per simulated day — it queries its hundred most recent records, prompts for the three most salient questions about them, retrieves evidence for each, and writes insights back into the stream with citations to the supporting records. Those insights are themselves retrievable and can support later reflections, producing trees whose leaves are observations and whose interior nodes are progressively more abstract. The citations are what keep this from becoming ungrounded drift.
Mem0 approaches the same territory from production, replacing store-everything-and-score-later with an extraction and consolidation pipeline that keeps the store small. Extraction produces candidate facts from each message pair using a running summary and the ten most recent messages. Consolidation retrieves the ten most similar existing memories and has the model choose among adding, updating, deleting, or doing nothing. The delete branch is the piece retrieval-only systems lack, and it is the direct answer to the staleness failure.
Its reported results quantify the trade. Search latency sits near 0.15 seconds at the median, and end-to-end latency at the ninety-fifth percentile is about 1.4 seconds against roughly 17 seconds for a baseline that stuffs the whole conversation into the prompt — a reduction over ninety per cent. Token footprint falls from roughly twenty-six thousand per conversation to about seven thousand. The accuracy side deserves reading rather than skipping: that full-context baseline scores higher on the judged metric, near 73 against 67. Reading every token is more accurate than reading a distilled subset. Consolidation buys an order of magnitude in latency and cost for a several-point accuracy concession, which is a good trade at production scale and a poor one when conversations are short and accuracy is the only objective.
| PARADIGM | CHEAP QUERY | EXPENSIVE QUERY | MAIN COST |
|---|---|---|---|
| Key-value profile | Point lookup of a known attribute | Anything relational or historical | Key space sprawl |
| Entity graph | Multi-hop relations; contradiction | Ordering and free-text recall | Extraction per write |
| Episodic log | What happened, when, in what order | Aggregates and generalisations | Scan cost grows with history |
| Vector store | Fuzzy similarity at scale | Negation, aggregation, time ranges | No invalidation path |
| Scored stream | Salient, relevant, and recent at once | Precise lookup | Rating importance at write time |
| Consolidated store | The current state of a fact | Reconstructing superseded history | Deleted detail is unrecoverable |
5.5Cross-agent memory, forgetting, and evaluation
When several agents share a store, the store becomes a trust boundary, and the common mistake is treating this as access control when it is closer to injection. A record written by a research agent and read by an agent with deployment permissions has crossed from low privilege to high, carrying whatever content it picked up. Scoping writes does not help, because the write was legitimate. What must be scoped is the read: each agent should declare which namespaces it consumes and at what trust level, and lower-tier content should enter the prompt marked as untrusted observation rather than as fact.
Shared memory also introduces write conflicts. Two agents observing the same situation and reaching different conclusions will both write, leaving contradictory records with equal standing. Resolving by last write loses the disagreement, which is often the most informative signal available. Keeping both with provenance intact and surfacing the conflict at read time lets the consuming agent see that two sources disagree rather than presenting one as settled.
Forgetting should be governed by content type rather than one global policy. Ephemeral task state should be discarded at task end and is actively harmful if it survives, since a stale plan retrieved during a new task misdirects the agent. Observations about a changing world should carry a short lifetime and be re-verified. Stable preferences may persist but should be revisited when contradicted. Corrections, where the user explicitly said the agent was wrong, should arguably never expire and should outrank the record they correct.
Cascade deletion makes forgetting harder than it looks. Derived memories depend on sources: a reflection was synthesised from observations, a consolidated fact merged from several turns. Deleting a source without addressing its derivatives leaves conclusions with no evidence, and those orphans are more dangerous than raw records because they are stated as generalisations carrying no visible uncertainty. Three policies are available and the choice should be deliberate — delete the derivatives too, mark them unsupported and require re-derivation, or retain them with a marker that their evidence was retracted. All three require that derivation edges be recorded at write time, which is the practical reason those citation links matter beyond interpretability.
Evaluating memory requires more than checking the final answer, since a correct answer can come from a lucky guess and a wrong one from perfect retrieval the model then ignored. Two benchmarks anchor current practice. LOCOMO consists of fifty very long conversations averaging around three hundred turns across up to thirty-five sessions, with questions spanning single-hop, multi-hop, temporal, and adversarial categories, and — critically — it annotates which turns contain each answer, which is what makes retrieval-level measurement possible rather than only answer-level. LongMemEval targets five abilities across five hundred curated questions, and reports roughly a thirty per cent accuracy drop for commercial assistants when information must be retained across sustained interaction.
Two of LongMemEval's categories deserve particular attention. Knowledge updates measure whether a system correctly supersedes an outdated fact, which is the staleness failure tested directly. Abstention measures whether it declines to answer when it has no basis, and it is the only category that penalises confident fabrication rather than rewarding a lucky guess.
The metrics that localise failure operate on the retrieved set rather than the answer. Memory recall is the fraction of the records genuinely needed that retrieval actually returned; if an answer depends on three and retrieval surfaced two, no prompt change will fix the result. Memory precision is the fraction of retrieved records that were relevant. A third measure is more diagnostic than either: the proportion of retrieved memories the response never used. High recall with low precision and a large unused fraction describes a system retrieving indiscriminately and paying for it every turn, where the fix is a tighter budget rather than a better model. Measuring these separately from answer accuracy is what distinguishes an indexing problem from a retrieval problem from a reading problem.
| CONTENT TYPE | RETENTION | ON CONTRADICTION | CASCADE CONCERN |
|---|---|---|---|
| Ephemeral task state | Delete at task end | Overwrite | None; nothing derives from it |
| World observations | Short lifetime; re-verify | Replace and re-derive | High; summaries depend on these |
| Stable preferences | Indefinite | Update with provenance | Moderate |
| User corrections | Indefinite; outrank what they correct | Never overwritten by inference | Must invalidate what they contradict |
| Reflections and summaries | Tied to the lifetime of their sources | Re-derive | These are the derivatives |
Audit what your agent remembers
Run a system with memory enabled for twenty turns. Dump every write. Classify each as still-true, superseded, or never-useful. The proportion in that last category is your memory precision, and it is usually worse than anyone expects.