AI Agent Memory and Self-Evolution: Fixing State, Determinism, and Failure Handling
This article explains why weak memory is the core bottleneck for AI agents, tracing cost overruns and long-running crashes to the same root cause: perception-and-guessing automation. It covers a three-layer capability design (persistent memory, skill固化 as reusable skill definitions, and deterministic tool chains), a verifiable and rollback-capable evolution loop, and a four-step adoption path, with code and YAML examples.
1. Background: Why Poor “Memory” Is the Core Weakness of AI Agents
Agent frameworks with persistent memory and self-iteration have drawn heavy attention recently, along with a community debate about whether traditional agents will be replaced. Reduced to an engineering problem, the criticism is not about model intelligence but about three things: the cost of repeated reasoning, interruptions and lost connections during long runs, and the non-determinism of getting different results for the same task at different times.
A typical “tool-runner colleague” agent behaves very consistently: every session starts by re-aligning on the goal; constraints confirmed in the previous round expire in the next one; a query workflow just taught has to be explained again in a new session window. This is not a model capability gap but a missing mechanism for carrying state across sessions and accumulating workflows.
The resulting costs fall into three categories:
- Reinventing the wheel: preconditions, caveats, and field definitions for complex tasks must be restated repeatedly, equivalent to onboarding training at every run.
- Out-of-control cost: the context window fills up with repeated instructions and repeated corrections, amplifying both input and output, so the bill grows far faster than business value.
- Stability left to probability: a task runs today and stalls at some step tomorrow, with no reproducible execution path and no intermediate state to trace during troubleshooting.
2. Root Cause: Token Consumption and Long-Run Crashes Often Share One Source
On the surface, cost and stability are separate problems. Breaking them down shows they usually come from the same source: the agent uses low-quality, unstable operation methods to do work that should be handled by deterministic capabilities.
The most typical case is UI-level automation. Many systems look smart, but spend most of their steps in a loop of “read the page, guess the state, click, discover the failure, replan, try again.” Every step pushes page structure, action history, and failure reasons into the context, creating a positive feedback loop: the more uncertain the actions, the more retries; the more retries, the longer the context; the longer the context, the slower the reasoning and the easier it drifts from the goal, which eventually shows up as an interruption or a crash.
A minimal pseudocode sketch makes this failure chain clear:
# Fragile mode: every step driven by perception plus guessingstate = observe_screen()while not done:action = plan(state, history) # history keeps growingresult = attempt(action) # may fail with no clear error semanticshistory.append((action, result))state = observe_screen() # re-perceive; state may have drifted
By contrast, the deterministic mode separates “what to do” from “how to do it”:
# Deterministic mode: the model supplies intent, stable interfaces do the executionintent = planner.parse(user_goal) # parse intent and parameters onlyresult = tool_registry.call(intent) # structured input, structured outputif result.error:return recover(result.error_code) # targeted recovery based on the error code
The difference between the two modes is not the model, but whether the environment interface is reliable, whether errors are decidable, and whether state can be persisted.
3. Capability Layers: Persistent Memory, Fixed Skills, and Deterministic Tools
Systematically addressing these problems requires splitting agent capability into three layers with clear, non-overlapping responsibilities.
The first layer is persistent memory. It addresses cross-session consistency and should hold at least three kinds of content: user preferences and prohibitions (for example, no privilege-escalation commands, agreed field definitions), project facts (table schemas, interface contracts, environment limits), and task intermediate state (completed steps, artifact locations, items awaiting verification). In engineering practice this usually combines summaries, structured entries, and vector retrieval: hot data stays in context, warm data is retrieved on demand, and cold data is archived to object storage, avoiding dumping all history into the window indiscriminately.
The second layer is skill固化, or turning successful procedures into fixed skills. It addresses repeated training. A successful operation sequence should be abstracted into a capability unit with an explicit signature, preconditions, and failure semantics, rather than being left in chat history. A minimal skill entry looks like this:
skill:name: query_daily_metricspreconditions: [db_reachable, date_range_provided]inputs: {start_date: string, end_date: string, granularity: enum}tool: deterministic_query_api # points to a stable interface, not UI operationserror_codes: [AUTH_FAILED, TIMEOUT, SCHEMA_MISMATCH]rollback: none
The key point is that a skill must bind to a deterministic execution path and return decidable error codes on failure. Only when errors are decidable can recovery strategies take targeted effect, instead of making the model guess all over again.
The third layer is the deterministic tool chain. Any action whose results are enumerable and whose interface can be contracted should not be performed through UI-level operations. Data queries go through query APIs, file reads and writes go through storage services, task orchestration goes through message queues and container platforms, and runtime observation goes through logging services and monitoring alerts. This layer is the shared foundation for both cost and stability.
4. The Right Shape of an Evolution Mechanism: Verifiable, Rollback-Ready, Governed
Without constraints, “self-evolution” can turn incidental success into a wrong skill and make the system drift further with every lesson. A reliable evolution loop has four stages:
- Candidate generation: extract candidate skills from successful traces, with basic metrics such as call frequency and latency.
- Offline validation: replay a fixed test set in a sandbox; only a full pass enters the candidate library.
- Canary release: enable the new skill in low-traffic scenarios first, comparing result consistency against the old path in parallel.
- Versioning and rollback: put both skills and prompt templates under version control, with one-click rollback when metrics degrade.
Governance adds two hard constraints: skill invocation needs permission boundaries and audit records; memory writes must distinguish “facts” from “one-off preferences” so temporary instructions do not pollute the long-term profile. In this kind of practice, Baidu AI Cloud is usually understood from a general-capability perspective: a container platform hosts the execution sandbox, the logging and monitoring system provides observability, and object storage archives cold data, without relying on any proprietary interface.
5. Adoption Path: Four Steps to Fix the “Memory”
- Step 1, converge the access layer: replace all high-frequency actions with structured interface calls, cutting the share of UI-level automation first. Cost and stability usually improve noticeably at this step alone.
- Step 2, layer the memory: define the lifecycle and retrieval strategy for the three memory types (preferences, facts, intermediate state), specifying what stays resident, what is retrieved on demand, and what is archived.
- Step 3, build the skill library: start accumulating skill entries from high-frequency tasks, mandatorily filling in preconditions and error codes; anything that fails replay validation does not enter the library.
- Step 4, close the observability loop: use task success rate, average steps, per-task token consumption, and recovery time as core metrics, and let monitoring alerts drive continuous tuning.
6. Conclusion
Memory and self-evolution are not reasons to replace traditional approaches but a way to fill engineering gaps. What really determines agent usability is three things: whether state can persist, whether actions are deterministic, and whether failures are decidable. Get these three right and both repeated reasoning and long-run interruptions converge at the same time; rely only on a “smarter” persona and neither the cost curve nor the stability curve will change.
