AI Agent Memory: A Layered Architecture and Implementation Guide

    Building reliable AI agent memory requires more than storing conversation history. This guide distinguishes agent memory from model-internal mechanisms and RAG, explains working, episodic, semantic, and procedural memory, and outlines practical approaches to retrieval, updates, deletion, storage, tenant isolation, evaluation, and phased implementation.

    AI agents need continuity across multi-turn tasks, separate sessions, and sometimes multiple users. The context window of a single request is not enough.

    Here, memory means information that an agent, acting as an independent execution system, stores, retrieves, updates, and reuses through externally managed storage. It does not mean knowledge encoded in model parameters. Building memory is an engineering task: deciding what to retain, where to store it, when to retrieve it, and when to forget it—and making those decisions observable and governable.

    Model-internal memory

    Model-internal memory addresses sequence modeling and context length: how attention covers longer histories and how state passes between layers. It operates during inference. Developers generally cannot create, read, update, or delete individual memory entries, nor can they guarantee consistent reuse across sessions.

    Retrieval-augmented generation

    Retrieval-augmented generation (RAG) divides external content into chunks, embeds or indexes them, and injects relevant passages into the prompt before generation.

    This approximates recall through storage and retrieval. However, conventional RAG assumes relatively static source material. It does not inherently manage questions such as whether an experience remains valid, conflicts with the current user’s information, or should replace an earlier conclusion. RAG is one implementation of memory in a broad sense, not a complete memory system.

    Agent memory

    Agent memory emphasizes information that is manageable, evolves over time, and can be reused across tasks. Facts may come from conversations, tool results, user corrections, or task summaries. The system must decide how granular entries should be, how to resolve conflicts, and when information expires.

    External memory complements the model’s internal mechanisms: the model handles immediate reasoning, while external memory maintains long-term state.

    Context engineering

    Context engineering brings these inputs together. Sliding windows, retrieved passages, user profiles, and tool results must all be trimmed, ranked, and compressed to fit a limited context window.

    A memory system should not return the entire history. It should produce the context package needed for the current decision.

    2. Organize Memory by Time Horizon and Purpose

    Short-term working memory

    Working memory covers the current task or session: recent conversation turns, unfinished subgoals, temporary variables, and intermediate tool results.

    A common implementation combines a sliding window with summaries. Keep the original text within the window, and compress older material into structured points such as goals, constraints, confirmed facts, and pending actions.

    Summaries must remain traceable to their source material. Otherwise, compression can lose critical negations or numerical details.

    Episodic memory

    Episodic memory records what happened: task trajectories, successful and unsuccessful approaches, and corrections made by the user during a task.

    It is useful for reviewing past work and supplying few-shot examples, but should not be treated as permanent truth. Store timestamps, task identifiers, and outcome labels with each entry. During retrieval, prioritize recent episodes with successful outcomes or user-confirmed results.

    Semantic memory

    Semantic memory captures stable knowledge, including user preferences, business rules, entity relationships, and verified conclusions.

    It must support updates rather than append-only storage. If a user changes a delivery address, the new entry should explicitly supersede the old one or mark it as invalid. Two conflicting addresses should not remain equally eligible for retrieval.

    Procedural memory

    Procedural memory stores reusable methods: checklists for particular support requests, parameter constraints for external systems, and troubleshooting sequences.

    It is closer to a skill or strategy than a fact. Update it cautiously. A failed attempt should not become a recommended procedure without validation or human confirmation.

    3. Manage Writing, Retrieval, Updates, and Forgetting

    Write selectively

    Do not store every sentence. Trigger memory extraction at the end of a turn or after a subtask completes. Extract entities, preferences, commitments, constraints, and conclusions while discarding greetings and repetition.

    Each entry should contain at least:

    • Content
    • Memory type
    • Source
    • Timestamp
    • Confidence
    • Scope: user, tenant, or global
    • Invalidation conditions

    Traceable sources make it possible to revoke an entry when an error is discovered.

    Retrieve using multiple signals

    Vector similarity alone is insufficient.

    • Keyword search works well for identifiers, proper names, and exact constraints.
    • Vector search helps retrieve semantically related experiences.
    • Structured filters enforce tenant isolation, time windows, and memory types.

    Ranking can combine relevance, freshness, confidence, and usage feedback. Limit the number of retrieved entries, then let context engineering trim them further. Irrelevant memories should not consume the space needed for reasoning.

    Resolve conflicts rather than simply appending

    Updates require conflict resolution. For a given key, such as a default language or approval threshold, maintain the currently valid value and retain the reason for the change.

    Model-based extraction can be wrong. High-impact fields involving permissions, monetary amounts, or identity should require higher confidence or human confirmation. A single casual conversation should not be enough to overwrite them.

    Make forgetting verifiable

    Forgetting matters as much as remembering. Use time-to-live policies, access-based decay, and explicit deletion.

    When a user requests deletion of personal information, remove it from source text, summaries, vector representations, and derived profiles. Deleting only the visible record is insufficient if retrieval can still recover the information.

    Logs and audit trails may retain records of the deletion operation, but they should not continue supplying the deleted information to generation.

    4. Coordinate Memory with RAG and Context Engineering

    Continue using RAG for relatively static knowledge bases. Policies, manuals, and API documentation are suited to chunking and versioned indexes because they change less frequently.

    Agent memory should handle dynamic state: the option a user selected previously, a rule that was rejected, or the step where the current task is blocked.

    Both can share a retrieval engine, but their indexes, permissions, and update policies should remain separate. This prevents private conversations from entering a public knowledge base and outdated manuals from being treated as user preferences.

    A suggested context assembly order is:

    1. System constraints and safety policies
    2. Current task goals
    3. Short-term working memory
    4. Retrieved semantic and episodic entries
    5. The current user input
    6. Available tool descriptions

    When the context exceeds its budget, compress episodes and merge duplicate facts before removing hard constraints.

    A simplified workflow is:

    1. End of turn -> Extract candidate memories -> Deduplicate and detect conflicts -> Store by type
    2. Start of next turn -> Filter by user/task -> Hybrid retrieval -> Rerank and truncate -> Inject into context

    5. Choose Storage and Runtime Components

    Different storage categories serve different needs:

    • Relational storage: preferences, permissions, and key-value facts requiring strong consistency
    • Document or object storage: original conversations and long summaries
    • Vector or full-text indexes: retrieval
    • Caches: frequently accessed session state

    Message queues can support asynchronous extraction so that calling an extraction model synchronously on every turn does not slow responses.

    Choose infrastructure by category—object storage, message queues, container platforms, logging, monitoring, and alerting—based on isolation, backup requirements, and retrieval latency. The architecture does not need to depend on a particular proprietary interface.

    For multi-tenant systems, attach tenant and user identifiers during both writes and retrieval. A prompt instruction telling the model not to access other users’ data is not an isolation mechanism.

    Encrypt or mask sensitive fields in storage. Tokens and identity-document numbers returned by tools should be excluded from long-term memory by default.

    6. Adapt the Design to the Use Case

    Customer support and personal assistants

    Prioritize preferences, previous support-case conclusions, and outstanding commitments. Use a somewhat longer short-term window, and ensure semantic memory supports replacement of outdated values.

    Evaluate whether users still have to repeat the same constraints.

    Research and coding agents

    Episodic memory is especially valuable for recording attempted approaches and failure reasons, helping agents avoid repeating unsuccessful work.

    Procedural memory should contain only validated steps. Do not store code or secrets verbatim in long-term memory.

    Enterprise workflow agents

    Semantic memory often comes from policies and approval outcomes. Writing this information should require stricter authorization than ordinary conversation-based extraction.

    Define scopes before sharing information across departments, and keep data isolated within tenant boundaries by default.

    7. Evaluate More Than Whether the Agent “Seems to Remember”

    Functional evaluation should check four things:

    1. Was information that should be remembered actually stored?
    2. Was information that should not be remembered blocked?
    3. Were conflicting entries correctly superseded?
    4. Is deleted information no longer retrievable?

    Use a fixed task set to assess quality. Test whether the agent continues to respect user constraints across sessions, misuses expired facts, or retrieves unrelated people’s information.

    Operational metrics should include extraction latency, retrieval time, context consumption, and storage growth.

    When memory quality deteriorates, inspect scope filters and conflict-resolution policies first, then examine embedding models or chunking. Increasing the number of retrieved entries can conceal errors rather than fix them.

    8. Implement in Stages

    A practical implementation sequence is:

    1. Start with a short-term window and session summaries to maintain continuity within a task.
    2. Add user-isolated semantic memory and explicit deletion.
    3. Introduce episodic memory and hybrid retrieval.
    4. Add procedural memory, auditing, and automated evaluation.

    Every stage should be possible to disable or roll back. Incorrect memory is harder to diagnose than missing memory.

    For teams already using general-purpose object storage, vector retrieval, message queues, and logging or monitoring on Baidu AI Cloud, raw task traces, indexes, and asynchronous extraction can be separated across components. However, memory policies—what to write, how to replace existing information, and how to delete it—must remain explicit in the application layer. Infrastructure alone does not become an agent memory system.

    Agent memory is not an ever-growing chat history placed into a prompt. Layered storage, controlled updates, verifiable forgetting, and disciplined context assembly allow agents to reuse experience reliably over long-running tasks rather than occasionally recalling an old remark by chance.