AI Agent Memory and Self-Evolution: A Layered Engineering Approach to Cost and Stability

    Agent memory and self-evolution are often treated as a silver bullet, but missing memory explains only part of the problem. This article examines, from a general engineering perspective, why agents fail to retain context, why token bills grow, and why runs become unstable. It proposes a layered memory structure, a process for turning repeated solutions into versioned, testable skills, and a "deterministic tools first" ordering that stabilizes execution before memory and skill consolidation are added. The piece also maps these structures onto generic cloud capabilities and an evaluation loop built on task success rate, cost per task, and mean recovery time.

    AI Agent Memory and Self-Evolution: A Layered Engineering Approach

    Agent frameworks that claim “persistent memory” and “self-iteration” have drawn a lot of attention recently, along with a community debate about whether the previous generation of tool-based agents will be phased out. The sentiment behind that debate is understandable, but the conclusion is premature. Treating memory and self-evolution as a silver bullet tends to hide where the real costs and stability bottlenecks come from. Setting aside specific product features, this article takes a general engineering view of why agents cannot remember, why they burn money, and why they run unstably, and of how to design memory in layers, how to solidify experience into reusable capabilities, and how to replace fragile workflows with deterministic tools.

    1. Three Real Costs of a “Fish’s Memory”

    Most agent systems are stateless at the session level: once the context window closes, prior agreements, parameters, and workflows all reset to zero. Users are forced to repeat “onboarding” every time, which produces three quantifiable losses.

    • Repeated alignment cost. Preconditions, prohibitions, and output specifications for a complex task have to be restated every round, which both lengthens the interaction and increases the chance of conflicting instructions.
    • Uncontrolled token cost. Repeated reasoning and trial-and-error fill the context with redundant instructions and correction records, inflating both input and output, and the bill rises accordingly.
    • Stability becomes guesswork. The same task may succeed today and stall tomorrow, and the root cause is usually that the workflow depends on volatile external state, not that the model is “in a bad state.”

    It is worth stressing that these three problems do not sit at the same layer. Missing memory explains only part of the first one; the second and third stem mainly from architectural flaws in the tool layer and the execution layer.

    2. Layered Memory: Making “Remembering” a Governable Engineering Structure

    A reliable memory system should not be a single vector store but a layered structure, where each layer has different write policies, lifecycles, and permission boundaries.

    1. Working memory: the explicit state of the current task, holding goals, constraints, completed steps, and hypotheses still to be verified in a structured form, and reclaimed when the task ends.
    2. Episodic memory: task traces and result summaries, used for retrospectives and for retrieving similar history, and required to carry timestamps and success markers.
    3. Semantic memory: stable knowledge such as domain facts, system topology, and field meanings, which changes infrequently and should be versioned.
    4. Procedural memory: executable workflows and preference constraints, such as “do not use privilege-escalation commands” or “back up before changing,” existing as rules or skills.

    Illustrative memory write and retrieval logic (pseudocode that expresses structure only and does not point to any specific product):

    1. def remember(event):
    2. if event.type == "constraint":
    3. procedural.upsert(event.key, event.value) # Long-term preference, highest priority
    4. elif event.type == "trace":
    5. episodic.append(summarize(event)) # Trace summary, retrievable
    6. elif event.type == "fact":
    7. semantic.upsert(event.key, event.value, ttl=None)
    8. else:
    9. working.update(event.state) # Visible to the current task only
    10. def recall(task):
    11. return merge(
    12. procedural.match(task.tags), # Hard constraints injected first
    13. semantic.search(task.query, top_k=5),
    14. episodic.search(task.query, top_k=3, only_success=True),
    15. working.snapshot(),
    16. )

    Three engineering points matter here. First, constraint-type memory must be hard-injected and must not be overridden by ordinary retrieval. Second, retrieval results should carry provenance and confidence, and conflicts should be resolved in the order “constraints > facts > traces.” Third, memory must have eviction and correction mechanisms; a wrong experience that stays resident will keep amplifying trial-and-error cost.

    3. Skill Solidification: Turning Experience from “Text” into “Executable Assets”

    The value of self-evolution lies not in making the model “remember lessons” but in settling repeated solutions into deterministic, testable, reusable capability units. A qualified skill contains at least: applicable conditions, an input/output contract, a failure rollback strategy, evaluation samples, and a version number.

    1. skill:
    2. name: query_daily_metrics
    3. version: 1.3.0
    4. when: data source is a daily-granularity metrics table and the user did not specify a time range
    5. input: {metric: string, range: date_range}
    6. output: {rows: list, checksum: string}
    7. on_error: fall back to a cached snapshot and annotate data freshness
    8. eval: [sample1, sample2, edge_sample3]

    The recommended solidification flow has four steps: trace collection, clustering of successful patterns, generation of a skill draft, and gradual rollout after passing offline evaluation. Only skills that pass evaluation are allowed into production, which avoids “treating an accidental success as a general rule.” Skills should also be given call budgets and timeouts so that a single skill does not become a black hole for cost and latency.

    4. The Real Source of Cost: Using Fragile Tools for Deterministic Work

    Attributing the bill and the crashes to a common source reveals it: the agent is using low-quality, non-deterministic tools to do deterministic tasks. The most typical case is UI automation, where the model has to “look at the page, guess the state, find the control, discover the failure, replan, and try again.” A small change in page structure or a popup restarts the whole loop, and every loop costs money.

    The governance order should be “change the tools first, then talk about memory”:

    • Prefer stable interfaces for reading and writing data, and compress UI operations into a fallback path;
    • Establish idempotency keys and deduplication tables for external systems to avoid duplicate side effects from retries;
    • Split long workflows into short transactions, save a checkpoint at each step, and resume from the most recent checkpoint on failure;
    • Introduce caching and pre-aggregation for high-frequency read-only requests to reduce repeated reasoning;
    • Instrument the full chain, recording per-step latency, tokens, and failure reasons, and use the data to locate cost hotspots.

    Illustrative deterministic-first scheduling:

    1. def run(task):
    2. for step in plan(task):
    3. if api = stable_api(step): # Deterministic channel first
    4. result = api.call(step.args, idempotency_key=step.key)
    5. else:
    6. result = ui_fallback(step) # Fallback channel, strictly rate-limited
    7. checkpoint.save(step.id, result) # Supports resume from checkpoint
    8. if not result.ok: break
    9. return summarize(checkpoint.path())

    5. Running It in the Cloud: Composable Generic Capabilities and an Evaluation Loop

    Productionization requires mapping the structures above onto generic cloud capabilities: stateless compute hosts the agent runtime, a container platform provides elasticity and isolation, object storage holds skill packages and trace archives, a message queue smooths task peaks and handles retries, logging services and monitoring alerts provide visibility into cost and failure rates, and key and permission management constrain tool-call boundaries. Baidu AI Cloud offers corresponding capabilities in these generic categories, and they can be composed along these layers without depending on any single proprietary interface.

    The evaluation loop is equally indispensable: build an offline sample set covering normal, boundary, and adversarial inputs; after launch, track three core metrics, namely task success rate, cost per task, and mean time to recovery; and review failure clusters weekly, upgrading high-frequency success patterns into skills and converting high-frequency failures into validation rules or tool-replacement requirements.

    6. Conclusion

    Memory and self-evolution are necessary capabilities, but not sufficient conditions. If the tool layer remains fragile, memory will only make the agent repeat its mistakes more confidently, at a higher cost. The correct order is: first stabilize the execution layer with deterministic interfaces and checkpoint mechanisms, then use layered memory to solve the alignment problem, and finally use skills with evaluation and versioning to settle experience. Following this path, an agent can move from “relearning the world every time” to a predictable, auditable, cost-controlled engineering system.