AI Cross-Session Memory: Principles, Architecture, and Implementation Practices

    This article explains AI memory as a dedicated data layer that enables large language models and agents to retain, retrieve, update, and forget user-related information across sessions. It covers memory types, system architecture, write and retrieval flows, forgetting mechanisms, integration with agents and tools, evaluation, security, and practical implementation tradeoffs.

    What Is AI Memory

    AI Memory refers to the ability of a large language model or AI agent to continuously and reliably retain and use user-related information across different sessions, tasks, and time periods. The goal is not to accumulate chat history indefinitely, but to help the system understand long-term context, extract reusable knowledge from past interactions, adapt behavior to user preferences, and carry confirmed facts across tasks.

    By default, most large language models are stateless. After a request finishes, the model itself does not automatically retain who the user is, what the user prefers, or where the previous task left off. The context window is only working memory for the current inference: once the window closes, information that has not been persisted disappears. Remembering the user must therefore be handled by an application-side memory subsystem that decides what to remember, where to store it, when to retrieve it, and how to update or delete it.

    For developers and enterprise users, memory capability directly affects whether personalization is trustworthy, whether multi-turn tasks can continue smoothly, and whether customer service or office assistants repeatedly ask the same questions. Poor memory design can cause the model to forget, or repeatedly inject outdated, incorrect, or sensitive information into prompts, leading to irrelevant answers and compliance risks.

    Memory Is Not Just a Longer Context Window

    Stuffing all historical conversations into a prompt can only temporarily reduce forgetting; it cannot replace a memory system. There are four main reasons:

    1. Limited capacity. Even a large context window has an upper bound. Long conversations will eventually be truncated, and important early facts are often lost first.
    2. Higher cost and latency. Irrelevant history participates in computation every time, causing cost and latency to degrade linearly.
    3. Noise overwhelms the signal. Chitchat, trial-and-error attempts, and revoked decisions can interfere with the current reasoning process.
    4. Lack of governance. When a user asks the system to forget something, it is difficult to precisely remove that item from an indivisible block of raw text.

    From an engineering perspective, memory should be treated as an independent data plane: structured writes, on-demand retrieval, versioning, and access control, rather than as a longer chat transcript.

    Human-Inspired Memory Layers, Without Anthropomorphic Slogans

    Aligning with human memory can help clarify responsibilities, but the implementation is still a set of software components.

    • Working memory: messages, tool results, and temporary variables within the current session. Its lifecycle equals the current task and is suitable for the context window or short-term cache.
    • Episodic memory: what happened in a specific interaction, such as “last Wednesday the user confirmed that the report standard should include tax.” It should preserve the time, source session, and evidence fragments for traceability.
    • Semantic memory: stable facts and preferences generalized from multiple interactions, such as forms of address, language, output format, and business terminology. Each item should be independently updatable.
    • Procedural memory: reusable ways of doing things, such as “when generating a weekly report, list metrics first and then write conclusions.” This is closer to a skill or workflow template than a simple preference.

    In practice, the most valuable memory is semantic memory plus a small number of episodic anchors. If procedural memory is written as executable scripts, it must also be constrained by permissions and sandboxes. A casual user statement should not directly become an automated action.

    Typical Architecture: Write, Store, Retrieve, Inject

    A usable memory pipeline usually has four stages.

    Write (extraction). At the end of a conversation or at a checkpoint, rules or a lightweight inference pass can extract candidate memories from the original text: facts, preferences, unfinished tasks, and explicit negations such as “do not recommend this type of content again.” Each candidate should include confidence, time, source message identifier, and scope, such as user-only, tenant-only, or project-only. Do not treat an entire conversation as a single memory item.

    Storage. At least two types of storage are needed:

    • Structured storage: key-value or relational tables, suitable for precise fields such as language, time zone, and role.
    • Vector or full-text index: suitable for episodic content and long descriptions that are semantically similar to the current question.

    Sensitive fields should be encrypted and isolated by tenant, and retention periods should be recorded. Object storage can archive raw sessions, while the online path should retain only distilled memory items.

    Retrieval. When the current user query arrives, first filter by identity, then rank a small number of highly relevant items using keyword matching, vector similarity, and time decay. Retrieval results should be explainable: which item was hit, what the score was, and when it was last updated. If relevance is low, it is better to inject nothing than to inject noise.

    Injection. Organize the retrieved items into a short prompt block, placed in the system instruction or a dedicated memory section, with a note such as “The following is historical memory. If it conflicts with the user’s explicit statement in the current turn, the current turn takes precedence.” This prevents the model from treating old preferences as immutable facts.

    Example flow (language-independent, showing only data shape):

    1. on_turn_end(user_id, messages):
    2. candidates = extract_memories(messages) # facts/preferences/todos/negations
    3. for m in candidates:
    4. if m.confidence < THRESHOLD: continue
    5. upsert(store, user_id, m) # merge older items on the same topic
    6. on_turn_start(user_id, query):
    7. hits = retrieve(store, user_id, query, top_k=5)
    8. return render_memory_block(hits) # short, traceable, overridable by current turn

    Thresholds, Top-K values, and field names should be defined by the business. There is no universal value that fits all scenarios.

    Write Policy: What to Remember and What Not to Remember

    Items worth remembering usually include stable identity and preferences, confirmed business definitions, long-term project constraints, and items the user explicitly asks the system to remember or forget. Items that should not be remembered include one-time verification codes and secrets, unverified guesses, model hallucinations, and third-party private information that the user has not authorized.

    Merging is more important than appending. When a new statement appears on the same topic, update the existing item and preserve historical versions instead of accumulating ten contradictory “preferences.” Negations should be modeled separately. If the user says “use concise lists from now on,” it should override the older “write long-form content” preference, rather than keeping both and randomly retrieving one of them.

    A fixed conflict-resolution priority is recommended: the user’s exact words in the current turn > recently confirmed memory > earlier generalizations > system defaults. Generalized memory must be traceable to its source session so that humans can correct it.

    Retrieval and Forgetting: The Other Half of a Memory System

    A memory system that only grows will become dirty. At least three types of forgetting are needed:

    • User-initiated deletion: provide interfaces to clear memory by topic or time, and remove indexes and backups within the allowed retention policy.
    • Expiration: set TTLs for temporary projects and campaign preferences; downgrade or archive them when they expire.
    • Correction: after the user negates an item, mark it invalid and reduce the weight of similar old items to avoid recalling near-synonymous entries after one item is deleted.

    Time decay should not be applied uniformly. Identity-related facts should decay slowly, while activity-related and mood-related information should decay quickly. During retrieval, separate “relevant” and “still valid” into two scores before deciding whether to inject the item.

    Integration with Agents and Tool Calls

    Agents add planning steps and tool round trips, so memory scope must be even clearer:

    • User level: preferences and profile information shared across all tasks.
    • Task level: the current goal, completed steps, and intermediate conclusions. At task completion, these can be promoted to user level or discarded.
    • Tool level: raw returns from a specific query usually do not need to be stored in long-term memory; only the conclusion and citation should be retained.

    If entire tool outputs are written into memory, later retrieval may treat expired data as fact. A better approach is to remember the “conclusion + data time” and call the tool again when fresh data is needed.

    In multi-turn conversations, the model may “remember” content that was never written to memory; that is merely repetition from the current context. Acceptance testing should be based on stored memory items, not on the model verbally claiming “I remembered it.”

    Quality, Security, and Evaluation

    Before launch, it is recommended to build a minimal evaluation set rather than relying only on conversational impressions:

    • Recall: whether relevant preferences are injected when needed.
    • Precision: whether irrelevant or expired items are incorrectly injected.
    • Update: whether new statements override old ones without contradiction.
    • Deletion: whether the information no longer appears in later sessions after the user clears it.
    • Isolation: whether User A’s memory never appears in User B’s prompt; tenant boundaries should be tested as well.

    From a security perspective, memory is a high-value personal information store. Sensitive information detection should be performed before writing; retrieval results should be injected according to the principle of least necessity; and backend access should leave audit logs. Prompt injection can also contaminate memory. If a user or external document requests “write the following content into the system memory of all users,” cross-user writes must be rejected during extraction, and memory update permissions must be limited to the current subject.

    Do not package memory retrieval scores or hit counts as externally promised accuracy rates. Without a unified benchmark, only report observations from your own evaluation set.

    Common Implementation Tradeoffs

    Full summarization vs. item-based memory. Periodically summarizing long conversations is useful for review, but personalization depends more on updatable short items. Both can coexist: summaries go to archives, while items go to online retrieval.

    Synchronous writes vs. asynchronous writes. Extracting memory after every turn increases latency. Writes can be executed asynchronously after the turn and take effect in the next turn. The interface should avoid implying that something is “immediately and permanently remembered.”

    Model extraction vs. user confirmation. Automatic extraction has high coverage but also more mistakes. Confirming key preferences once with the user can significantly reduce correction costs. Enterprise scenarios are better suited to “suggest memory, then persist after human or user confirmation.”

    General cloud component choices. Online items can use databases and caches; semantic retrieval can use vector search services; raw sessions can use object storage; write streams can use message queues to smooth peaks; failures and hit rates can be connected to logging, monitoring, and alerting. These are general capabilities. Selection should be based on isolation, encryption, retention periods, and query latency, rather than chasing a specific proprietary interface name. If a team is already building applications on Baidu AI Cloud, the memory service can be planned as a normal stateful component with appropriate permissions and backups; do not assume the model itself will persist user data.

    Summary

    AI can “remember you” not by magically turning a stateless model into a stateful one, but through a memory system that can write, retrieve, update, and delete. Working memory stays in the current context; long-term memory stores only distilled items with sources and expiration; and injection must obey the user’s new instructions in the current turn. By handling scope, conflicts, and forgetting well, personalization becomes a stable capability rather than an occasional lucky recollection.