Self-Evolving Agent Architecture: Dual-Drive Mechanisms and Engineering Practices
Most agent systems optimize for keeping the current session stable, then discard the execution trajectories that contain valuable trial-and-error experience. This article presents a self-evolving agent architecture that converts runtime interaction data into reusable assets through two complementary loops: an external symbolic loop that distills long-term memory and structured skills for immediate, auditable correction, and an internal parameter loop that uses GRPO-based reinforcement learning to update model weights. It also covers asynchronous skill review, trajectory synthesis and quality inspection, trajectory compression, context budgeting, layered prompting, and a production harness with isolation, observability, regression testing, canary rollout, rollback, and cost controls. The article concludes with implementation guidance and risk controls for avoiding experience contamination, capability degradation, and uncontrolled costs.
1. Starting Problem: Why Most Agents Have a Capped Intelligence Ceiling
Traditional AI coding tools and general-purpose agent frameworks manage context mainly to prevent the current session from breaking down. Window trimming, summary compression, and tool-result truncation are all designed around the stability of a single task. Once the task ends, the execution trajectory is discarded. Experience gained through trial and error is not retained, and system capability remains anchored to two static assets: the native reasoning level of the base model and a manually prewritten skill collection.
This leads to three common symptoms: similar problems are re-explored repeatedly; error patterns recur across multiple sessions; and domain performance cannot improve through use—the only lever is switching to a larger model. Breaking this constraint requires transforming one-off execution into a cumulative data loop.
2. Overall Architecture: A Self-Evolving Loop with Dual Driving Wheels
The core of a self-evolving agent is to feed interaction data generated at runtime back into two types of reusable assets:
- External evolution (symbolic layer): Distill trajectories into structured skills and long-term memory, inject them into context, and enable immediate error correction. This does not change model weights. It is fast-acting, auditable, and rollback-capable.
- Internal evolution (parameter layer): Convert high-quality trajectories into training signals and update weights through reinforcement learning, so that a general model develops native capabilities in a specific domain. This is costly and slow, but it can break through the ceiling of prompt engineering.
Together, the two form a complete chain: task execution → trajectory collection → experience deposition → weight internalization → capability regression validation → re-execution. Engineering practice must make every segment of this chain observable and evaluable; otherwise, “self-evolution” can degrade into “self-contamination.”
3. External Evolution: Upgrading Skills from Static Components to Dynamic Assets
3.1 Trigger Mechanism: Counter-Driven Asynchronous Review
Review must not block the main execution path, nor should it run every turn, because the cost would be too high. A practical approach is to maintain a counter for the number of iterations since the last skill update. When the counter exceeds a threshold—for example, a default of 10 turns—and no skill write has occurred, enqueue a background review task:
# Pseudocode: non-blocking triggerif state.iters_since_skill >= SKILL_REFRESH_THRESHOLD:state.iters_since_skill = 0queue.submit(background_review, fork(state.trajectory_window))
The key point is fork semantics: the background reviewer receives a read-only snapshot of the trajectory, while the main agent returns a response immediately. The user side incurs no additional latency.
3.2 Three-Dimensional Decomposition by the Background Review Agent
Background review is a lightweight agent that performs three parallel analyses of the trajectory:
- Memory review: Extract key facts, constraints, and long-term preferences. After deduplication, write them to the long-term memory store for retrieval in later sessions.
- Skill review: Determine whether the solution path is general. Does it depend on incidental context? Can it be parameterized? Does it have reusable preconditions? If it meets the criteria, abstract it into a structured skill.
- Holistic review: Summarize error patterns, such as misjudging file structure or ignoring dependency versions, and generate constraint-oriented optimization strategies that feed back to revise the prompt and tool descriptions.
3.3 Skill Asset Structure and Governance
Skills must carry metadata; otherwise, the library will expand rapidly and conflict with itself:
name: incremental-build-diagnosisversion: 1.3trigger: [build failure, dependency conflict]preconditions: [build logs are readable]steps: [locate first error, verify dependency versions, retry with minimal change]confidence: 0.82 # rolling statistic based on historical success ratehit_count: 41rollback_to: 1.2
Recommended governance rules include similarity-based deduplication, automatic downweighting of skills below a confidence threshold, injecting only the Top-K most relevant skills per session, and retaining versions and rollback points. The injection volume must be hard-constrained by the context budget.
4. Internal Evolution: A Weight Loop Based on GRPO
Injected skills solve immediate error correction, but they cannot change the native reasoning ceiling of the model. The second path consists of three microservice-level stages.
4.1 Trajectory Synthesis and Quality Inspection
Use a flagship general-purpose LLM as the teacher model. Within a parallel batch scheduling module, batch-sample against task-specific prompts or publicly available code evaluation benchmarks, producing a unified multi-turn dialogue data format: role, tool call, tool return, and final answer. Quality inspection applies four filters: format validity, tool-call parseability, executable verification of the answer (compilation/unit tests passing), and deduplication/decontamination by removing samples that overlap heavily with the evaluation set. In domains without executable verification, do not use model self-evaluation as a substitute for quality inspection.
4.2 Trajectory Compression
Raw trajectories are long and noisy, so they must be compressed into a training-friendly form: collapse repeated tool outputs, preserve key decision points and failure branches, and summarize long context into structured state. The goal is to increase information density per token while retaining the reasoning traces that explain why each choice was made.
4.3 Reinforcement Learning Training
Use methods such as Group Relative Policy Optimization (GRPO): sample a group of responses for the same prompt, and replace an independent value network with group-based reward normalization to reduce GPU memory usage and engineering complexity.
The general form of advantage estimation is:
A_i = (r_i - mean(r_1..r_n)) / std(r_1..r_n)
Rewards should be based on verifiable signals such as test pass rates, static checks, and task completion, supplemented by length and format penalties. On the training side, use small, fast iterations, run regression evaluations each round, and retain base snapshots for rollback, so that “evolution” does not become capability degradation.
5. Context Engineering: Budget Is Architecture
Context is a scarce resource and should be explicitly modeled as a budget allocation. For example: system instructions and constraints 10%, skill and memory retrieval 20%, task state and plan 15%, tool results 40%, and headroom 15%. Supporting strategies include hierarchical summarization—verbatim text for recent context and summaries for distant context—structured truncation of tool results, retrieval on demand rather than full injection, and temporal decay and conflict resolution for cross-session memory.
6. Prompt Engineering: Layering and Structure
Split the prompt into four layers: identity and boundaries, domain constraints, skill injection section, and output contract. The output contract should be enforced with a strict schema, such as JSON Schema, to support programmatic validation and automatic retries. The skill injection section should explicitly label the source and confidence of each skill, so the model understands that it is receiving “experience” rather than “hard rules.”
7. Harness Engineering: Production-Grade Runtime
The harness is the runtime foundation that carries the mechanisms described above and determines whether the system can go into production:
- Isolated execution: Containerized or sandboxed tool execution, resource quotas, timeouts, and network allowlists.
- Tool gateway: Unified authentication, rate limiting, idempotency, and retries; abstract underlying differences.
- Observability: Trace every tool call and token consumption end-to-end; store structured trajectories in logging services and object storage.
- Evaluation regression: A fixed benchmark set plus shadow traffic; any skill or weight update must pass a regression gate.
- Canary deployment and rollback: Run dual versions of skills and models in parallel, ramp traffic by percentage, and automatically fall back on anomalies.
- Cost control: Queue-based peak shaving, batch offline training, cache reuse, and monitoring/alerting with budget thresholds.
On public clouds, these capabilities are typically delivered through general-purpose service categories such as container platforms, message queues, object storage, logging, and monitoring/alerting. Platforms such as Baidu AI Cloud offer these general categories; selection should be based on standardized interfaces and portability.
8. Implementation Recommendations and Risk Control
- Build evaluation before building evolution; unmeasured self-evolution cannot be controlled.
- Start with external evolution and defer internal evolution: the skill loop can show results within weeks, while the weight loop requires data accumulation.
- Prevent experience contamination: skills and memory must be auditable, downweightable, and rollback-capable.
- Ensure data compliance: trajectories may contain sensitive code and user data, so they require de-identification, tiered storage, and access auditing.
- Make costs predictable: set separate budgets and circuit breakers for review, synthesis, and training.
The essence of self-evolution is not “making the model smarter by itself,” but turning the engineering system into a machine that continuously converts execution experience into reusable assets. The dual-drive mechanism provides two complementary paths, and the harness provides safety and operational boundaries. Only when all three are in place can agent capabilities achieve long-term improvement.
