AI Agent Memory Architecture: A Practical Guide to Layered Memory Design

    This article explains why in-process memory falls short for production AI agents and presents a practical layered memory architecture: framework-managed short-term conversation history combined with model-managed long-term facts, unified through a shared workspace directory. It covers the overall design, file layout, interceptor-based persistence, sliding-window and summary injection, memory tools, write-quality control, and engineering details such as atomic writes, backups, concurrency, privacy, and observability. The guide also outlines a step-by-step implementation path for building agent memory that survives restarts and grows over time.

    AI Agent Memory Architecture: A Practical Guide to Layered Memory Design

    1. The Problem: Why In-Process Memory Cannot Support a Real Agent

    Most agent frameworks ship with the most basic session memory component, usually an in-process cache that holds the last few messages. This is enough for demos and unit tests, but the shortcomings surface quickly in real business scenarios:

    • Lifecycle tied to the process: Service restarts, rolling deployments, and container migration all reset the conversation history, forcing users to explain the background again and again.
    • Limited capacity and retrieval: Only a fixed number of messages or a fixed token budget is retained, so critical information from the early stages of long-running tasks is naturally evicted.
    • No accumulation across sessions: Preferences a user mentioned today, project constraints, and terminology conventions all have to be restated when a new session starts tomorrow.
    • Rigid write timing: The framework can only mechanically append messages; it cannot decide “which sentence is worth remembering long term.”

    A more robust engineering approach is therefore not to keep enlarging the cache, but to treat memory as a first-class citizen: layered, persistent, retrievable, and with clear write ownership. The following sections present a solution that can be implemented directly.

    2. Overall Design: Two Memory Layers Plus a Shared Workspace

    The core idea can be stated in one sentence: short-term memory is handled by the framework, long-term memory is decided autonomously by the model, and the two are merged through the same workspace directory.

    Layer Write owner Storage location How it is injected into the model
    Short-term conversation history Automatically appended by a framework interceptor Session files under the workspace, split by channel Recent history is injected automatically before each request
    Long-term facts and knowledge Written by the model calling tools on its own judgment An agent description file at the workspace root plus topic-based files under the memory directory The system prompt tells the model where to read, and it reads on demand

    The value of this division of labor is that the framework guarantees “nothing is lost,” while the model guarantees “nothing is redundant.” The former is deterministic logic that suits a code implementation; the latter is semantic judgment that is better left to the model.

    3. Short-Term Memory: Automatically Persisted Conversation History

    The short-term layer solves “continuity.” There are three implementation points.

    1) Isolate files by channel. Different entry points (CLI, desktop app, service calls) keep their contexts from interfering with each other, avoiding cross-talk. Example structure:

    1. workspace/
    2. ├── conversations/
    3. │ ├── chat-cli.yaml
    4. │ └── chat-desktop.yaml
    5. ├── AGENT.md
    6. └── memories/
    7. ├── user-preferences.md
    8. └── project-constraints.md

    2) Centralize writes in an interceptor. Attach a memory interceptor to the request processing chain: it assembles history on read and appends messages on write, so business code does not need to be aware of it. Pseudocode:

    1. class MemoryInterceptor implements AroundHandler {
    2. Path store = workspace.resolve("conversations/chat-" + channel + ".yaml");
    3. Object around(Request req, Chain chain) {
    4. var history = HistoryStore.load(store); // Deserialize existing turns
    5. req.context().put("history", history.recent()); // Inject the last N turns
    6. var reply = chain.proceed(req);
    7. history.append(req.userMessage(), reply.text());
    8. HistoryStore.save(store, history); // Atomic write to prevent partial files
    9. return reply;
    10. }
    11. }

    3) Control the injection budget. Injecting everything crowds out the context and raises costs. A combination of “sliding window + summary” is recommended: inject the most recent turns verbatim and compress earlier content into a bullet-point summary that is included as well. Summaries can be generated asynchronously to avoid blocking the main request path.

    4. Long-Term Memory: Let the Model Make the Write Decisions

    The long-term layer solves “accumulation.” The framework should not guess what to store; instead, it should expose tools that let the model judge value at the semantic level.

    1) Three basic tools. Read file, write file, and edit file (partial replacement). Writing and editing must follow a read-before-write rule to avoid overwriting content created by others or by earlier sessions.

    2) Directory conventions are knowledge organization. Place an agent description file at the root to record identity, conventions, and current progress; split the memory directory into topic files such as user preferences, project constraints, a glossary, and lessons from failures. The files are plain text, so they can naturally be versioned, reviewed manually, and migrated.

    3) The system prompt only gives directions. Do not stuff the prompt with facts; tell the model where to read them:

    1. You can use the read/write/edit tools to manage long-term memory.
    2. - General conventions and current progress: ./AGENT.md
    3. - User preferences: ./memories/user-preferences.md
    4. - Project constraints: ./memories/project-constraints.md
    5. Read the relevant files when you need background. When you discover a stable fact, read before editing, and keep entries short and reusable.

    4) Write quality control. Instruct the model to follow three rules: record only facts that are stable and useful across sessions; keep one fact per line with a topic prefix; rewrite existing entries rather than appending when a new fact conflicts, to prevent memory bloat and self-contradiction.

    5. Merge Mechanism and Engineering Details

    • The shared workspace is the merge point: Both layers live under the same directory tree. Short-term memory is the running log, long-term memory is the conclusions; they do not interfere with each other yet can corroborate each other.
    • Atomic writes and backups: Write to a temporary file first, then rename it; periodically sync the directory to object storage for backup, enabling recovery across instances.
    • Concurrency and multiple instances: When the same workspace is mounted by multiple replicas, use file locks or a serialized queue to avoid write conflicts; shard by session identifier when necessary.
    • Privacy and compliance: Session files may contain sensitive information, so support encrypted storage, retention-based cleanup, and deletion by user.
    • Observability: Record memory read/write counts, injected token volume, and hit rate to tune the sliding-window size and summary frequency.
    • Relationship to retrieval augmentation: Long-term memory is “small and precise” structured facts that are best read directly; large-scale document knowledge should still go through vector retrieval. The two complement rather than replace each other.
    1. Define the workspace directory and file conventions, and first get short-term persistence working for a single channel.
    2. Add the interceptor to implement automatic appending and sliding-window injection, and verify that history survives a restart.
    3. Expose the three tools (read, write, edit) and add path guidance to the system prompt.
    4. Observe the quality of what the model writes, iterate on the prompt and directory granularity, and keep memory size under control.
    5. Complete atomic writes, backups, cleanup, and monitoring, then gradually expand to multiple channels and multiple instances.

    7. Summary

    The essence of memory management is putting “determinism” and “semantic judgment” in their proper places: short-term history is automatically handled by the framework, long-term facts are accumulated autonomously by the model, and the shared workspace connects the two naturally. This layered approach does not depend on any proprietary feature of a specific framework; it can be implemented with generic files and interceptors. It can also be combined with common capabilities such as object storage, logging services, and monitoring alerts in environments like Baidu AI Cloud for persistence and operations, giving the agent memory that can be restarted, traced, and grown.