Evolving AI Agent Architecture: Closed-Loop Learning, Layered Memory, and Decoupling

    This article breaks down why conventional conversational agents lose all knowledge when a session ends, and presents a reusable design methodology for self-evolving agents across three dimensions: closed-loop learning that turns task experience into reusable skills, automatic optimization of prompts and skills, layered memory that separates short-term context from long-term knowledge and external retrieval, and architecture decoupling across runtime, capability, and storage layers. It also covers evaluation metrics, common pitfalls, and security considerations for teams building internal assistant platforms.

    1. The Starting Problem: Why Conversational Assistants “Lose Memory on Restart”

    In the previous session, the assistant had just finished debugging a complex deployment workflow with you. You close the window and reopen it, and it immediately becomes a stranger with no knowledge of your project. You have to explain the project structure, environment variables, and every pitfall you already hit, all over again.

    This is not a capability gap in any single model. It is a structural trait shared by most mainstream conversational agents today: the session lifecycle and the knowledge lifecycle are forcibly bound together, so when the session ends, the knowledge is wiped.

    From an engineering perspective, these systems behave essentially like stateless functions: context goes in, a result comes out, and once the process exits, no transferable internal state remains. This leads to three direct consequences:

    • Repeated cost: similar tasks require fresh reasoning every time, keeping token consumption and response latency high.
    • Broken experience: user preferences, established conventions, and past decisions never accumulate, making collaborative trust hard to build.
    • Uncontrollable quality: the same task may be handled differently across sessions, producing high output variance that is difficult to fit into engineering standards.

    So the industry is shifting its focus from “how strong is the model” to “does the agent have an architecture that can keep evolving.” This article takes self-evolving agents as its subject and lays out a reusable design methodology across three dimensions: closed-loop learning, layered memory, and architecture decoupling.

    2. Closed-Loop Learning: Turning Task Experience into Reusable Skills

    The execution chain of a traditional agent is linear: receive instruction → plan steps → call tools → return result. When the task ends, the experience evaporates. A growth-capable architecture adds a loop at the end of that chain: once a task is judged successful, experience extraction and consolidation are triggered automatically.

    A pragmatic loop breaks down into four steps:

    1. Result verification: use verifiable signals as the success criterion, for example a script exiting with code 0, all test cases green, or a health check passing. This avoids “it felt fine” style misjudgment.
    2. Experience extraction: pull the key decision points, failed branches, and workarounds out of the execution trace, rather than simply saving the full log.
    3. Structure consolidation: write a skill file with metadata containing at least five fields: trigger conditions, prerequisites, execution steps, verification method, and cautions.
    4. Retrieval and reuse: when a similar task appears again, match against the skill library first. On a hit, skip the lengthy reasoning; on a miss, fall back to full planning.

    Skill files should be parameterized rather than hardcoding the specific values from one particular run. An example:

    1. ---
    2. name: container-deployment
    3. triggers: ["deploy", "release", "rollout"]
    4. params: [image_name, tag, replicas]
    5. preconditions: ["image registry credentials configured", "target environment has sufficient resources"]
    6. verify: ["health check returns success", "sample of key endpoints is reachable"]
    7. notes: ["roll out gradually first", "rollback script must be prepared in advance"]
    8. ---
    9. Steps:
    10. 1. Verify ${image_name}:${tag} can be pulled
    11. 2. Apply the deployment manifest and wait for ${replicas} replicas to become ready
    12. 3. Run the checks listed in verify
    13. 4. On failure, roll back to the previous version using the rollback script

    Parameterization brings two benefits. First, one skill can adapt to different projects and environments. Second, skills become testable: a fixed parameter set can be used for regression verification. If a skill uses an open, general-purpose description format (cross-tool skill description conventions already exist in the industry), it can be migrated across agents, avoiding lock-in to a single runtime.

    3. Automatic Optimization of Prompts and Skills: Continuously Refining “Experience”

    Curating skills by hand alone becomes hard to maintain at scale. A further step is to introduce an automatic optimization pipeline that iteratively improves skill text, tool descriptions, and system prompts. The general idea of evolutionary prompt optimization can be borrowed here: keep the better-performing batch of candidates, generate new candidates through mutation and crossover, evaluate them across multiple task samples, and retain the winners. This forms an iterative process similar to gradient descent, except the optimization target is natural language text rather than model parameters.

    Four guardrails are mandatory in engineering practice:

    • No model retraining: evaluation and selection happen entirely through inference APIs, consuming no training compute.
    • Evaluation set first: prepare a fixed sample set covering typical and boundary scenarios to prevent overfitting to the evaluation set.
    • Auditable changes: optimization outputs are submitted as change requests, keeping diffs and evaluation scores.
    • Effective only after human confirmation: maintainers review and merge, preventing the agent from gradually drifting away from the original intent under no supervision, the so-called goal drift.

    It is worth stressing that automatic optimization only addresses whether the wording is clearer and the steps more complete. It cannot replace judgment about business correctness, which is why evaluation set quality and the review mechanism are the real threshold for this system.

    4. Layered Memory: Dividing Labor Between Short-Term Context, Long-Term Knowledge, and External Retrieval

    A single store cannot satisfy speed, cost, and capacity requirements at the same time. The mature approach is to layer memory:

    • Session short-term memory: holds the current task’s context and intermediate artifacts, archived when the session ends, optimized for low latency.
    • Long-term persistent memory: holds user preferences, project conventions, environment parameters, and conclusions from past decisions. Stored in a structured way, searchable, updatable, and expirable.
    • External retrieval memory: keeps large-volume information such as documents, code repositories, and tickets outside the system, fetched on demand through retrieval so the context does not grow indefinitely.

    Three rules are recommended when writing to long-term memory: write only conclusive, reusable information; tag each memory with its source and confidence; allow expiration and conflict resolution (new evidence overrides old conclusions while versions are retained). A sample structure:

    1. {
    2. "memory_id": "pref-deploy-001",
    3. "type": "preference",
    4. "scope": "project/A",
    5. "content": "Production releases must be gradual and keep one-click rollback",
    6. "source": "session-2026-02-11",
    7. "confidence": 0.92,
    8. "version": 3,
    9. "expire_at": null
    10. }

    Once memory is layered, the context budget becomes a manageable resource: short-term memory controls window size, long-term memory is injected on demand through hybrid vector and keyword retrieval, and bulky material always stays in external storage.

    5. Architecture Decoupling: Letting the Runtime, Capability, and Storage Layers Evolve Independently

    To keep the capabilities above maintainable over the long term, the system must be split into three layers with clear boundaries that communicate through standard interfaces:

    • Runtime layer: handles session scheduling, context assembly, and security and permission control.
    • Capability layer: registers tools and skills as plugins, declares input and output schemas, and can be upgraded or replaced independently.
    • Storage layer: keeps the memory store, skill library, logs, and evaluation data separately, supporting backup and migration.

    The direct benefit of decoupling is controlled replacement cost: switching model vendors, changing the vector retrieval approach, or adjusting the memory strategy does not require rewriting business logic. On the cloud, general-purpose capability categories can be composed as needed, for example using object storage for skills and archived sessions, a container platform to host the runtime, a message queue for asynchronous experience extraction, and logging plus monitoring and alerting services to observe task success rate and skill hit rate.

    Security and compliance are also part of the architecture. Skills and memories may contain environment details, so sensitive information should be masked, access permissions isolated per project, and traceable records kept for all automatic writes.

    6. Evaluation and Common Pitfalls

    To judge whether a growth-capable architecture actually works, four kinds of metrics are worth observing: average time and token cost for similar tasks, skill hit rate, first-attempt task success rate, and human correction rate. If the skill hit rate rises but the first-attempt success rate does not, it usually means the extraction step also consolidated paths that succeeded only by chance.

    Common pitfalls include: treating a full conversation log as a skill (noisy and impossible to parameterize); lacking a success criterion, which amplifies wrong experience; memory that only grows and never shrinks, causing context pollution; and automatic optimization without a fixed evaluation set, which inflates metrics. The respective countermeasures are structured templates, verifiable checks, expiration and conflict resolution, and a double gate of evaluation sets plus human review.

    7. Conclusion

    Moving from a “stateless calculator” to a “growing digital twin” depends not on swapping in a stronger model but on completing three pieces of infrastructure: a loop that consolidates experience into parameterized skills, a layered and expirable memory system, and a cleanly decoupled architecture, always keeping human review as a guardrail. For teams building internal assistant platforms, general-purpose capabilities from Baidu AI Cloud such as its container platform, object storage, logging service, and monitoring and alerting can serve as the foundation for this kind of architecture, so that every collaboration with an agent leaves behind genuinely reusable assets.