Designing a Self-Evolving AI Agent Mechanism Across Sessions
Many general-purpose agent frameworks perform well within a single conversation—they can plan, call tools, and adjust based on intermediate results—yet they start from scratch in every new session. This article explains how to close that gap with a six-stage self-evolution loop: extracting reusable experience, storing it as structured skill cards, retrieving skills semantically, injecting them under context budgets, validating results against reality, and continuously patching stale knowledge. It also covers key design trade-offs around autonomy, observability, and security, plus a three-phase rollout path for putting the mechanism into production.
Designing a Self-Evolving AI Agent Mechanism Across Sessions
The Core Problem: Coherent Within a Session, Blank Across Sessions
Many general-purpose agent frameworks perform reasonably well within a single conversation. They can plan steps, call tools, adjust strategy based on intermediate results, and eventually complete what looks like a complex task. For example, ask one to write a service management unit configuration, configure a reverse proxy, and pipe application logs into the system logging service. The task itself is not exotic, but the execution often requires twenty-plus rounds of tool calls, with path selection, parameter corrections, error troubleshooting, and final verification along the way.
The real problem appears the next time. Move to a different machine, a different working directory, or even just open a new session, and ask it to do a similar task—it will likely start from zero again: probing the directory structure anew, stepping on the same parameter pitfalls, and reorganizing tool-call sequences. The reasoning chain built within a session never becomes a cross-session capability; the system prompt and tool descriptions remain empty.
This is the default state of most agent tools: strong within a session, weak in persistent experience. They can “reason in the moment” but cannot “learn from mistakes.” To build agents that are genuinely usable, you must add a closed loop that turns one-off execution into reusable experience.
The Six Stages of the Self-Evolution Loop
Agent self-evolution does not mean letting the model modify its own weights online. It means having the agent accumulate reusable procedural knowledge during task execution, and retrieve, inject, validate, and patch that knowledge in later tasks. A complete loop includes at least six stages.
1. Experience Extraction: Deciding What Is Worth Remembering
Not every task deserves to be remembered. A simple file read or a fixed-format conversion has little documentation value; complex tasks, difficult error fixes, and non-trivial workflows often contain substantial tacit knowledge. Practical trigger conditions include: tool calls exceeding a threshold, multiple failed retries during a task, fixing a hard-to-locate error, discovering a non-obvious cross-system workflow, or reaching a stable solution after human intervention.
The key point: the agent decides autonomously rather than relying entirely on the user saying “remember this.” Explicit user triggers are convenient but come with high hidden costs—novices don’t realize that those twenty rounds of calls are worth saving, nor that they will encounter the same task again. Delegating the decision to the agent requires explicit constraints in the system prompt: after completing a complex task, proactively summarize it; when an existing skill is found to be outdated, incomplete, or incorrect, patch it immediately without waiting for instructions.
2. Structured Storage: Turning Workflows into Skill Cards
Experience cannot simply pile up as chat history, or retrieval and injection will become unmanageable. A better approach is to store it as structured “skill cards” containing fields such as: skill identifier, applicable scenarios, preconditions, step sequence, tool call templates, parameter constraints, common errors, verification methods, version number, last-verified time, and confidence score.
Pseudocode example:
skill_card = {id: "configure_reverse_proxy_and_logs",scope: "Service deployment and log integration",preconditions: ["Target host reachable", "Application port confirmed"],steps: ["Confirm how the service runs and which port it uses","Generate the service management unit configuration","Configure reverse proxy forwarding rules","Pipe application logs into the system logging service","Reload configuration and verify health"],pitfalls: ["Port conflicts", "Insufficient permissions", "Log path does not exist"],verification: ["Service status is healthy", "Proxy chain is reachable", "Logs are searchable"],version: 3,confidence: 0.82}
The value of a skill card is twofold: it lets the agent reuse the skill quickly, and it lets humans review its boundaries and risks.
3. Semantic Retrieval: Finding the Right Experience at the Right Time
Once the skill library grows, the biggest challenge is not availability but precision. A good approach is multi-route recall: match by task keywords, tool types, error signatures, and environment tags, then rank by semantic similarity. Retrieved results should not be injected wholesale; filter for relevance first and detect conflicts. For example, when multiple versions of the same skill exist, prefer the card that most recently passed verification and whose scope best matches the task.
4. On-Demand Injection: Controlling the Context Budget
Injecting experience is not a case of “the more, the better.” Stuffing an entire skill manual into the context crowds out reasoning space and can introduce stale information. A safer strategy is “summary injection plus on-demand expansion”: first inject the skill card’s goal, preconditions, and step summary so the agent can judge applicability; when execution reaches a specific step, expand the parameter templates and error-handling details. For high-risk operations, the agent should also be required to re-verify preconditions before proceeding.
5. Result Validation: Letting Experience Face Reality
A stored workflow is not necessarily correct. Environments change, dependencies get upgraded, and permission policies get adjusted. Therefore, every skill hit should write execution results back to the skill card: success raises confidence; failure records the reason and the discrepancies. Validation methods can include command output checks, health checks, log inspection, unit-test replay, and manual spot checks. Experience without validation is just “documented guessing.”
6. Continuous Patching: Making Maintenance the Default
Once a skill goes stale, it turns from an asset into a liability. The system prompt should explicitly require: when using a skill and discovering missing steps, incorrect parameters, or a changed scope of applicability, patch it in place immediately rather than waiting for user feedback. Patching should support versioning, diff records, and rollback, so a single bad edit does not contaminate the entire skill library. Skills that remain unverified for a long time, whose failure rate rises, or whose environment tags become invalid should be automatically down-weighted or marked for review.
Key Design Trade-offs
Autonomous triggering vs. noise control: Full autonomy will accumulate plenty of low-value experience. Set thresholds and apply secondary filtering: only candidates that satisfy complexity, reusability, and verified success enter the skill library.
Injection strategy and observability: Log every skill hit, injected fragment, execution result, and patch action to create an auditable chain. Core metrics include task success rate, average tool-call rounds, repeated-task completion time, skill hit rate, false-hit rate, and rollback rate.
Security boundaries: Skill cards may contain sensitive paths, credential placeholders, or high-risk operations. Sanitize on storage, enforce permission checks on injection, and require confirmation or sandboxed verification for high-risk steps.
A Rollout Path
Start with high-frequency, low-risk, verifiable tasks such as environment checks, log integration, proxy configuration, and build/release support workflows. Phase one: automatic extraction plus human review before entry into the library. Phase two: open up retrieval/injection and result write-back. Phase three: introduce automatic patching and version rollback. This sequence captures reuse benefits early while preventing the skill library from going off the rails.
In short, an agent’s competitiveness lies not only in how well it reasons in a single pass, but in whether it can turn one session’s struggle into the next session’s starting point. Stitching together experience extraction, storage, retrieval, injection, validation, and patching is what moves an agent from “starting from zero every time” to “getting better the more you use it.”
