AI Agent Architecture Design for Self-Improving Agents: Closed-Loop Learning, Layered Memory, and Decoupling

    This article explains how to design AI agents that improve over time instead of resetting after every conversation. It covers a three-stage closed-loop learning process that turns completed tasks into reusable, parameterized skill files, a three-layer memory structure for preserving information across sessions, and an architecture that separates reasoning, skills, memory, and tool execution. It also outlines reliability and safety practices such as negative examples, versioning, human approval for high-risk actions, and deployment considerations for long-running, observable systems.

    1. The Starting Problem: Why Agents Reset When the Conversation Ends

    Many developers have had this experience: in one session, an assistant works with you to refine a complex deployment script, with clear logic and a shared understanding of the context. You close the window and reopen it, and the assistant behaves like a different agent, knowing nothing about the decisions, preferences, and pitfalls from before. You have to restate the background, paste the logs again, and correct the same misunderstandings.

    This is not a one-off reasoning failure. It is a structural limitation of most mainstream conversational agents: the system is stateless. Each model response is an independent computation based on the current context. When the session ends, the context is released, and the judgments, parameter choices, and failure lessons formed during the task do not automatically carry into the next round. As a result, the agent stays “smart but unfamiliar”: it can complete a single task well, but it cannot accumulate experience for a specific user, project, or operational routine.

    To make an assistant genuinely usable and trustworthy, three capabilities need to be added: first, turn successful experience into reusable assets through closed-loop learning; second, keep information alive across sessions with layered memory; third, decouple the architecture so that memory, skills, and the reasoning core are not tightly bound, making them easier to replace and evolve. The following sections cover each in turn.

    2. Closed-Loop Learning: Turning “Done Once” into “Able to Do It Next Time”

    The execution flow of a traditional agent is linear: receive an instruction, plan steps, call tools, return results, and clear experience when the task ends. A more mature engineering approach adds an explicit loop at the end of the flow: once a task is judged successful, trigger experience extraction and consolidation.

    2.1 A Three-Stage Learning Loop

    • Extraction: Pull key decision points from the completed task, such as why a particular image version was chosen, why configuration was validated before applying changes, and what order was used to roll back on failure.
    • Consolidation: Write the experience into a structured skill file, typically containing trigger conditions, pre-checks, execution steps, exception branches, and caveats.
    • Reuse: When a similar task appears again, retrieve and load the skill first, skip lengthy trial and error, and go straight to controlled execution.

    2.2 Skill Files Should Be Parameterized, Not a Running Log

    The value of a skill file depends on how reusable it is. If it only records “which commands were run this time,” it cannot be applied to the next project. The recommended approach is to use variable templates and abstract the variable parts into placeholders:

    1. ---
    2. name: container-deploy
    3. trigger: keywords include "deploy/release/go-live" and an orchestration file exists
    4. params: [image_name, tag, replicas, env_file]
    5. ---
    6. 1. Validate that params are complete; if anything is missing, confirm with the user and do not fill in defaults on your own
    7. 2. Pull {image_name}:{tag} and verify the digest rather than relying on the tag alone
    8. 3. Apply config {env_file} and run static checks first
    9. 4. Perform a canary release with {replicas} replicas, and watch error rate and latency
    10. 5. On failure, roll back in reverse order and output a diagnostic summary

    Parameterization brings three direct benefits: one skill can cover multiple projects; execution boundaries are clear and easy to audit; and skills can be composed into higher-level workflows. If the skill format follows an open, general exchange convention, skills can also be migrated and shared across different agents, avoiding experience being locked into a single runtime.

    2.3 Automatic Optimization of Prompts and Skills, with a Human in the Loop

    On top of the loop, an automatic optimization mechanism can be added: use evolutionary search to iteratively improve skill descriptions, tool descriptions, and system prompts, with a set of evaluation samples as the fitness function, keeping the better-performing candidates. This kind of method usually requires no model retraining and can be done entirely on the inference side, keeping costs under control.

    But the biggest risk of automatic optimization is goal drift: the optimizer may exploit gaps in the evaluation set and produce prompts that “look high-scoring but actually behave off-target.” Engineering practice should therefore hold to three constraints: submit optimization output as a change review that takes effect only after human merge; keep versioning and rollback capability; and isolate the evaluation set from real traffic to avoid overfitting.

    3. Layered Memory: Keeping Information Alive Across Sessions

    Skills alone are not enough; the agent also needs to “remember.” A practical approach is a three-layer memory structure, where each layer has a different responsibility and lifecycle.

    • Working memory: the current session context. It has small capacity and the lowest latency, and keeps only the information required for the current task, avoiding context bloat that dilutes attention.
    • Long-term memory: structured entries persisted across sessions, such as user preferences, project conventions, environment topology, and common parameters. On write, apply deduplication, conflict resolution, and confidence labeling; on read, recall by relevance rather than injecting everything.
    • External memory: put large, low-frequency-changing material in external storage and retrieval services, and fetch fragments on demand at runtime. Logs, monitoring metrics, and document repositories all fit in this layer.

    There are several key points in the engineering implementation. First, writes need a threshold: only store confirmed facts and reusable conclusions, and avoid writing one-off intermediate noise into long-term memory. Second, reads need a limit: set caps on the number of recalled entries and the token budget to prevent “the more memory, the dumber.” Third, memory must be able to expire: set expiration and review mechanisms for entries so that outdated conclusions are automatically downgraded after the environment changes. Fourth, sensitive information must be classified: credential-type information does not enter the memory layers; only a reference identifier is stored, and the runtime exchanges it temporarily through key management capabilities.

    4. Architectural Decoupling: Maintainability from Three-Layer Separation

    If the reasoning core, memory, skills, and tool gateway are all coupled in one process, the system quickly becomes a monolith that is hard to maintain. The recommended split is:

    1. Reasoning and planning layer: only responsible for understanding the goal, breaking down steps, and selecting tools; it persists no state.
    2. Capability and skill layer: manages skill definitions and versions as files or a registry, supporting hot loading and canary rollout.
    3. State and memory layer: consolidates memory read/write, retrieval, and expiration policies, and exposes a simple interface.
    4. Tool and execution layer: all external side effects (deployment, changes, queries) go through a unified gateway with permission checks, audit logs, and rate limiting.

    The direct benefit of decoupling is low replacement cost: swap the model without touching memory, swap storage without touching skills, and add tools without changing the core. It also makes security boundaries clearer: high-risk actions are forced through secondary confirmation and approval at the gateway, rather than scattered across prompts relying on “voluntary compliance.”

    5. Reliability and Safety: A Required Course for Self-Improving Agents

    A system that learns also amplifies errors: once a wrong experience is consolidated, it may be reused repeatedly. A “negative experience” mechanism is therefore required: failed tasks also generate records, but are marked as counterexamples, used at retrieval time to avoid rather than execute. In addition, the system should have: versioning of skills and memory, auditable changes, and replayable execution results; human confirmation by default for high-risk operations; and normalized evaluation and regression, running baseline cases every time a prompt or skill is updated.

    In terms of deployment, this kind of system usually needs to be online long-term, with externalized state and observability support. It can be run on Baidu AI Cloud’s container platform for the runtime, with object storage holding skill and memory snapshots, a message queue decoupling the asynchronous learning flow, and log services plus monitoring and alerting covering the execution chain, so that “self-improvement” becomes an operable, governable engineering capability rather than a one-time demo.

    6. Conclusion

    The next stage of competitiveness for agents lies not in how impressive a single answer is, but in whether the collaboration process can be turned into an organizational asset: experience that can be consolidated, memory that can be retrieved, architecture that can be replaced, and behavior that can be audited. Closed-loop learning solves “whether it can accumulate,” layered memory solves “whether it can remember,” and architectural decoupling solves “whether it can evolve over the long term.” Together, these three turn an assistant from a one-off tool into a self-improving digital counterpart that truly captures working habits.