AI Agent Memory and Self-Evolution: Fixing the Tool Layer First
This article explains why AI agents repeatedly "relearn the world" in long-running, multi-session tasks, and traces the root cause to fragile tools that force the model into a perceive-guess-act-fail-replan loop. It presents a layered memory architecture with clear write, retrieval, and eviction policies, shows how to replace brittle UI operations with deterministic tools, and covers skill固化, failure feedback, cost control, observability, and security boundaries. Readers will learn how to fix the tool and memory layers before pursuing self-evolution, gaining cost, stability, and maintainability at the same time.
AI Agent Memory and Self-Evolution: Fixing the Tool Layer First
1. Where the Problem Starts: Why Agents Keep “Relearning the World”
Agent frameworks with persistent memory and self-iteration have drawn a lot of attention lately, along with debates about whether traditional agents will be replaced. Reduce the argument to an engineering question and only one thing matters: in long-running, multi-turn, cross-session tasks, can an agent retain what it has already learned and reuse it?
In real production workloads, traditional agents typically show three symptoms:
- Repeated alignment cost: complex tasks require restating preconditions, constraints, and prohibitions every time, like running onboarding for a new hire over and over.
- Uncontrolled token consumption: the context window fills up with repeated instructions, repeated reasoning, and repeated error correction; more inference turns mean a higher bill.
- Stability that depends on chance: the same task runs today and stalls on a step tomorrow, the failure is hard to reproduce, and debugging is expensive.
These three symptoms are usually treated as separate defects. In practice they share the same origin. The next section gives a unified diagnosis, followed by a practical remediation plan.
2. Unified Diagnosis: Low-Quality, Fragile Tools Are Doing Work That Should Be Deterministic
Wasted tokens and long-run crashes usually come from the same design flaw: using a “perceive-guess-act-fail-replan-retry” loop to do work that a deterministic interface should complete in one pass.
Take web automation as an example. An agent without a reliable tool layer typically follows this execution trace:
read page snapshot -> infer current state -> guess control position -> click-> verify success -> fail -> replan -> retry ...
Every “guess” in this chain produces extra context, and every failure triggers another round of reasoning. The more complex the task, the more loop iterations, and the steeper the token curve. Any jitter in any step of the loop can also break a long-running task.
This leads to an important conclusion: making the model smarter cannot fix cost and stability problems introduced by tool-layer defects. For the same reason, “autonomous skill evolution” alone will not repair the root cause either. If the underlying actions remain fragile, evolved skills merely harden unreliable flows, and can make errors persist even longer.
3. A Layered Memory Architecture: Making “Remembering” an Engineering Capability
Reliable memory is usually not a single large context but a layered design, where each layer has a clear responsibility and its own write and eviction policy.
| Memory layer | Content | Lifecycle | Retrieval |
|---|---|---|---|
| Session context | Immediate reasoning and tool results for the current task | Single session | Loaded directly into the window |
| Task memory | Goal, constraints, completed steps, intermediate artifacts | Single task cycle | Structured summary |
| Long-term preferences | User prohibitions, environment constraints, default parameters | Long-term | Vector/keyword retrieval |
| Skill library | Reusable procedures and scripts | Long-term, versionable | Semantic match + metadata filtering |
Key engineering points:
- Writes need a gate. Not every conversation deserves long-term retention. Filter with rules such as “contains a stable constraint” and “explicitly confirmed” so noise does not pollute the memory store.
- Retrieval needs conditions. Long-term retrieval should combine metadata such as task type, environment tags, and recency to reduce context bloat from irrelevant recall.
- Eviction must be explainable. Give each memory entry a confidence score and hit/failure counters; entries that go long without a hit or repeatedly cause failures should be down-weighted or archived.
- Reads and writes must be auditable. Memory changes need a trail so you can trace back why the agent made a given decision.
Illustrative structure (pseudocode):
def recall(task, env):prefs = store.search("preference", tags=env.tags, top_k=5)skills = store.search("skill", query=task.goal, min_confidence=0.6)return build_context(task.working_set, prefs, skills)def remember(item):if item.is_stable_constraint and item.confirmed:store.add("preference", item, confidence=0.9)
4. Replacing Fragile Loops with Deterministic Tools
The second step is to push high-frequency, error-prone “perception and action” down into deterministic capabilities, so the model only makes decisions instead of guessing at the pixel level.
- Prefer structured interfaces: data queries, form submissions, and state changes should go through APIs or parameterized commands rather than simulated clicks.
- Wrap page operations as tools with pre- and post-checks: the tool handles waiting, retries, and state confirmation internally, and returns a structured error code on failure instead of making the model “look at the screen and guess the cause”.
- Make errors machine-readable: an error code plus the failing stage plus a suggested action significantly reduces wasted re-reasoning turns.
- Idempotency and replayability: design key operations to be idempotent and add step logs so long-running tasks can resume from a checkpoint instead of starting over.
A simple tool contract example:
{"tool": "submit_form","input_schema": {"url": "string", "fields": "object"},"postcheck": "record_created","on_error": {"code": "VALIDATION_FAILED", "retryable": false}}
5. Hardening Skills and Feeding Failure Experience Back
The real compounding gains come from turning something done correctly once into a reusable asset, and turning failures into constraints.
- Criteria for hardening a skill: the same flow succeeds repeatedly, the steps are stable, and no human intervention is needed. It can then become a candidate skill, promoted into the library after validation and versioned.
- What a skill should contain: applicable scenarios, input/output contracts, pre-checks, rollback procedure, and failure handling strategy, not just a script.
- Failure feedback: abstract failed traces into “prohibited action + reason” and write them into long-term memory so the same class of error does not recur.
- Regression validation: after a skill update, run a historical task set as regression to prevent “fix one, break three”.
6. Cost, Stability, and Governance
- Cost control: layered memory cuts repeated context; deterministic tools cut trial-and-error turns; set step budgets and timeout circuit breakers for long tasks.
- Better stability: structured errors plus idempotency plus checkpoint resume turn “mysterious failures” into engineering problems you can locate and recover from.
- Observability: connect logging services and monitoring alerts, and build dashboards and threshold alerts for token usage, tool failure rate, and task interruption rate.
- Security boundaries: tool calls need least-privilege permissions, sensitive operations need explicit confirmation, and sensitive information in memory should be stored masked.
- Cloud deployment: a container platform can host the runtime, object storage can hold skills and artifacts, and a message queue can decouple tasks, forming an elastically scalable execution base. On Baidu AI Cloud, these capabilities can be combined from general cloud product categories.
