Agent Memory and Self-Evolution: Fixing High Token Cost and Unstable Long Runs
Agent memory and self-evolving skills are gaining attention, but they do not automatically solve the two most common complaints about AI agents: heavy token consumption and poor stability over long runs. This article explains why those problems often share the same root cause, and how to address them with layered memory, skill固化 through deterministic code, memory governance, cost controls, and recoverable execution. It includes a target four-layer architecture, rules for what to store and forget, skill contracts, anti-patterns to avoid, and a practical rollout plan with acceptance metrics.
1. What the Hype Is Really About
A class of agent frameworks built around persistent memory and self-iteration has quickly drawn attention, with community interest spiking in a short time. Many are asking whether the old paradigm, in which an agent has to rediscover the world every time, is about to be replaced.
It helps to think of these systems as coworkers. A traditional agent behaves like a temporary worker with a poor memory: every collaboration starts by realigning requirements, and a process agreed on last time is forgotten next time. You just taught it how to query a certain kind of data, and in a new session window it looks blank and asks what the first step is. This “fish memory” causes real pain in three ways:
- Reinventing the wheel: complex tasks require restating preconditions and caveats every time, like onboarding a new hire over and over.
- Pushed-up costs: repeated reasoning and repeated trial and error fill the context with duplicate instructions and corrections, and the end-of-month bill makes your heart race.
- Stability by guesswork: the same task runs today but may get stuck at some inexplicable step tomorrow, and when you ask why, it looks more innocent than you do.
So the selling point of “remembers and learns” is highly attractive: once it remembers user preferences (for example, not to use privilege-escalation commands), it stops suggesting them; parameters you have tuned manually many times get solidified into reusable skills; it can even summarize lessons from failures. The contrast is strong enough that people worry the old paradigm will be squeezed into a corner if it does not “fix its memory.”
2. The Key Judgment: Self-Evolution Does Not Fix the Most Criticized Problems
A cold splash of water is needed here: autonomous evolution of memory and skills does not automatically solve the two things agents are most often criticized for, namely heavy token consumption and poor stability over long runs.
At first glance these are two problems, but breaking them down shows they often share a root cause: the agent is using low-quality, fragile tools to do work that should be done by deterministic tools. The most typical case is browser automation. It looks smart on the surface, but in practice a lot of time is spent in a loop of “look at the page, guess the state, click a button, find it failed, replan, try again.” A slight page redesign, a small popup change, or a bit of network jitter breaks the flow, after which longer retries and reasoning follow, and the bill and stability collapse at the same time.
So the right question is not “do we need memory,” but: put uncertainty in a cage, and let memory remember only what is worth remembering.
3. Target Architecture: Layered Memory, Solidified Skills, Deterministic Execution
Split the system into four layers with clear responsibilities, observability, and rollback.
- Working memory (within a session): holds only the current task state, constraints, and intermediate results, and is reclaimed when the session ends.
- Episodic memory (across sessions): stores structured traces of “task, action, result, failure reason” for retrieval and review.
- Semantic memory (preferences and facts): stores user preferences and environment facts (such as available tools and permission boundaries), with strong constraints and low noise.
- Procedural memory (skill library): solidifies stable flows into skills with input and output contracts, executed by deterministic code, with the model only responsible for planning and selection.
Core principle: the model is responsible for “selection and planning,” and code is responsible for “execution and validation.” Anything that can be written as deterministic steps should not be left to the model to improvise.
4. Memory Governance: What to Write, What Not to Write, and How to Evict
More memory is not better; governance rules decide success or failure.
- Write threshold: only information that “appears repeatedly at least N times,” “brings quantifiable benefit,” and has “verifiable results” may be promoted to long-term memory.
- Structured storage: use key-value or document storage for entries, with fields including scene, constraints, steps, success criteria, failure modes, and version number.
- Deduplication and conflict resolution: for multiple memories in the same scene, score them by “success rate x recency of use x cost”; on conflict, keep the higher version and archive the old one.
- Forgetting mechanism: set TTL and access decay so that entries that are not hit for a long time or whose success rate drops are automatically downgraded or deleted, avoiding memory pollution.
- Privacy and permissions: desensitize sensitive information before storing it, isolate by tenant or project, and support one-click clearing.
Example structure (pseudocode):
MemoryItem {scene: string, // scene identifierconstraints: string[], // hard constraints, e.g. "no privilege escalation"steps: Step[], // executable steps (deterministic first)success_check: string, // success criteriafailure_modes: string[],// known failures and how to avoid themversion: int,hit: int, success: float, cost: int, ts: long}
5. Skill Solidification: Turning “Taught Once” into a Permanent Capability
A skill is the elevation from episodic memory to procedural memory. The criterion is simple: if the same flow has been executed successfully more than twice and the success criteria are stable, it should be solidified into a skill.
A skill should have a clear input/output contract, timeout and retry strategy, idempotency, observable logs, and failure rollback. At runtime the model only selects skills and fills in parameters, and no longer reasons through steps word by word.
# Example: skill contract and registrationclass Skill:name: strdef validate(self, args) -> bool: ...def run(self, args) -> Result: ...def register(skill: Skill):REGISTRY[skill.name] = skill# Runtime: the model emits a structured call; code executes and validatesplan = model.plan(task) # {"skill":"db_query","args":{...}}assert REGISTRY[plan["skill"]].validate(plan["args"])result = REGISTRY[plan["skill"]].run(plan["args"])
6. Replacing Fragile Flows with Deterministic Tools (the Key to Lower Cost and Stability)
Push browser clicks, file parsing, and API calls down into deterministic tools as much as possible:
- Prefer official APIs or batch APIs over page operations; when no API exists, use stable selectors, explicit waits, and a state machine rather than “looking at the screen and guessing the state.”
- Set success criteria and timeouts for every step, and return a structured error on failure; unbounded retries are forbidden.
- Introduce queues and containerized execution environments so tasks are replayable, isolated, and horizontally scalable; connect logs and metrics to a unified logging service and monitoring and alerting.
# Anti-pattern: model-driven long loopwhile not done:page = observe()action = model.decide(page) # high uncertainty, high token usageapply(action)# Recommended: state machine + deterministic stepsfor step in state_machine:out = tool.call(step) # low uncertaintyassert step.check(out)
7. Cost Control: Spend Tokens Where They Matter
- Context compression: inject only retrieved memory fragments and the current state, and never feed back the full history.
- Tiered models: use a strong model for planning and small models or rules for execution and extraction, reducing expensive calls.
- Caching and reuse: cache results for identical subtasks; default parameter values inside skills come from semantic memory.
- Budget guardrails: set token, time, and cost limits per task, and downgrade to human confirmation or a deterministic fallback when exceeded.
- Observable attribution: track tokens, latency, and success rate per task to locate the “most expensive and least stable” step and prioritize it.
8. Long-Run Stability: Recoverability Beats Never Failing
- Idempotency and transactions: every skill can be retried safely; cross-system operations use compensation or rollback.
- Checkpoints and recovery: persist state in stages for long tasks, and resume from the latest checkpoint after interruption.
- Isolation and rate limiting: isolate different tenants and tasks with containers and queues so they do not drag each other down.
- Drills and regression: build a regression set from historical failure samples, and skill upgrades must pass it.
9. Rollout Plan and Acceptance Metrics
- Week 1: instrumentation and baseline (tokens, success rate, P95 latency, interruption rate).
- Weeks 2-3: add semantic memory and retrieval, starting with “preferences no longer need to be repeated.”
- Weeks 4-6: solidify the top 5 high-frequency flows into skills and replace fragile automation.
- From week 7: enable budget guardrails, checkpoint recovery, and the regression set, and enter continuous optimization.
Acceptance suggestions (example targets, to be set against the business baseline): lower tokens per task, lower interruption rate for long tasks, near-zero manual intervention for repeated flows, and a stable skill regression pass rate.
10. Conclusion
“Remembers and evolves” is a direction, not a silver bullet. What really creates the gap is engineering discipline: memory must be governed, skills must be contractual, execution must be deterministic, cost must have guardrails, and long runs must be recoverable. Only by putting uncertainty in a cage can an agent be both smart and reliable. If you build the execution and observability foundation on general-purpose capabilities such as the container platform, object storage, message queue, logging service, and monitoring and alerting on Baidu AI Cloud, your team can form a reusable agent engineering system faster.
