Building AI Agents with Long-Term Memory: An Open-Source Framework Architecture

    This article breaks down how to build AI agents with long-term memory, moving beyond stateless tool callers to collaborative systems that retain context across sessions. It presents a five-layer reference architecture, details the three-tier memory structure and its lifecycle, and explains hybrid retrieval and context engineering. It also covers turning execution traces into reusable skill cards, deployment, evaluation, cost control, and common pitfalls to avoid.

    1. From Tool Callers to Interns: The Agent Paradigm Is Shifting

    Over the past two years, AI agents have moved from demos into production. The core problem they expose is not that models are not smart enough, but that they cannot remember. Most early solutions are essentially stateless function callers: they receive instructions, plan steps, call tools, and return results. Once the session ends, the context is cleared. These systems perform well on single tasks, but when a task spans several days and requires multiple rounds of feedback and preference accumulation, they repeatedly make the same mistakes, forcing users to restate the background over and over.

    The industry has therefore proposed a second paradigm: treating the agent as a collaborator that grows alongside the user. The key difference is whether the agent has controllable, retrievable, and updatable long-term memory, and whether it converts historical execution traces into priors for later decisions. This article uses the phenomenon of an open-source agent framework that gained popularity quickly as a starting point, strips away product-specific attributes, and abstracts a transferable technical skeleton for building similar capabilities in your own environment. It does not discuss any proprietary features of a specific project, only widely accepted industry practices.

    2. Capability Layers: A Practical Reference Architecture

    Splitting an agent into five layers helps turn “memory” from a slogan into an engineering object.

    1. Model layer: handles reasoning and generation, typically invoked through an inference service interface, supporting streaming output and function calling.
    2. Orchestration layer: task decomposition, plan generation, retry and rollback, and parallel branch management.
    3. Tool layer: file read/write, terminal commands, retrieval, database access, and external API calls, all registered with schema-based descriptions.
    4. Memory layer: writing, retrieval, compression, and invalidation of short-term context, working memory, and long-term memory.
    5. Governance layer: permissions, auditing, cost, evaluation, and canary releases.

    The following is a schematic of the memory write and retrieval logic (it expresses structure only, not any product interface):

    1. def remember(agent, episode):
    2. # 1) Structured extraction: goal, steps, tools, result, user feedback
    3. record = extract_episode(episode)
    4. # 2) Scoring and deduplication: low-value or duplicate content is not stored
    5. if score(record) < THRESHOLD or is_duplicate(record):
    6. return
    7. # 3) Layered write: summary goes to the long-term store, raw text to object storage
    8. long_term.upsert(embed(record.summary), record.meta)
    9. object_store.put(record.raw)

    3. The Three-Tier Memory Structure and Its Lifecycle

    Short-term memory is the current session window. Its capacity is limited, so it relies on a sliding window and summary compression to stay manageable. Working memory holds intermediate artifacts of the current task, such as confirmed API contracts and hypotheses awaiting validation. Long-term memory stores stable preferences, project conventions, and historical conclusions that persist across sessions.

    Lifecycle management matters more than writing. Every memory entry should carry its source, timestamp, confidence, and scope of applicability, and support three operations: merge (aggregating fragmented conclusions into a single rule), downweight (reducing credibility when it conflicts with recent facts), and invalidate (deleting entries that are outdated or disproven). A memory system without an invalidation mechanism is quickly polluted by noise, which shows up as an agent “stubbornly sticking to old approaches.”

    4. Retrieval and Context Engineering: The Details That Decide Success

    Long-term memory is usually dominated by vector retrieval, but pure vector recall performs poorly on proper nouns, version numbers, and error codes. In practice, hybrid retrieval is more reliable: keyword recall ensures exact matches, vector recall handles semantic generalization, and a reranking model then scores everything uniformly.

    For context organization, follow the principle of “stable first, volatile last”: place system constraints and long-term rules at the front, task-relevant fragments in the middle, and the user’s latest instruction at the end to reduce the chance of instructions being drowned out. Also set a budget cap and trim and deduplicate retrieval results to avoid the latency and cost increases that come with context bloat.

    5. From Experience to Skills: Turning Traces into Reusable Capabilities

    The highest form of memory is not “remembering the answer” but “forming a method.” A practical approach is to abstract successful traces into skill cards that include trigger conditions, prechecks, step sequences, failure fallbacks, and acceptance criteria, and to bring them under version control as ordinary files that take effect after review. This makes skills testable and rollback-friendly, and easy for teams to share.

    1. skill: batch data validation
    2. trigger: user asks to verify incremental data consistency
    3. precheck: target table is accessible with read-only permission
    4. steps: [sampling, primary key comparison, output diff report]
    5. rollback: keep the original snapshot
    6. acceptance: each diff row can be traced individually

    6. Engineering in Practice: Deployment, Evaluation, and Cost

    For deployment, container platforms host stateless orchestration processes, object storage holds raw traces and artifacts, message queues decouple long-running tasks, logging services and monitoring alerts provide observability, and keys are managed by a dedicated credential management mechanism. Baidu AI Cloud offers corresponding capabilities across these general categories, which can be combined as needed to avoid tightly coupling business logic with infrastructure.

    Evaluation must come first. It is recommended to build three types of benchmarks: task success rate, step efficiency (number of steps and tool calls), and memory effectiveness (whether cross-session reuse reduces repeated communication). Rollout should use canary releases and dual-track comparison, with a rollback switch kept in place.

    Cost control depends on three things: small models handle summarization and classification while large models handle only critical reasoning; retrieval results are trimmed to a budget; and repeated requests are served from a result cache. Security and compliance cannot be skipped either: tool calls need least-privilege access and human confirmation boundaries, sensitive data must be masked before entering memory, and the full chain should be logged to support auditing.

    7. Common Pitfalls and an Implementation Checklist

    Common pitfalls include stuffing all history into the context, writing without ever deleting, lacking an evaluation baseline, and giving the agent overly broad execution permissions. The corresponding implementation checklist is: define the memory schema and invalidation policy, build hybrid retrieval and reranking, accumulate reviewable skill cards, set up the three evaluation metrics, complete permissions and auditing, and set cost and latency caps. Following this order, a team can build a maintainable, extensible agent system within weeks that genuinely gets more useful the more it is used.