AI Agent Architecture Design for Self-Improving Agents
This article analyzes why conventional conversational agents forget user context across sessions and explains how to fix it at the architecture level. It covers a closed-loop learning pipeline that turns successful task trajectories into reusable, parameterized skills, a three-layer memory design for cross-session persistence, and a decoupled component architecture that lets reasoning, skills, memory, and execution evolve independently. It also outlines a four-step adoption path, the metrics for evaluating whether self-improvement actually works, and the security and observability controls required to keep the system bounded.
1. The Starting Problem: Why Conversational Agents Forget Everything
In the previous session, the agent had just helped you write a fairly complex deployment script. The indentation, variable naming, and rollback strategy all matched your conventions. You close the window and reopen it, and the agent behaves as if it has never seen you, asking for the same basic information all over again. Many developers blame this on the model “not being smart enough,” but from an engineering perspective this is an architecture problem, not a model capability problem.
Most mainstream conversational agents are stateless functions at runtime: they take context as input, produce output, and release the context once the session ends. The behavior can be expressed with minimal pseudocode:
def chat(user_input, session_context):# session_context is destroyed along with the sessionreturn model.generate(user_input, session_context)
This design has three direct consequences:
- Experience cannot accumulate: everything is cleared when the task finishes, so similar tasks require reasoning from scratch next time, and token cost and latency grow linearly.
- Personalization is not sustainable: user preferences, project conventions, and past pitfalls have nowhere to live.
- Capability boundaries are fixed: as long as the model weights stay unchanged, the agent’s “capability set” is frozen on the day it is deployed.
So to move an agent from a passive tool to a sustainable collaborator, a “digital twin” of sorts, three engineering capabilities must be added outside the model: a writable experience layer, a retrievable memory layer, and a replaceable component layer. Each is broken down below.
2. Closed-Loop Learning: Turning One-Off Tasks into Reusable Assets
The traditional agent pipeline is linear: receive instruction → plan → execute → return. The key change is to add a return path at the end, so that successfully executed trajectories are saved in a structured form and preferentially reused in similar tasks.
2.1 The Three-Stage Loop
- Extract: after a task succeeds, distill the key decision points from the execution trajectory, for example “verify the port is free before starting the container” or “when hitting a permission error, check the mount path first,” rather than copying the entire log.
- Materialize: write the result into a structured skill file, which typically contains five fields: trigger conditions, prerequisites, execution steps, failure rollback, and caveats.
- Reuse: when a new task matches the trigger conditions, load the skill directly, skip the lengthy reasoning, and only reason locally about the differences.
A sample structure for a parameterized skill file:
---name: container_deploytrigger: ["deploy", "release", "ship service"]params: [image_name, tag, replicas]---Steps:1. Verify image {image_name}:{tag} can be pulled2. Check remaining resources in the target environment3. Roll out {replicas} replicas gradually and watch health checksRollback: keep the previous version and switch back on failureNote: production changes require a second confirmation
Parameterization is the dividing line that determines whether a skill is reusable. A record with a specific project name hard-coded is just a log; only one with placeholders and trigger conditions is an asset. It is advisable to follow an open, general skill description specification for the skill format, so skills can be migrated between different agent runtimes and avoid creating a new form of lock-in.
2.2 Automatic Optimization of Prompts and Skills
Relying on manual skill authoring alone improves coverage slowly. A more engineering-driven approach is to introduce an automatic optimization loop: use task success rate, number of steps, and number of human interventions as evaluation metrics, and iteratively search over skill text, tool descriptions, and the system prompt. A common industry practice is evolutionary-search-based prompt optimization (keep better-performing candidates, apply crossover and mutation, and optimize multiple metrics simultaneously along a Pareto frontier). Its advantage is that it needs no gradients and no GPU training; it can be done entirely through inference API calls.
One control point must be emphasized: the output of automatic optimization should be submitted as a change proposal and merged only after human review, while version numbers and rollback capability are retained. Otherwise the agent may drift from the original intent under the appearance of “looking more efficient,” for example skipping a required confirmation step in order to shorten the sequence of steps.
3. Three-Layer Memory: Keeping Context Alive Across Sessions
Closed-loop learning solves “does it know how to do it”; the memory system solves “does it remember you.” Memory can be split into three layers with distinct responsibilities, and the layers should not be mixed.
- Working memory: the current session window. Small capacity, low latency, holding only what the current task needs.
- Long-term semantic memory: stable facts such as user preferences, project conventions, glossaries, and environment topology. Short entries, low update frequency, requiring deduplication and conflict resolution.
- Episodic memory: historical task trajectories and outcomes. Large in volume, best retrieved first and then injected. A typical approach combines vector retrieval with keyword retrieval, ranked with time decay and importance scoring.
There are two common mistakes in engineering implementation. The first is stuffing all history into the context in full, which loses control of cost and dilutes key information; the correct approach is “retrieve first, inject later,” with a token budget in place. The second is having no forgetting mechanism, so memory only grows and conflicting facts coexist; each memory entry should carry its source, timestamp, and confidence, and low-confidence entries should be archived periodically.
External memory can also be attached via plugins, with team knowledge bases, ticketing systems, and code repositories serving as retrieval sources. The agent is only responsible for querying and citing, not copying the raw data, which lowers storage cost and makes permission governance easier.
4. Architectural Decoupling: Letting the Three Capabilities Evolve Independently
If learning, memory, and execution are all folded into a single monolith process, any change to one layer forces a full regression test. The recommendation is to split into four component types by responsibility and communicate through explicit contracts:
| Component | Responsibility | Key contract |
|---|---|---|
| Reasoning core | Planning and generation | Stateless, horizontally scalable |
| Skill repository | CRUD and versioning of skills | Structured files + version numbers |
| Memory service | Write, retrieval, forgetting | Retrieval interface + permission filtering |
| Execution sandbox | Tool invocation and side-effect isolation | Allowlist + audit log |
The direct benefits of decoupling are that skills can be rolled out gradually, memory can be migrated, and execution can be replaced. For example, when swapping the underlying model, skills and memory do not need to be rebuilt; when connecting internal enterprise tools, you only need to extend the sandbox allowlist.
Security and governance must be designed at the same time: the execution layer defaults to least privilege, write and delete operations require mandatory second confirmation, and all tool invocations leave an audit trail. Plaintext credentials are prohibited in memory and skills; sensitive information is accessed by reference through a key management service. For observability, it is recommended to build dashboards for reuse hit rate, average number of steps, human intervention rate, and rollback count, so data can tell you whether self-evolution is actually effective.
5. Adoption Roadmap and Evaluation
A four-step rollout is recommended to avoid a one-time rewrite:
- First add out-of-session persistence, turning user preferences and project conventions into retrievable entries, and validate the improvement in cross-session experience.
- Then introduce skill materialization, starting with high-frequency, low-risk, verifiable tasks (such as environment checks, log inspection, and script template generation).
- Next connect automatic optimization, while keeping the human review gate and version rollback.
- Finally do component decoupling and sandbox isolation, filling in permissions and auditing.
Evaluation should not look only at “whether the answers are smarter,” but at four quantifiable metrics: reduction in time for similar tasks, skill reuse hit rate, number of human corrections, and rollback rate. If the reuse rate rises but the rollback rate rises with it, skill extraction quality is insufficient, and trigger conditions and prerequisite checks need to be tightened.
6. Conclusion
“Being able to grow” is not an extension of a model property but the result of system design: closed-loop learning turns experience into assets, layered memory sustains the relationship, architectural decoupling lets the three evolve independently, and human review plus auditing hold the boundary. For teams that want to build such capabilities on a cloud environment such as Baidu AI Cloud, it makes sense to first reuse general-purpose capabilities such as container platforms, object storage, log services, and monitoring and alerting to carry the skill repository, memory persistence, and effectiveness observation, and to focus effort on skill quality and governance rules themselves.
