AI Agent Memory and Self-Evolution: A Practical Guide
This guide explains why AI agents struggle with repeated work, rising token costs, and unstable long-running tasks, and how to fix the underlying architecture. It covers replacing non-deterministic UI automation with structured tools, defining clear tool contracts, layering memory across session, preference, skill, and experience stores, building a verifiable skill-evolution loop with validation and rollback, and using state machines, checkpoints, and observability for reliable long-running execution. The focus is on practical engineering patterns that keep agents flexible while bringing cost and stability back under control.
1. The Real Problem Behind the Symptoms: A Missing Architecture Layer, Not a Weak Model
A class of agent frameworks emphasizing “persistent memory + self-iteration” has recently drawn attention in technical communities, often compared with existing general-purpose agent solutions. The discussion is focused: if an agent has to re-align on requirements, re-confirm workflows, and re-try from scratch in every conversation, both its usability and its economics come into question.
Abstracting these complaints one level up reveals that the problem is not a “dumb model” but a system that lacks a stable state-bearing layer. The mainstream approach repeatedly stuffs all context into a limited context window: system prompts, conversation history, tool outputs, error stacks, and correction instructions are mixed together, forcing the model to re-infer “where am I now and what should I do next” from that large blob of text at every step. This produces three typical symptoms.
- Repeated labor: preconditions, constraints, and prohibitions for complex tasks are restated over and over, equivalent to onboarding a new hire hundreds of times.
- Cost inflation: repeated reasoning and repeated trial-and-error translate directly into token consumption, especially for long tasks, where the bill grows super-linearly with task length.
- Unstable results: the same task succeeds today and stalls tomorrow, because success depends on “which information happens to remain in the context,” which is chance rather than design.
It is worth emphasizing that capabilities like “autonomous skill evolution” do not automatically eliminate these problems. They optimize “how experience is accumulated” but do not answer “where state lives, whether tools are reliable, and how failures are recorded in a structured way.” If the underlying architecture stays the same, evolved skills will still be built on a fragile execution chain.
2. The Shared Root Cause of Cost and Safety: Doing Deterministic Work with Uncertain Tools
High token consumption and frequent interruptions during long runs may look like two problems, but they often share one root cause: the agent is using low-quality, non-deterministic tools to do work that should be done by deterministic ones.
The most typical case is web automation. A fragile implementation spends many steps in a loop of “screenshot - recognize - guess state - click - verification fails - replan - try again.” Each loop writes page text, control lists, and action history back into the context, so more steps cause context to expand, and context expansion lowers decision quality, forming a positive-feedback vicious cycle.
The engineering criterion can be simple: if the result of a step is inconsistent across repeated executions, it should not sit on the main task path; it should be encapsulated, constrained, or replaced with a deterministic interface.
A suggested order for refactoring:
- Prefer structured interfaces (server-side APIs, database queries, message queues, object storage) over UI operations.
- When UI operations are unavoidable, wrap them as atomic tools with explicit parameters and stable return structures, and cap the number of retries.
- Define preconditions, post-checks, and idempotency notes for each tool so failures can be judged rather than “guessed at again.”
An illustrative tool contract:
def query_order(order_id: str) -> dict:"""Pre: read-only connection established; Post: returns a status field; Idempotent: yes"""...def submit_refund(order_id: str, reason: str) -> dict:"""Pre: status == 'paid'; Post: returns refund_id; Idempotent: deduplicated by order_id"""...
Once tools have clear contracts, the agent no longer needs to “guess state by looking at state,” and both planning steps and context size drop significantly.
3. Layered Memory: Moving State Out of the Context
The key to solving the memory problem is not a bigger window but externalizing and layering state. A practical layered structure usually has four layers.
- Session layer: short-range state for the current task, keeping only the goal, completed steps, todos, and key constraints, archived when the task ends.
- User preference layer: long-lived explicit preferences (for example, no privileged operations, default output language, code style), stored as key-value pairs and injected on demand rather than in full.
- Skill layer: verified multi-step workflows solidified into reusable, parameterized skill units, invoked with parameters only, not history.
- Experience layer: structured records of failures and fixes, including trigger conditions, error signatures, fix actions, and verification methods.
Each layer needs a different read/write strategy to save tokens while staying stable:
system = base_prompt + select_preferences(user_id, task_tags) # fetch only relevant preferencesplan = load_skill(task_type) # load skills by namestate = {"goal": ..., "done": [...], "todo": [...]} # keep short-range state minimal
An important principle is “retrieve on demand, discard after use.” Stitching all user preferences into the prompt is a hidden source of runaway cost in many systems; the right approach is to tag preferences and retrieve the few that match the task type.
4. Solidifying Skills and Writing Back Experience: Making Evolution Verifiable
Without guardrails, “self-iteration” easily turns accidental success into a wrong skill. A reliable evolution loop has four stages: candidate, validation, solidification, and rollback.
- Candidate: after a task succeeds, compress the trajectory into “trigger condition + step sequence + checkpoints.”
- Validation: run regression with multiple sample sets in an isolated environment; only allow it into the store if the success rate exceeds a set threshold.
- Solidification: assign a version number and applicable scope when storing; the calling side depends only on a stable signature.
- Rollback: switch back to the old version when the online failure rate rises, preventing bad skills from spreading.
Failure experience should also be structured rather than left as a natural-language stack trace:
{"task_type": "data_export","symptom": "timeout_after_30s","cause": "full_table_scan","fix": "add_time_range_filter","verify": "row_count_between(1, 100000)"}
The value of such records is that they are searchable and reusable: the next time a similar task appears, the agent can avoid known pitfalls during planning instead of stepping into them again.
5. Long-Running Stability: State Machines, Checkpoints, and Observability
Most long-running interruptions are not model capability problems but a missing execution skeleton. It is advisable to model agent execution as an explicit state machine and persist checkpoints at key nodes (in object storage or a logging service) so tasks can resume from the break point instead of restarting from zero.
Also fill in observability: record the tool name, elapsed time, token usage, return code, and retry count for each step, and set thresholds with monitoring and alerting. When the retry rate or average step count for a class of tools rises abnormally, the problem usually lies in the tool contract rather than the prompt.
In terms of deployment, container platforms handle elasticity and isolation, while logging and monitoring services handle tracing and alerting. This common combination can move agents from “works in a demo” to “works on call.”
6. Conclusion
The essence of an agent’s “poor memory” is the lack of externalized state and tool constraints; the shared root cause of high cost and easy crashes is letting an uncertain execution chain take on deterministic responsibilities. A viable path is: layered memory + deterministic tools first + skill solidification with a validation gate + structured failure write-back + state machines and observability. On platforms such as Baidu AI Cloud, using common capabilities like object storage, message queues, container platforms, and logging and monitoring to carry these layers can let agents stay flexible while bringing cost and stability back into the developer’s hands.
