Agent Architecture Design for Self-Improving AI Agents

    This article explains why most conversational AI agents forget everything once a session ends and how to design agents that improve over time. It covers closed-loop learning that turns completed tasks into reusable skill files, the human-in-the-loop safeguards required for automatic prompt and skill evolution, a three-tier memory system spanning working, long-term, and external storage, and an architecture that decouples models, skills, memory, tools, and evaluation. A phased rollout plan and common pitfalls are also included.

    1. The Problem: Why Most Agents Forget Everything After a Chat

    Developers often run into the same scenario. Within a single session, an agent helps write a deployment script, debug it, and tune it. Close the window, reopen it, and the agent knows nothing about the context — the background has to be explained all over again. This is not a limitation of any particular model but a structural trait shared by mainstream conversational agents: the session lifecycle is the knowledge lifecycle. When the process ends, the state resets to zero.

    From an engineering perspective, these systems behave much like stateless functions: they take a prompt and context as input, return a result, and retain no reusable information. The upside is simple deployment, easy horizontal scaling, and clear privacy boundaries. The downside is that every task starts from scratch, repeatedly burning tokens and latency, with no way to accumulate an organization’s operating conventions and experience.

    The goal of a self-improving agent is to keep the advantages of a stateless service while adding a controlled state layer and a learning loop, evolving the system from a passive tool into a digital counterpart that accumulates working habits. What matters here is not model size but three engineering capabilities: closed-loop learning, persistent memory, and architectural decoupling.

    2. Closed-Loop Learning: Turning One-Off Tasks into Reusable Skills

    The traditional agent execution path is linear: receive instruction → plan steps → call tools → return result. Once the task is done, the experience is gone. Closed-loop learning adds a feedback path at the end: once a task is judged successful, the key steps and decision rationale are extracted automatically and written into a structured skill file that similar tasks can load directly later.

    A practical loop has four stages:

    1. Task execution and trace recording: capture tool calls, parameters, return codes, elapsed time, and failed retries.
    2. Success detection and experience extraction: use verifiable signals (tests passing, a successful build, healthy checks) as the trigger, so accidental success is not hardened into a skill.
    3. Skill generation and structuring: describe triggers, prerequisites, execution steps, parameter placeholders, and caveats in a templated file.
    4. Reuse and evaluation: when a similar task matches a skill, skip the lengthy reasoning, and keep tracking success rate and average duration as the basis for retiring or revising the skill.

    An illustrative skill file structure (Markdown with front matter):

    1. ---
    2. name: container_deploy
    3. triggers: ["deploy a containerized service", "release a new version"]
    4. params: { image_name: string, tag: string, replicas: int }
    5. preconditions: ["image registry is reachable", "orchestration platform credentials are configured"]
    6. success_check: "health check returns ready three times in a row"
    7. ---
    8. ## Steps
    9. 1. Validate parameters and credentials;
    10. 2. Render the orchestration manifest, injecting {image_name} and {tag};
    11. 3. Roll out {replicas} replicas as a canary;
    12. 4. Run the health check and roll back on failure.

    A skill file is not a log; it is executable knowledge. Three design principles are worth emphasizing. First, parameterization: use placeholders so the skill fits different projects. Second, verifiability: every skill must be bound to an objective success signal. Third, portability: adopt a widely used skill description convention so skills can be shared across different agents.

    3. Automatic Evolution of Prompts and Skills: Keep a Human in the Loop

    Once enough skills have accumulated, an automatic optimization mechanism can be introduced to iterate on skill descriptions, tool descriptions, and system prompts. A common industry approach borrows from evolutionary search: maintain a set of candidates, filter and mutate them against measurable criteria (task success rate, number of steps, token consumption), and keep the better solutions each round. This is typically far more efficient than a pure reinforcement learning training path, and it needs no GPU training — only API calls.

    Automatic evolution must have safety boundaries, or goal drift becomes likely:

    • Fixed and stratified evaluation sets: cover normal, boundary, and adversarial cases to prevent overfitting to the evaluation set.
    • Submit changes as patches: each optimization produces a reviewable diff that a human reviews before merging.
    • Canary rollout and rollback: validate the new version on shadow traffic first, and roll back automatically if metrics degrade.
    • Immutable constraints: permission scope, data boundaries, and audit requirements are hard constraints and never participate in evolution.

    4. A Three-Tier Memory System: Where State Comes From and Where It Goes

    Persistence is the carrier of growth. A layered design by lifecycle is recommended:

    • Working memory: the current session context, released when the session ends, keeping latency low.
    • Long-term memory: user preferences, environment topology, past decisions, and the skill index, persisted in a database and injected by similarity retrieval.
    • External memory: documents in enterprise knowledge bases, ticketing systems, code repositories, and object storage, pulled on demand through retrieval plugins instead of stuffing everything into the context.

    Retrieval and writes need governance. On the write side, deduplicate, resolve conflicts, and tag freshness. On the read side, apply permission filtering and inject only the minimum necessary. Illustrative logic:

    1. def build_context(task, user, session):
    2. ctx = session.recent(limit=8) # working memory
    3. ctx += memory.search(task, top_k=5, acl=user) # long-term memory with ACL filtering
    4. ctx += kb.query(task, scope=task.project) # external knowledge pulled on demand
    5. return dedup_and_truncate(ctx, budget=6000) # deduplicate and trim to budget

    5. Architectural Decoupling: Make Capabilities Replaceable, Observable, and Governable

    A self-improving system has five variable parts — model, skills, memory, tools, and evaluation — and they must be decoupled:

    • Separate the model layer from the capability layer: the model is replaceable, and skills and memory are not bound to a specific model.
    • Standardize the tool layer: describe each tool’s name, parameter schema, and error codes through a unified interface, making registration and authentication straightforward.
    • Make the memory layer pluggable: persistence can be a relational database, a vector retrieval service, or object storage, adapted through an interface.
    • Evaluation and observability: record the full call trace, tokens, and elapsed time end to end, wire up logging and monitoring with alerts, and track core metrics such as success rate and rollback rate.

    Security and compliance are architectural constraints too: centrally managed credentials, least privilege, masking of sensitive data, and an audit trail for operations. High-risk actions against internal enterprise systems should require explicit human confirmation.

    6. Rollout Path and Common Pitfalls

    A four-step rollout is recommended. Start with a read-only assistant to validate retrieval and permissions. Then open low-risk write operations and introduce skill accumulation. Next, enable automatic evolution while keeping human merging. Finally, add multi-agent collaboration and skill sharing.

    Common pitfalls include hardening failed traces as experience, skill count growth that adds retrieval noise, a single evaluation set that invites drift, no context budget control that sends costs out of control, and missing permission filters that lead to unauthorized reads. The countermeasures are clear success criteria, periodic retirement of low-hit skills, stratified evaluation, token budgets, and access control applied up front.

    In short, an agent’s “growth” is not model self-adaptation but an engineering loop built from state, skills, and evaluation. Writing experience into structured assets that are verifiable, reusable, and governable is what lets a system genuinely get stronger with use. Such platform capabilities can be built on demand from the relevant Baidu AI Cloud product categories.