Self-Evolving AI Agent Architecture: Layered Memory and Multi-Backend Deployment
Learn how to design long-running AI agents with a controlled learning loop, layered memory, interchangeable execution backends, and model routing. This article covers trace-based skill generation, sandbox evaluation, retrieval cost controls, deployment abstractions, and the governance and metrics needed to keep agent behavior auditable and reversible.
1. Design Challenges and Goals
Comparing individual AI agent products can quickly become a discussion of changing versions and feature lists. The more durable questions concern reusable architecture:
- Can a long-running agent turn task histories into reusable experience?
- Can it maintain retrieval quality and control inference costs as memory grows?
- Can it move smoothly between execution environments and models with different capabilities?
These questions suggest five architectural layers: interaction and control, execution backends, memory and indexing, learning and skills, and governance and observability.
Traditional static execution engines treat “skills” as fixed blocks of code written by developers or contributed by a community. The agent schedules and executes them. This approach offers predictable behavior and straightforward debugging, but its capabilities remain bounded. When business requirements change, people must update prompts, toolchains, or workflows.
A self-evolving architecture does not give a model unrestricted permission to modify itself. Instead, it establishes a controlled engineering loop:
Task traces → reflection and root-cause analysis → candidate skills → sandbox evaluation → canary rollout → rollback or retirement
The design has four goals:
- Continuous improvement: Extract reusable patterns from successful and failed tasks rather than reasoning from scratch every time.
- Controlled costs: Prevent growing memory from causing linear growth in context size by using layered storage and on-demand retrieval.
- Deployment flexibility: Decouple execution environments, model services, and storage components through abstract interfaces.
- Governable safety: Apply permissions, auditing, and rollback mechanisms to generated skills, persistent memory, and remote execution.
2. Overall Architecture: Separate Control and Execution
Separate the control plane from the execution plane.
The control plane handles task planning, context construction, policy decisions, model routing, and state-machine management. The execution plane handles tool calls, code execution, file processing, browser operations, and other controlled actions. Memory and skills form an independent data plane that the control plane accesses through standard interfaces.
A typical task follows this flow:
- Receive the user request and create a task identifier and permission context.
- Retrieve candidate information from session memory, long-term notes, skill memory, and user preferences.
- Select models and tool strategies based on task complexity, cost limits, and latency requirements.
- Execute tool calls in the selected backend, recording complete traces, logs, and artifacts.
- Summarize the result and assess whether the task succeeded or requires human confirmation.
- Write the structured trace to session memory and, when appropriate, trigger reflection and candidate skill generation.
- Record metrics, audit logs, and cost details for subsequent optimization.
This separation makes execution backends replaceable, model services routable, memory manageable by lifecycle, and the learning loop independently deployable through staged rollouts.
3. The Learning Loop: From Traces to Reversible Skills
3.1 When to Trigger Reflection
Running a full retrospective after every conversation creates unnecessary cost and noise. Use configurable triggers instead, such as:
- Completion of every N tasks.
- A complex task.
- A failed tool call.
- An explicit user correction.
- A successful example marked by a human reviewer.
- Repeated tasks of the same type exceeding a threshold.
These thresholds should be configuration settings, not hard-coded rules.
3.2 Steps in the Learning Loop
- Normalize the trace. Record the input, context summary, plan, tool-call arguments, return values, exceptions, duration, cost, and human feedback.
- Evaluate the outcome. Distinguish success, partial success, failure, and cases where the result is correct but the process is high-risk.
- Analyze root causes. Determine whether failures resulted from missing information, incorrect retrieval, inappropriate tool selection, invalid arguments, insufficient permissions, or model reasoning errors.
- Synthesize a skill. Package reusable steps into a structured skill definition with applicable scenarios, prerequisites, steps, an allowed-tool list, failure handling, and examples.
- Run static checks. Check for unauthorized tools, sensitive information, infinite loops, and operations that exceed permissions.
- Evaluate in a sandbox. Use historical replay datasets, synthetic cases, and adversarial cases in an isolated environment to assess success rates and risks.
- Register the version. Move approved candidates into shadow or canary mode, recording provenance, evaluation scores, dependency versions, and rollback points.
- Roll out or retire. Monitor production metrics and downrank, disable, or delete skills with low value or high risk.
3.3 Illustrative Pseudocode
function onTaskFinished(task):trace = normalizeTrace(task)verdict = evaluateOutcome(trace)if shouldReflect(task, verdict):lesson = reflect(trace, verdict)candidate = synthesizeSkill(lesson)if staticCheck(candidate).passed:score = sandboxEvaluate(candidate, replaySet)if score >= baseline + margin:registry.add(candidate,status = "shadow",provenance = trace.id,version = nextVersion())scheduleCanary(candidate)memory.writeEpisodic(trace)
3.4 Risk Controls
Generated skills constitute an internal supply chain and require version management and security review.
- Apply least-privilege tool access. Skills may invoke only explicitly allowed tools.
- Require human confirmation for high-risk actions, such as external communications, financial operations, and production changes.
- Do not allow skill packages to execute arbitrary code directly. Parse them into controlled steps or run them in a restricted sandbox.
- Make persistent failure patterns forgettable or isolatable so incorrect lessons do not repeatedly contaminate later tasks.
- Run regression tests before releasing important skills to ensure that learning one workflow does not degrade another class of tasks.
4. Layered Memory: Governable Data Structures
4.1 Memory Layers
A single memory file is transparent and easy to edit. Over long periods, however, it becomes difficult to retrieve from, expands the context window, and creates maintenance overhead.
A layered approach separates memory by purpose:
- Working memory: Current task context, temporary variables, and short-term plans, compressed and archived when the task ends.
- Session memory: Per-session summaries, key conclusions, user feedback, and unfinished items.
- Knowledge notes: Stable facts, business rules, glossaries, and reusable reference material shared across sessions.
- Skill memory: Validated workflows, tool-use patterns, failure-handling strategies, and applicability boundaries.
- User profiles: Preferences, constraints, permissions, preferred formats, and interaction habits, classified by sensitivity.
4.2 Storage and Indexing
A common storage design combines several mechanisms:
- Structured metadata for type, scope, source, confidence, sensitivity, and lifecycle.
- Full-text indexes for keyword retrieval.
- Vector indexes for semantic retrieval.
- Model-generated summaries for compressing long documents and building summary pyramids.
Retrieval should first gather candidates, then rerank and trim them to a budget. It should not place the entire historical record into the model context.
record MemoryItem:idkind // session | note | skill | profilescope // user | project | tenant | globalcontentsummarykeywordsvectorRefsourceconfidencesensitivityttlversion
4.3 Cost Control
Cache-aware design should extend throughout context construction:
- Separate stable prefixes from changing content to reduce repeated-prefix inference overhead.
- Use a summary pyramid, selecting original text, paragraph summaries, or topic summaries as needed.
- Set limits for retrieved candidates, reranked candidates, and context tokens; automatically trim content that exceeds the budget.
- Deduplicate content and use hash checks to avoid storing the same fact repeatedly.
- Periodically compress, merge, or retire low-value memories, while giving high-value memories greater weight and longer retention.
- For long-running tasks, summarize on write and rerank on read to reduce the cost of assembling context at runtime.
Illustrative retrieval pseudocode:
function buildContext(query, user, budget):a = keywordSearch(query, scope = user)b = vectorSearch(query, scope = user)c = recentImportant(user)candidates = deduplicate(a + b + c)ranked = rerank(query, candidates)selected = []cost = 0for item in ranked:piece = summarizeIfNeeded(item, remainingBudget(budget, cost))if cost + size(piece) <= budget:selected.add(piece)cost += size(piece)return selected
Evaluation should track at least retrieval recall and precision, the proportion of stale memories, context tokens per task, the human correction rate, and whether memory actually improves task success.
5. Multi-Backend Execution and Model Routing
5.1 Execution Backend Abstraction
Execution environments have different requirements for isolation, elasticity, latency, and cost. Local processes may suit individual development, containers may suit team environments, orchestration platforms may suit enterprise clusters, and serverless functions may suit temporary batch workloads.
Define a common execution interface to avoid coupling the system to one runtime:
interface ExecutionBackend {prepare(workspace, spec) -> RuntimeHandlestart(handle, command) -> ExecutionIdstreamLogs(executionId, callback)cancel(executionId)collectArtifacts(executionId) -> ArtifactRef[]cleanup(handle)}
The interface must account for timeouts, cancellation, resource quotas, idempotency keys, artifact collection, and error classification.
Keep state external wherever possible. Store task state in the control plane, file artifacts in object storage, and logs in a centralized logging system. This prevents backend changes from making tasks unrecoverable.
5.2 Model Routing
Model services also need an abstraction layer. Routing can consider task type, context length, structured-output requirements, latency limits, cost limits, and availability, with fallback when a model fails.
Avoid hard-coding a particular model’s capabilities into business logic. Match requirements using capability labels and capability checks instead. For workflows with strict requirements, validate model outputs against a schema and validate tool-call arguments.
5.3 Migrating from Static File-Based Memory
Migration can proceed in four stages:
- Parse existing text records and classify them as facts, workflows, preferences, or temporary conversations.
- Deduplicate and merge records, then generate summaries and keywords.
- Revalidate tool permissions for skill-related content and evaluate it through sandbox replay.
- Run the new system in shadow mode, comparing task success, cost, and human intervention rates with the old system before gradually shifting traffic.
Preserve a rollback path throughout migration. Do not delete the old data in a single step.
6. Implementation and Evaluation Checklist
A phased implementation is preferable:
- Establish observable task traces and tool-call audits. Reliable reflection requires reliable traces.
- Introduce memory layers and retrieval budgets. Address retrieval quality and context costs first.
- Build the skill registry, version management, and sandbox evaluation. Enable automatic skill generation only after these controls exist.
- Abstract execution backends and model routing. Validate switching and rollback in a test environment first.
- Complete permission controls, sensitive-data redaction, auditing, and human confirmation mechanisms.
Evaluation should cover:
- Task success rate.
- Tool-call accuracy.
- Average and P95 latency.
- Cost per task.
- Memory retrieval quality.
- Skill reuse rate.
- Production rollback count.
- Human correction rate.
- High-risk action interception rate.
When using general-purpose cloud infrastructure, such as Baidu AI Cloud, container platforms, object storage, logging services, monitoring, and alerting can support elastic scaling and centralized governance. The core architecture should nevertheless remain interface-neutral and portable.
7. Suitable Use Cases and Boundaries
This architecture suits long-running customer service, personal assistants, content operations, internal workflow automation, and ongoing data organization. These workloads benefit from accumulating capabilities and reusing memory across sessions.
For highly deterministic, tightly audited, or high-risk production workflows, restrict automatic learning and use human approval and fixed procedures.
The purpose of self-evolution is not to replace engineering governance. It is to reduce repetitive work within controlled boundaries and convert experience into engineering assets that can be validated, rolled back, and audited.
The learning loop determines whether an agent can improve. Layered memory determines whether it can retain important information reliably over time while controlling costs. Multi-backend execution and model routing determine whether it can adapt from local development to enterprise clusters.
Building these capabilities as independent, observable, and reversible infrastructure offers more lasting value than chasing the feature list of any single agent product.
