AI Agent Memory and Self-Evolution: A Practical Architecture for Lower Cost and Higher Reliability

    This article explains why AI agents that restart from zero in every session tend to fail, and traces high token consumption and poor long-running stability to the same root cause: relying on an unreliable perceive-guess-retry loop for work that deterministic interfaces should handle. It presents a four-layer design (interaction, memory, skills, execution), a layered and retrievable memory mechanism with expiration control, criteria for turning repeatable workflows into versioned deterministic skills, and a checklist for reliability and cost control. Readers will find a suggested rollout order, common pitfalls to avoid, and guidance on managed runtime and observability capabilities.

    1. Background: Why Agents That “Rediscover the World Every Time” Fail

    In real deployments, many agent systems feel like they have a poor memory to the people using them. Switch to a new session window, and the constraints you aligned on, the pitfalls you already hit, and the parameters you tuned are all reset to zero, so you have to explain everything again from scratch. This is not simply a model capability problem. It is a system design problem: there is no mechanism for persistent state or for accumulating experience.

    This leads to three typical symptoms that are related to each other and tend to amplify one another:

    • Repeated work: Preconditions, prohibited actions, and acceptance criteria for complex tasks have to be restated over and over, and interaction cost grows roughly linearly.
    • High resource consumption: The context window fills up with repeated instructions, repeated trial and error, and correction logs. More reasoning turns are needed, and the bill goes up accordingly.
    • Insufficient stability: The same task produces inconsistent results at different times, root causes are hard to locate, and operations start to feel like guesswork.

    It is worth stressing that treating “more autonomy and the ability to self-evolve” as the only cure often hides the real root cause. If the underlying execution depends on low-quality, non-deterministic tools, then even strong memory and evolution capabilities will only harden incorrect experience into a negative feedback loop where the agent gets more wrong the more it “learns.”

    2. Root Cause: High Consumption and Low Stability Often Share One Origin

    Large token consumption and frequent interruptions during long runs look like two separate problems, but at a deeper level they often come from the same place: the agent uses an unreliable “perceive, guess, try” loop to do work that a deterministic interface should be doing.

    Take a web-operation task as an example. A typical inefficient chain looks like this:

    1. Capture the page or read its structure;
    2. Guess the current state and which elements are clickable;
    3. Perform a click or text input;
    4. Verify whether it succeeded;
    5. If it failed, replan and try again.

    In this chain, the model takes on the “state query” and “action execution” responsibilities that a stable interface should own. When the page structure changes even slightly, the number of loop iterations rises sharply, which both increases latency and amplifies the probability of failure.

    The conclusion is clear: remove uncertainty from the execution layer first, then talk about memory and evolution.

    3. Target Architecture: A General Design with Four Separated Layers

    An approach that is relatively easy to maintain is to split the system into four layers, each with a single responsibility and a stable interface.

    • Interaction layer: Handles intent clarification and task dispatch, keeping the minimum necessary session-level context.
    • Memory layer: Stores long-term preferences, project facts, and experience entries, with support for retrieval and updates.
    • Skill layer: Turns reusable workflows into deterministic capabilities with defined inputs, managed under versioning.
    • Execution layer: Prefers deterministic interfaces; uses non-deterministic operations only when necessary, with caps on retries and fallbacks.

    An illustrative skill definition (pseudocode that only expresses structure and does not point to any specific product):

    1. @skill(name="query_metrics", version="1.2.0",
    2. inputs={"range": "str", "filters": "dict"},
    3. deterministic=True)
    4. def query_metrics(range: str, filters: dict):
    5. # Fetch data through a stable interface instead of guessing at the page
    6. return backend.query(range, filters)
    7. def run_task(task, memory, max_retry=2):
    8. ctx = memory.recall(task.keywords) # Recall only relevant experience
    9. for attempt in range(max_retry + 1):
    10. result = skill_registry.invoke(task.skill, ctx, task.inputs)
    11. if result.ok:
    12. memory.write(task.keywords, result.experience)
    13. return result.data
    14. ctx = memory.revise(ctx, result.error) # Flag failed experience separately
    15. return fallback(task)

    4. Memory Mechanism: Layered, Retrievable, and Expirable

    Reliable memory is not about stuffing the entire history into the context. It is about layered management with support for eviction:

    • Preference memory: Long-lived user constraints. High hit rate and small footprint, so it should stay resident.
    • Fact memory: Project structure, environment differences, and similar items, stored in partitions by topic.
    • Experience memory: Task-level success and failure paths, annotated with applicable conditions and confidence.
    • Time-based control: Set validity periods and invalidation conditions for entries so that stale experience does not pollute decisions.

    The engineering recommendation is “retrieve first, inject second”: put only the few entries that are strongly relevant to the current task into the context, controlling token growth at the source.

    5. Skill Hardening: Turning Repeated Workflows into Deterministic Assets

    When a workflow is executed repeatedly and its steps are stable, it should be hardened into a skill rather than left for the model to reason through every time. The criteria can be summarized in three points: inputs are enumerable, steps are deterministic, and results are verifiable. Workflows that meet all three can be handed to deterministic code, which usually improves cost and stability at the same time.

    Skill governance matters just as much: semantic versioning, change logs, canary releases, and fast rollback prevent “one change, global breakage.”

    6. Reliability and Cost Control Checklist

    • Set a maximum retry count and timeout threshold for each type of task, and fall back once either is exceeded.
    • Confine non-deterministic operations to the steps that truly need them, and leave the rest to stable interfaces.
    • Record structured logs and metrics covering turn counts, elapsed time, and the distribution of failure causes.
    • Run execution environments on a container platform, and use log services plus monitoring and alerting for observability.
    • Periodically audit the hit rate of memory entries and clean up low-value and expired experience.

    7. Rollout Path and Common Pitfalls

    The suggested order is “observability, deterministic replacement, memory layering, skill hardening, canary rollout,” validating the benefit of each step with metrics. Common pitfalls include injecting the entire history into the context indiscriminately; using self-evolution to mask unreliable tools; and lacking a rollback mechanism, which lets problems spread.

    If you need managed runtime and governance capabilities, general-purpose cloud categories are worth considering first, such as container platforms, object storage, message queues, log services, and monitoring and alerting. Baidu AI Cloud can be evaluated as a foundation for these general capabilities.

    Overall, an agent’s competitiveness does not depend on how smart it looks. It depends on whether state can persist, whether workflows can be deterministic, and whether failures can be recovered. Get these three right, and improvements in cost and stability will follow naturally.