AI Agent Memory Architecture: Working, Episodic, and Semantic Memory
Design AI agent memory with clear working state, durable facts, episodic records, retrieval boundaries, conflict resolution, expiry, and reliable deletion.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
An agent that remembers everything can still remember the wrong thing. A shipping preference from last year can override a correction from today. A summary can turn a tentative suggestion into an established fact. A retrieved memory can leak information between customers even when the final answer sounds helpful.
AI agent memory architecture therefore needs more than a vector database. It needs explicit decisions about what may be retained, who may retrieve it, when it stops being true, and how it can be removed. The architecture below is an illustrative design for a business assistant, rather than a benchmarked implementation.
Separate working state from persistent knowledge
Treat working memory as the current task packet: the goal, unresolved questions, selected evidence, pending actions, and recent messages. Persist it when resumability matters, but do not assume that everything in it deserves reuse in another conversation. LangGraph makes a similar implementation distinction between thread-scoped state and cross-thread memories stored in namespaces. LangChain memory overview.
Within persistent storage, distinguish information by purpose:
| Memory class | Example | Retrieval question | Main risk |
|---|---|---|---|
| Working | Approval is pending for proposal 19 | What must happen next? | Losing execution state |
| Episodic | Proposal 12 failed because the address was incomplete | Has a similar event happened? | Generalizing from one incident |
| Semantic | This customer prefers email updates | What relevant fact is currently supported? | Treating stale preferences as permanent |
| Procedural | Approved address-change procedure, revision 7 | Which procedure applies? | Allowing observations to rewrite policy |
These categories are a useful engineering vocabulary, not evidence that an agent has human memory. They also need not imply four databases. A relational store can hold typed records while separate indexes serve different retrieval paths.
Keep action state authoritative in the workflow engine. An episodic note saying a refund succeeded is insufficient proof that money moved. Read the payment system or the action ledger. See agent loops as state machines for the boundary between execution state and descriptive context.
Define the memory record before selecting storage
A useful memory record contains a claim plus its lifecycle. The following is an illustrative application schema, not a framework API:
{
"id": "memory-319",
"tenant_id": "tenant-A",
"subject_id": "customer-42",
"kind": "semantic",
"claim_key": "contact_preference",
"value": "email",
"source_ref": "message-881",
"observed_at": "2026-11-10T09:00:00Z",
"valid_from": "2026-11-10T09:00:00Z",
"expires_at": null,
"status": "active",
"version": 3,
"sensitivity": "internal"
}
observed_at records when the system encountered evidence. valid_from records when the claim became applicable. They differ when a customer reports a change that began yesterday. An optional end time can preserve historical truth without making an old fact current.
Use claim_key for deterministic conflict handling. Without it, “email me” and “please use telephone now” can become unrelated vector neighbors rather than revisions to one preference. A confidence value may help prioritize review, but an uncalibrated model score should not decide authority.
Store references to source material rather than duplicating sensitive transcripts into every memory record. Ensure those references remain resolvable only for authorized callers. Record extractor and schema versions so a later correction can identify affected records.
Make writes an explicit pipeline
A proposed write should pass through extraction, validation, authorization, conflict detection, and commit. A model can propose a memory; application code decides whether the proposal becomes durable.
For the hypothetical assistant, accept an explicit preference stated by the authenticated customer. Reject an inferred preference based solely on browsing behavior. Quarantine an instruction embedded in a retrieved webpage that tells the agent to remember a new payment destination. Provenance and caller authority matter more than fluent wording.
Choose synchronous writes for facts the next interaction must immediately observe, such as a confirmed preference correction. Background extraction can reduce response-path work for lower-priority episode summaries, but it creates a delay during which readers may see the old state. Give every asynchronous job the source event identifier and expected record version; duplicate delivery should not create duplicate memories.
Do not let an agent silently promote an episode into a global procedure. A successful workaround can reflect an exceptional permission, outdated software, or luck. Route proposed procedural changes through the same review and versioning process as application configuration.
Retrieve evidence into a bounded context packet
A retrieval pipeline should narrow the eligible set before ranking it: tenant, subject, caller access, memory type, active status, and validity interval. Then rank by relevance and task-specific utility. Filtering only after global similarity search can lose authorized candidates when unauthorized neighbors occupy the result window.
MemGPT studies management of information across memory tiers under a finite context window. Its architectural lesson is that stored information and information currently available to the model are different resources; it does not establish a universal retrieval policy for business agents. MemGPT paper.
For this design, assemble a packet with a few current facts, relevant episodes, and links to authoritative procedures. Keep each memory's identifier, source, and timestamp attached. Put contradictory evidence in separate entries rather than asking a summary to quietly reconcile it.
The Generative Agents research combines recorded experiences, reflection, and dynamic retrieval in a simulated social environment. That is a useful research reference for separating observations from derived reflections, but its simulated believability outcomes do not demonstrate correctness for customer operations. Generative Agents paper.
A practical ranking mistake is to reward recently accessed memories indefinitely. Frequent retrieval can make an obsolete item appear important. Track access recency separately from evidence freshness. Evaluate the packet that reaches the model, not merely the nearest-neighbor results. Context window management covers the next selection boundary.
Handle corrections, expiry, and deletion differently
Consider this hypothetical sequence:
- A customer requests telephone updates in January.
- In November, the same authenticated customer explicitly requests email instead.
- A delayed January extraction job arrives after the November correction.
The old job must not win because it was processed last. Resolve by evidence authority and applicable time, with a conditional version update to prevent racing commits. Retain the old preference as superseded history only if the product has a justified retention need.
If two authorized sources conflict without a clear ordering, mark the claim disputed and request clarification. Do not combine incompatible preferences into a confident sentence. For high-impact facts such as bank details, fresh verification should replace recall before acting.
Expiry is different from deletion. An expired memory should stop influencing current decisions even if a retention policy permits historical storage. An explicit deletion request requires a coordinated removal process across raw records, embeddings, summaries, caches, and any derived memory that still contains the information.
Maintain dependency references from derived summaries to contributing records. If a deleted source influenced a summary, regenerate that summary from the remaining eligible sources or remove it. Simply deleting the original embedding leaves the copied claim alive elsewhere. For implementation details, connect memory lifecycle to retrieval freshness and deletion consistency.
Enforce isolation outside the prompt
A namespace is a storage organization mechanism; authorization must still be enforced. Resolve tenant and subject identifiers from trusted application identity, rather than accepting them from an unconstrained model argument.
PostgreSQL row-level security can restrict visible and writable rows, with default-deny behavior when enabled without an applicable policy. Its documentation also identifies important bypass cases, including superusers, roles with BYPASSRLS, and ordinarily table owners. A connection role that bypasses policies defeats an otherwise plausible isolation design. PostgreSQL row security.
For this assistant, use an application role subject to the intended policies, test access through the actual connection pool, and validate identity handling on reused connections. Apply equivalent checks to vector searches, exports, background writers, and administrative tools. Never present a remembered secret as ordinary context when the task can instead reference an authorized secret manager operation.
Validate memory behavior with adversarial sequences
LangGraph's memory guide documents checkpointers for conversation persistence and separate long-term storage, including database-backed production persistence. Those primitives provide storage behavior; application tests still need to establish correctness for a chosen lifecycle. LangGraph memory guide.
Build sequence-based evaluation cases rather than isolated recall questions:
- Correct a preference, then replay a delayed old write.
- Ask an unrelated task and verify that private episodes stay out of context.
- Delete a source and inspect both search results and regenerated summaries.
- Restart between memory commit and response delivery; check for duplicate records.
- Present two conflicting authoritative facts and expect clarification.
Measure supported recall, stale-fact usage, unauthorized retrieval, deletion completion, and task outcome. Compare against a no-memory baseline: persistence earns its complexity only when it improves the actual task without unacceptable retention or isolation failures.
Frequently asked questions
Does every AI agent need a vector database?
No. Key-based facts, chronological episodes, and explicit procedure identifiers may work well in a relational database. Add semantic retrieval when paraphrased queries and a sufficiently large eligible collection justify its cost and evaluation burden.
Should an agent remember every conversation?
No. Decide retention by purpose and user expectations. A task transcript may contain temporary instructions, third-party information, and speculation that should never become a durable user profile.
Can summarization replace an audit trail?
No. A summary is a derived interpretation. Keep authoritative action records and required evidence separately, subject to their own access and retention policies. Memory helps decide what to consider; it does not prove what actually happened.
Source reference list
Related reading
- Designing an AI Agent Loop as a State Machine
Design a reliable AI agent loop with explicit states, guarded transitions, bounded execution, and recovery illustrated through a support-ticket workflow.
- Agent Context Window Management: Compaction and Evidence Retention
Manage agent context windows with explicit budgets, evidence selection, recoverable compaction, provenance, and checks that preserve task constraints over time.
- RAG Freshness: Updates, Deletion, and Index Consistency
Keep RAG answers current with versioned ingestion, deletion watermarks, permission checks, and cache invalidation that survives delayed jobs and replay.