Memory in Open-Source AI Agent Frameworks: Architecture, Retrieval, and Evaluation

    This article breaks down what it takes to build open-source AI agents with memory, moving beyond stateless tool-style calls toward systems that accumulate reusable experience. It defines four capability gaps between memory-enabled and tool-only agents, presents a layered reference architecture (working, episodic, semantic, and procedural memory) with write and recall pipelines, and covers context engineering, evaluation metrics, storage and operations, and common anti-patterns. The guidance is product-agnostic and maps to general cloud capabilities such as container platforms, object storage, message queues, and observability services.

    1. From Tool Runner to Intern: Why Agents Need Memory

    A common gap shows up in agent engineering practice: demos look impressive, but long-running behavior is disappointing. The reason is that most implementations are essentially stateless calls—the model receives a prompt, returns a result, and discards the context. Such systems behave like a “tool runner”: they do exactly what you ask and forget it immediately, so yesterday’s successful experience cannot carry over to today.

    An agent that “grows with you” instead turns every interaction into a searchable, reusable, and correctable experience asset. By analogy, the former is a temp worker who needs to be briefed from scratch on every shift, while the latter is an intern who writes down business rules, your preferences, and the pitfalls already encountered. This is not a prompt-engineering trick but an architecture problem: memory must be a first-class citizen of the system, with storage, retrieval, updating, forgetting, and permission boundaries.

    To be clear, this article does not evaluate or recommend any specific framework. Instead, it abstracts the common technical elements of these “open-source agents with memory” and discusses how to build them solidly with general engineering practices.

    2. Capability Boundaries: Four Differences Between Memory-Enabled and Tool-Only Agents

    1. State continuity: For tool-only systems, the session is the endpoint; memory-enabled systems treat each session as a write opportunity and preserve task context across sessions.
    2. Reusable experience: Tool-only systems reason from zero every time; memory-enabled systems can recall successful historical paths, reducing repeated trial and error and redundant tool calls.
    3. Correctability: A user correction should remain effective over the long term. Memory-enabled systems turn “do not do this” into a persistent preference constraint instead of losing it in the next conversation.
    4. Governability: Memory introduces privacy and compliance pressure, so it must be paired with tiered storage, redaction, access control, and deletion capability.

    These four points shift the engineering focus from “tuning prompts” to “designing the memory subsystem.”

    3. Reference Architecture: Layered Memory and Retrieval Paths

    A robust approach is to split memory into four layers, each treated differently in terms of lifecycle, access frequency, and consistency requirements:

    • Working memory: short-term context for the current task, reclaimed when the session ends.
    • Episodic memory: what happened, such as the steps and outcome of a troubleshooting session, used to recall similar problems.
    • Semantic memory: abstracted stable facts, such as coding standards, API conventions, and team terminology.
    • Procedural memory: executable strategies and tool-usage patterns, usually expressed as “trigger condition + step template.”

    For the write path, use an “extract—validate—deduplicate—classify—store” pipeline. For the read path, use an “intent recognition—multi-path recall—rerank—budget trimming—injection” sequence. The sample code below only expresses the structure and is not bound to any specific product interface:

    1. def remember(raw_turn, profile):
    2. facts = extract_facts(raw_turn) # Extract candidate memories
    3. facts = [f for f in facts if not is_sensitive(f, profile)]
    4. facts = dedup_and_merge(facts, profile) # Merge and deduplicate with existing memory
    5. for f in facts:
    6. store.write(layer=classify(f), text=f, tags=profile.tags)
    7. return facts
    8. def recall(query, budget=4000):
    9. cands = []
    10. for layer in ("episodic", "semantic", "procedural"):
    11. cands += store.search(layer, query, limit=20)
    12. ranked = rerank(query, cands) # Relevance + recency + confidence
    13. return fit_budget(ranked, budget) # Trim by token budget

    4. Context Engineering: Making Memory Actually Useful

    Writing memory in is only the first step; retrieving it at the right moment is what separates effective systems from ineffective ones. Three practices deliver the highest returns:

    • Structured entries: each memory carries a type, confidence, source, timestamp, and applicable scope, avoiding a “one-pot” concatenation.
    • Recency decay and conflict resolution: when new evidence overrides an old conclusion, keep the version history and explicitly mark conflicting items instead of silently overwriting them.
    • Budget awareness: context is a scarce resource, so allocate separate quotas for instructions, retrieved snippets, and tool outputs to prevent critical instructions from being drowned out by historical content.

    A minimal working prompt assembly order:

    1. [System constraints and safety policies]
    2. [Long-term preferences and hard rules]
    3. [Relevant memories recalled for this turn]
    4. [Current task instructions]
    5. [Tool return results]

    5. Evaluation: How to Prove It Gets Better with Use

    “Growing together” must be measurable, otherwise it is just narrative. Establish at least three categories of metrics:

    1. Task success rate and step count: the change in success rate for similar tasks before and after memory accumulation, and the reduction in average tool calls.
    2. Repeated correction rate: the proportion of the same type of error corrected by the user again, which directly reflects whether procedural memory is working.
    3. Recall quality: recall hit rate, share of irrelevant snippets, and context waste rate.

    Evaluation must guard against two traps: memory pollution, where wrong experiences are repeatedly recalled and amplified; and leakage, where evaluation set content enters the memory store and inflates scores. A practical approach is to build an isolated environment for evaluation and to perform periodic audits and sampled reviews of the memory store.

    6. Engineering Implementation: Storage, Retrieval, and Operations

    • Storage selection: structured metadata fits relational storage, vectorized snippets fit vector search capability, and raw text and attachments go into object storage, forming a “metadata + vector + raw text” trio.
    • Asynchronous writes: place memory extraction on an asynchronous path after task completion, using a message queue to smooth peaks and avoid slowing down the main interaction latency.
    • Observability: include recall details, hit snippets, and injected token counts in logging services and monitoring alerts so that regressions can be located quickly.
    • Cost and security: set capacity limits and hot/cold tiering for memory entries, redact sensitive fields before writing, and provide a memory management entry point that users can view, edit, and delete.

    In a cloud implementation, these capabilities map to general product categories: a container platform can host the agent runtime, object storage can hold raw text, a message queue can decouple writes, and logging plus monitoring and alerting can ensure observability. Specific choices should be based on compliance and cost evaluation rather than tied to a single implementation.

    7. Common Anti-Patterns

    • Full injection: stuffing all history into the context, which dilutes instructions and loses control of cost.
    • Write-only, never delete: lacking a forgetting mechanism, so expired information keeps interfering with judgment.
    • No permission isolation: sharing one memory space in multi-tenant scenarios, causing data to cross boundaries.
    • Memory replacing reasoning: treating recalled results as conclusions without validation and tool verification.

    8. Conclusion

    What goes viral overnight is never a name but a real pain point it addresses: agents must move from one-off execution to experience accumulation. Treating memory as a system design problem—layered storage, rigorous retrieval, measurable evaluation, and governable operations—gives agents the engineering foundation to become “more comfortable with use.” This path is independent of any specific product and can be mapped directly onto a combination of general cloud capabilities on Baidu AI Cloud to build an autonomous, auditable long-term memory agent system.