AI Agent Memory and Self-Evolution: A Technical Breakdown

    This article explains why unreliable long-term memory is a core bottleneck for AI agents and how to address it. It traces high token consumption and poor stability to the same root cause, then presents a layered memory architecture spanning working, session, long-term, and skill memory, along with on-demand retrieval practices. It also covers turning repeated workflows into reusable skills, prioritizing deterministic tools over UI automation, retry strategies by error type, and the observability metrics and cost controls needed to keep agent systems stable and efficient.

    1. Introduction: Why Poor Memory Is a Core Agent Bottleneck

    Agent systems with persistent memory and self-iteration capabilities have recently drawn significant attention. A recurring pain point in these discussions comes down to a deceptively simple problem: agents lack reliable long-term memory, so every task starts roughly from scratch.

    This is not mysterious from an engineering standpoint. Take a conversational agent as an example. If the context lives only inside a single session window, then once the session ends or the window is compressed, all previously aligned constraints, pitfalls already encountered, and tuned parameters are lost. Users have to restate preconditions, and the agent repeats the same trial-and-error. Three typical symptoms emerge:

    • Repeated work: Preconditions for complex tasks must be stated over and over, equivalent to onboarding a new hire hundreds of times.
    • Out-of-control cost: Repeated reasoning and retries fill the context with redundant instructions and correction messages, significantly inflating token consumption.
    • Random instability: The same task may pass today and break tomorrow, with failure causes hard to pinpoint.

    It is worth stressing that blaming these problems simply on the model “not being smart enough” is a misdiagnosis. The real structural defect is that the agent lacks a layered memory system and relies heavily on low-quality, non-deterministic tools to do work that should be handled by deterministic ones.

    2. Root Cause: The Shared Origin of Token Consumption and Poor Stability

    Common agent frameworks in the industry have long been dogged by two kinds of feedback: invocation cost is too high, and long-running sessions tend to stall, lose connection, or crash. On the surface these look like two independent problems, but breaking them down reveals they often share the same source.

    A typical scenario is web automation. Many systems look “smart,” but in practice spend most of their time in a loop of “read the page — guess the state — click a control — discover a failure — replan — try again.” Each iteration stuffs the page structure, action history, and failure reasons back into the context, so:

    1. Context grows linearly, and token cost rises non-linearly with the number of retries;
    2. Minor changes in page structure or network state can break the reasoning chain, causing the task to lose connection midway;
    3. Failure signals are natural-language descriptions rather than structured error codes, leaving replanning without a reliable basis.

    The conclusion is clear: improving model capability cannot fix this at the root. If skills can evolve autonomously but the underlying tools remain fragile, all you evolve is a “loop that is better at retrying.” The right direction is to complete the deterministic tool layer — hand what can be determined to code, and leave what requires judgment to the model.

    3. Layered Memory Architecture: From Session Cache to Long-Term Assets

    Reliable memory is not about piling unlimited conversation history into the context, but about managing it in layers by lifecycle. A practical layered scheme looks like this:

    Layer Lifecycle Storage Form Typical Content
    Working memory Single task turn Context window Current goal, completed steps
    Session memory Single session Session state store User preferences, temporary constraints
    Long-term memory Cross-session Vector retrieval store + structured store Domain knowledge, historical conclusions
    Skill memory Permanent Code repository/script library Reusable workflows, parameter templates

    The key design principle is “retrieve on demand” rather than “inject everything.” Long-term memory should be fetched through a retrieval interface by similarity to pull back a small number of relevant fragments, avoiding stuffing entire history into the prompt. Illustrative logic:

    1. def build_context(task, session_id, top_k=5):
    2. # 1. Inject only the working memory required for the current task
    3. ctx = [f"Current goal: {task}"]
    4. # 2. Session-level preferences; small enough to inject in full
    5. ctx += load_session_prefs(session_id)
    6. # 3. Retrieve long-term memory on demand to control injection size
    7. for item in retrieve(task, top_k=top_k):
    8. ctx.append(f"Historical conclusion: {item.text}")
    9. # 4. If a skill matches, call the deterministic script directly instead of re-reasoning
    10. skill = match_skill(task)
    11. if skill:
    12. return ctx, skill.entrypoint
    13. return ctx, None

    Engineering also requires three additional constraints: memory writes need deduplication and conflict resolution to avoid multiple contradictory versions of the same constraint; memory should carry source and confidence, and low-confidence content must not directly influence critical decisions; sensitive information should be desensitized before storage, with support for per-user isolation and deletion.

    4. Skill Solidification: Turning “Taught Once” into a Reusable Asset

    If self-iteration stays only at the prompt level, the payoff is very limited. A more robust approach is to solidify workflows that recur more than three times into parameterized scripts, forming a version-controlled skill library.

    The criteria can be quantified: the frequency of a given task type, the duration of a single execution, and the number of failed retries. When all three are high at the same time, the workflow is worth solidifying. After solidification, the agent shifts from “reasoning through the workflow every time” to “selecting and invoking an existing implementation,” and token consumption and execution variance drop together.

    A skill library should contain four elements: type contracts for inputs and outputs, declaration of prerequisite dependencies, error code definitions, and a rollback method. Missing error codes is the most common oversight — without structured errors, upper-layer replanning can only rely on guessing from natural language, and stability is out of the question.

    5. Deterministic Tools First: Engineering Means to Reduce Uncertainty

    In a stable agent system, uncertainty should be concentrated in one place — model reasoning — while everything else is made as deterministic as possible. A workable priority order:

    1. Prefer official APIs over UI operations, since APIs have clear contracts and error codes;
    2. When UI operations are unavoidable, use stable element-location strategies with explicit waits, avoiding fixed delays;
    3. Set timeouts, retry limits, and idempotency keys on all external calls to prevent duplicate submissions;
    4. Emit structured logs for critical steps to make failure attribution easier.

    Retry strategies must distinguish error types: network jitter can be retried with exponential backoff; parameter errors or insufficient permissions are non-retryable and should terminate immediately and be reported, otherwise cost is only amplified.

    6. Observability and Cost Control

    The memory and skill systems must be observable; otherwise they cannot be tuned. Four metrics are recommended: token consumption per task, skill hit rate, first-attempt task success rate, and average retry count. Among these, skill hit rate and first-attempt success rate are the core signals for judging whether the memory system is truly working.

    For cost control, techniques include context compression, retrieval-result truncation, and stable prefix caching. For cloud deployment, you can use container platforms to host the runtime, object storage to hold skill packages, message queues to decouple long-running tasks, and logging services with monitoring and alerting for tracking and threshold notifications. Baidu AI Cloud offers corresponding product categories for these general capabilities.

    7. Conclusion

    The dividing line in agent capability is not whether a single answer looks good, but whether assets can accumulate across sessions and whether stability holds during long-running operation. Layering memory, solidifying workflows into skills, and handing deterministic steps to deterministic tools is the viable path to reducing cost and improving stability at the same time.