Long-Term Memory Architecture for AI Agents: Offline “Dreaming” to Consolidate Interaction Experience

    This article describes a layered long-term memory architecture for AI agents that separates raw interaction logs, memory notes, memory representations, and context injection. It explains how offline consolidation—replaying, verifying, merging, correcting, and forgetting memories—can turn interaction experience into reusable knowledge without modifying model weights. It also covers memory scoring, evaluation metrics, and enterprise concerns such as permissions, sensitive data, auditability, and service decoupling.

    In complex tasks, an AI agent must do more than understand the current conversation. It also needs to remember user preferences, prior decisions, verified facts, and the causes of failures in past tasks. If every session starts from zero, the system can hardly develop a capacity for continuous improvement. But if all historical records are pushed back into context as-is, the system faces problems such as overly long context, increased retrieval noise, and repeated propagation of errors.

    A more reasonable approach is to design agent memory as a readable and writable information system that is independent of model parameters. The online interaction phase captures facts and events. The offline phase uses idle compute to replay history, verify content, merge duplicate information, and organize high-value experience into context that can be retrieved directly in the next task. This offline consolidation process can be understood as the agent “dreaming.”

    1. Long-Term Memory Is Not the Same as Expanding Context

    In engineering practice, several capabilities are often confused with one another.

    The first is single-session context. A model can use historical messages in the current window to maintain coherence, but after the session ends, this information usually does not automatically become long-term knowledge.

    The second is context compression. A system can summarize a long conversation into a shorter summary and use it to replace older messages. This reduces context length, but it does not necessarily produce a reusable and verifiable knowledge structure.

    The third is model parameter updates. Training or fine-tuning can change model weights and give the model more stable behavioral patterns. However, this approach is costly, slow, and unsuitable for frequently writing user-level facts.

    The fourth is agent memory. The system extracts information from tasks and user interactions and stores it as text, structured records, or vector indexes. In later sessions, it retrieves this information and injects it into context. This approach does not require modifying model weights, nor does it depend on retaining the full history of conversations. Instead, it establishes an independent mechanism for managing experience.

    Therefore, the core of long-term memory is not “storing more.” It is answering four questions:

    1. What information is worth saving?
    2. Is the saved information reliable?
    3. In which future scenarios should it be retrieved?
    4. When facts change, how should old memories be updated or invalidated?

    2. Layered Architecture: From Raw Records to Usable Knowledge

    A scalable memory system can usually be divided into four layers.

    2.1 Raw Interaction Records

    This layer stores raw information such as conversations, tool calls, task results, user feedback, and system events. Its value lies in preserving complete evidence for later tracing and re-analysis.

    Raw records are not suitable for direct injection into model context for several reasons:

    • The volume of information keeps growing.
    • The same fact may be expressed repeatedly.
    • Records contain guesses, errors, and temporary conclusions.
    • Historical content may not be relevant to the current task.
    • Sensitive information may be propagated indiscriminately.

    As a result, raw records are more like an archive than a knowledge base that the model reads directly during every task.

    2.2 Memory Notes

    During online interaction, an agent can generate short notes, such as explicit user preferences, confirmed business rules, causes of task failures, and reusable operating procedures.

    This layer emphasizes timeliness, but it does not mean that every note is already correct. To avoid presenting guesses as facts, it is advisable to add necessary metadata to each note:

    1. Content: The user wants all monetary amounts in reports to use RMB as the unified unit
    2. Source: Explicit user request
    3. Status: Confirmed
    4. Time: Most recent relevant session
    5. Scope: Report generation tasks
    6. Confidence: High

    For content that has not yet been verified, the system can explicitly mark it as “pending confirmation” or “inferred” instead of writing it directly as a deterministic rule. This allows later offline processing to prioritize high-risk, low-confidence information for review.

    2.3 Memory Representation

    As the number of notes increases, the system needs to further merge and abstract them. For example, multiple sessions may separately record a user’s requirements for format, language, and output order. Offline processing can integrate them into a more stable description of preferences.

    This layer usually includes:

    • Fact memory: objective information that has been confirmed.
    • Preference memory: long-term stable expression or operation preferences of the user.
    • Procedural memory: steps and strategies for completing a type of task.
    • Correction memory: past problems and methods for avoiding them.
    • Relationship memory: associations among entities, events, time, and conditions.

    The representation layer should not be a simple summary. It should preserve applicable conditions, evidence sources, and time ranges as much as possible. For example, “the user does not like tables” is too absolute. A more precise expression might be: “In quick communication scenarios, the user prefers bullet points; in data comparison tasks, tables are still acceptable.”

    2.4 Context Injection

    Finally, the system needs to select a small number of the most relevant memories based on the current task and inject them into context in a form that the model can easily understand. The injection process should consider at least relevance, reliability, timeliness, and conflicts.

    A simple scoring approach can be expressed as:

    1. Memory score =
    2. relevance × reliability × timeliness × scope match

    High-scoring memories enter context first, while low-scoring or conflicting records enter a review process. For contradictory content, the system should not simply overwrite based on write time. It should also assess source credibility and applicable conditions.

    3. The “Dreaming” Mechanism: Using Idle Compute for Memory Consolidation

    Online interaction prioritizes low latency. An agent usually does not deeply reorganize all history after every response. A more suitable approach is to place complex processing in session intervals or background tasks.

    Offline processing can include the following steps.

    Step 1: Replay Recent Events

    The system extracts recent interaction fragments from raw logs, focusing on user corrections, task failures, tool return results, explicit confirmations, and recurring behavioral patterns.

    Replay is not mechanical repetition. It means asking again:

    • Was the conclusion at that time correct?
    • Which information was reused in later tasks?
    • Which errors caused user dissatisfaction or task failure?
    • Is there a rule that can be generalized?

    Step 2: Identify High-Value Experience

    Memory value can be evaluated from multiple dimensions:

    • Probability of future reuse.
    • Degree of impact on task outcomes.
    • Whether the user explicitly confirmed it.
    • Whether it can be transferred to multiple similar tasks.
    • Whether saving it can reduce repeated reasoning.
    • Potential risk of error propagation.

    For example, a one-time wording change may not be worth saving long term. In contrast, a user’s long-term output format requirements and verified business constraints are better candidates for long-term memory.

    Step 3: Verification and Correction

    The offline phase should actively distinguish between “facts” and “model guesses.” If a note comes from model inference but has not been verified by the user or a tool result, it should not be directly promoted to a stable rule.

    The following graded statuses can be used:

    • Unverified: candidate memory only.
    • Partially verified: valid in limited scenarios.
    • Confirmed: supported by explicit feedback or reliable results.
    • Expired: once valid, but current conditions may have changed.
    • Conflicted: inconsistent with newer information and requiring human or rule-based arbitration.

    Step 4: Merge and Rewrite

    When multiple notes describe the same topic, the system can generate a more compact reference document while preserving the evidence chain. For example, format requirements from multiple tasks can be merged into “report output specifications,” and several failure cases can be summarized into a “risk avoidance checklist.”

    During merging, the goal should not be merely shorter text. The system should also preserve:

    • Applicable conditions.
    • Exceptions.
    • Sources and time.
    • Confidence.
    • Relationships with other memories.

    Step 5: Cleanup and Forgetting

    Long-term memory must have the ability to forget. Downranking, archiving, or deleting content that has expired, is duplicated, has low value, or carries high risk can prevent the memory store from growing without limit.

    Forgetting strategies can be based on time decay, retrieval frequency, verification status, and user-initiated modifications. For example, short-term project rules can have expiration dates; information explicitly withdrawn by the user should immediately stop being injected; content that has not been retrieved for a long time and has no stable evidence can be moved to lower-priority storage.

    4. Memory Writes Are Essentially Predictions About the Future

    When an agent decides whether to remember something now, it is actually predicting its future value.

    Writing down a verified rule means the system judges that this rule can save reasoning cost the next time a similar task appears. Recording a failure cause predicts that a similar error may recur. Saving a user preference predicts that the preference will persist across sessions.

    This also explains why a memory system cannot use only “information importance” as its criterion. It must also consider “future usability.” Even if a piece of content looks important now, it may not be a good memory if it cannot be accurately retrieved and applied in the future.

    More mature systems can evaluate memory quality in reverse based on later outcomes:

    • Memories that are frequently retrieved and improve results gain weight.
    • Memories that are retrieved and then cause errors are downweighted and trigger review.
    • Memories that have not been retrieved for a long time gradually decay.
    • Memories that are repeatedly corrected by users are marked as high risk.

    In this way, memory forms a closed loop of “write—retrieve—feedback—update.”

    5. Evaluating Long-Term Memory Requires More Than Storage Volume

    To determine whether a system truly has long-term memory capability, it is not enough to count how many notes have been saved. The following metrics matter more.

    Memory Accuracy

    Does the memory retrieved by the system match reality? Does it mistakenly treat guesses as facts?

    Memory Recall

    Can relevant information be retrieved when needed? In particular, when the wording of a question changes, can the system identify semantic associations?

    Memory Utilization

    Does retrieved content actually improve task outcomes rather than adding context noise?

    Conflict Handling

    When old and new memories are inconsistent, can the system identify the conflict, explain the reason, and choose the more applicable information?

    Long-Term Stability

    After multiple rounds of sessions, does memory remain clearly structured? Does it show duplicate accumulation, error diffusion, or generalization of irrelevant content?

    User Controllability

    Can users view, modify, withdraw, and delete relevant memories? Long-term memory is not better simply because it is more automated. Transparency and controllability are equally important.

    6. Key Considerations for Enterprise Deployment

    In real systems, memory architecture also involves security, permissions, and operations.

    First, layered permissions should be implemented. Memories belonging to different users, projects, and organizations must be isolated. They should not be mixed across scopes simply because they are semantically similar.

    Second, sensitive information governance should be implemented. Identity documents, account credentials, internal confidential information, and similar content should not be written into long-term memory by default. When necessary, such content should be identified, redacted, or blocked before writing.

    Third, audit records should be retained. The system should be able to answer when a memory was created, where it came from, who modified it, when it was retrieved, and why it appeared in the current context.

    In addition, the memory service is best decoupled from the main task. Raw logs can be stored in persistent storage. Background consolidation can be executed asynchronously through a task queue. The retrieval service returns candidate memories according to permissions. The monitoring system tracks metrics such as write failures, retrieval latency, conflict rate, and abnormal growth.

    Conclusion

    Long-term memory for AI agents is not simply about saving historical conversations. It is a continuously operating information processing system. The online phase observes and records. The offline phase replays, verifies, summarizes, corrects, and forgets. The next task then selectively injects memories based on relevance and credibility.

    The technical core of the “background dreaming” metaphor is the use of non-real-time compute resources to consolidate experience, allowing the agent to extract reusable knowledge from repeated interactions. A truly high-quality memory system must remember well and apply accurately. It must accumulate experience while identifying errors. It must support automated evolution while giving users clear rights to view, modify, and delete memories. Only with such a closed loop can cross-session memory evolve from a concept into a reliable engineering capability.