Designing a Layered Memory System for a Long-Lived LLM Agent
Machine LearningModel answerLast updated
Describe the layers of memory in a persistent LLM agent, what each holds, how it is written and read, and how the layers are managed, secured and evaluated across many sessions.
You are building an assistant that runs for months and talks to each user across many separate sessions. The model itself is stateless, so everything it "remembers" must be supplied by the surrounding system.
Question: Lay out the main components of such an agent's memory. For each component, explain:
- What kind of information it holds and how long it lives.
- How information gets written into it.
- How information is read back out and placed in front of the model.
- How the components cooperate over the agent's lifetime.
Also address how the memory stays healthy over time (merging, correcting and forgetting), how it is kept private and safe from tampering, and how you would tell whether it actually improves the agent.
Before answering, it is reasonable to state your assumptions about:
- Whether the agent serves one user or many, and whether their memories must stay separate.
- How long sessions are compared with the model's context window.
- Whether memory exists to personalize responses, to improve task success, or both.
- Whether users must be able to inspect or delete what is stored.
Hints
Hint 1
Start by splitting memory by lifetime: what lives only for one model call, what lives for one session, and what must survive across sessions. Then split long-term memory by content type (events, facts, skills).
Hint 2
For every layer, write down three policies: when to write, how to retrieve (recency, similarity, structured lookup, or always-on), and when to update or delete. Retrieval must respect a token budget.
Hint 3
Don't stop at the taxonomy. Cover contradictory facts, forgetting, per-user isolation, prompt-injection or poisoned memories, user deletion, and an ablation-style evaluation of memory on versus off.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I will assume a multi-user product, so memory is strictly partitioned per user (and per tenant). Sessions can exceed the context window, memory serves both personalization and task performance, and users can view and delete what is stored.
The components
The cleanest way to organize this is by lifetime, then by content type.
1. Working memory (the context window)
- Holds: everything the model sees right now: system prompt, tool definitions, recent turns, tool outputs, and any retrieved memories.
- Write: the orchestrator assembles the prompt each step.
- Read: the model attends to it directly.
- Management: this is the scarcest resource, so use a token budget. For example, reserve fixed shares for instructions and tools, recent turns, retrieved memory, and output. Truncate or summarize bulky tool results rather than carrying them verbatim.
2. Session (short-term) memory
- Holds: the running transcript and state of the current conversation: turns, intermediate tool results, the current plan and scratchpad.
- Write: append every turn to a per-session store (a log or key-value store).
- Read: the most recent turns go in verbatim; older turns are replaced by a rolling summary once the transcript crosses a threshold (say 60-70% of the budget).
- Trade-off: summarization saves tokens but loses detail, so keep the raw log on disk and let the agent re-fetch specifics on demand.
- Lifetime: discarded or archived at session end, after a consolidation step (below).
3. Episodic memory
- Holds: records of specific past events: "On March 3 the user asked to migrate their billing job; we tried X, it failed with Y, Z worked."
- Write: at session end (or at task milestones), an LLM or rule-based extractor produces an episode record with timestamp, participants, outcome, and a short summary. Store the summary plus metadata, and a pointer to the raw log.
- Read: hybrid retrieval: embedding similarity against the current query, filtered by metadata (user, time, task type), and re-ranked with a recency and importance score.
- Use: continuity ("last time we...") and few-shot examples of similar past tasks.
4. Semantic memory
- Holds: distilled, relatively stable facts and preferences: "prefers Python, works in UTC+1, team uses Postgres 15." It can be entity-centric, as a profile or knowledge graph, rather than a pile of text chunks.
- Write: an extraction pass over conversations proposes candidate facts with confidence and source. A reconciliation step compares each candidate to existing entries and decides to add, update, merge, or ignore.
- Read: a small, high-value profile can be always injected; the rest is retrieved by key or by embedding when relevant.
- Conflict handling: newer explicit statements usually win, but keep history (valid-from / valid-to, or a superseded flag) so you can audit and roll back. Ask the user when a conflict is high stakes.
5. Procedural memory
- Holds: how to do things: refined instructions, tool-use recipes, reusable workflows, learned rules ("always run the linter before committing in this repo").
- Write: from successful trajectories or explicit user feedback, distill a reusable procedure. Gate changes behind review or evaluation because this memory alters behavior.
- Read: retrieved by task type, or merged into the system prompt. Can also be stored as code or tool definitions.
- Risk: a bad procedure affects every future run, so version it and keep it testable.
Optional: external knowledge
Documents, tickets and databases accessed via RAG are sometimes counted separately. They are shared and not learned from the user, which is why they should not be mixed into per-user memory stores.
How the layers work together
- A request arrives. The orchestrator loads the user profile (semantic) and runs retrieval over episodic and procedural stores using the query and session state.
- Candidates are scored (similarity x recency x importance), deduplicated, and packed into the retrieval slice of the token budget, with source labels.
- The model responds; the turn is appended to session memory.
- At milestones and session end, a consolidation job summarizes the session into an episode, extracts facts into semantic memory, and proposes procedural updates.
Writes can be done on the hot path (cheap, explicit "remember this") or asynchronously (extraction and consolidation), which keeps latency low.
Keeping memory healthy
- Consolidation: periodically merge near-duplicate episodes and roll old ones into higher-level summaries.
- Updating: treat facts as versioned records, not append-only text.
- Forgetting: use time decay, usage-based retention (items never retrieved expire), TTLs for sensitive categories, and hard deletion on user request, including derived embeddings and summaries.
- Retrieval quality: tune top-k and a minimum-score cutoff. Injecting irrelevant memories is worse than injecting none.
Privacy and security
- Partition by user ID at the storage and query layer, not just in the prompt; test for cross-user leakage.
- Encrypt at rest, minimize what is stored, avoid saving secrets or sensitive categories unless needed.
- Memory poisoning: content from web pages or tool outputs can contain instructions that get saved and replayed later. Mitigate by recording provenance, treating retrieved memory as untrusted data rather than instructions, restricting what sources may write to procedural memory, and requiring confirmation for high-impact memories.
- Give users a way to view, edit and delete memories.
Evaluation
- Offline: build multi-session test scripts with planted facts, then measure recall, correct updates after contradictions, and abstention when a fact is absent.
- Retrieval metrics: precision@k and recall@k of the memories surfaced.
- End to end: A/B or ablation (memory on vs off) on task success, user satisfaction, and cost/latency, with tokens spent on memory tracked.
- Safety: red-team for injection and cross-user leaks.
Common mistakes
- Treating "memory" as just a vector database of raw chat chunks.
- Never updating or deleting, so stale facts keep resurfacing.
- Stuffing too many memories into the prompt, crowding out the task.
- Ignoring isolation and poisoning.
- No measurement of whether memory helps.