AI Agent Plugin Architecture and Closed-Loop Learning: A Practical Guide

    This guide explains how to build AI agents that move beyond single-turn answers to deliver multi-step tasks. It covers a four-layer architecture separating the host, plugins, and execution layers, a tiered memory design for persistence and retrieval, skill self-evolution that turns completed task traces into reusable assets, tool ecosystems with multi-model routing, and orchestration techniques for long-running tasks. It also outlines evaluation metrics and deployment suggestions on Baidu AI Cloud, giving developers an engineering blueprint for agents that improve with use.

    1. Background: From Answering Questions to Delivering Outcomes

    Large language models are shifting from single-turn question answering to long-horizon, multi-step task delivery. In practice, developers run into three recurring pain points: limited context windows that cannot retain information across sessions; errors that accumulate and amplify once a task chain exceeds a certain number of steps; and reasoning that starts from scratch every time, with no reuse of existing solutions. A plugin-based agent framework addresses all three with an engineering answer: decouple channel integration, decision scheduling, and task execution so that each component has a clear role and complementary capabilities.

    It is worth stressing that plugin-based design is not simple feature stacking but a runtime architecture choice. The host platform owns the session entry point, permissions, and scheduling, while plugins own execution and experience accumulation, communicating through a standard protocol. This layering lets the system keep expanding its capabilities without modifying the host.

    2. Architecture Layers: Defining Responsibilities for the Host, Plugins, and Execution

    A deployable agent system is typically divided into four layers:

    • Access layer: connects to instant messaging, email, ticketing, or custom business systems, and handles authentication, rate limiting, and message normalization in one place.
    • Decision and scheduling layer: performs intent recognition, task decomposition, priority ordering, and resource allocation, deciding what to do, who does it, and when.
    • Execution layer: calls tools to perform real operations, including file read/write, web retrieval, code execution, and database queries.
    • Memory and skill layer: handles information persistence, experience abstraction, and reuse, and is the key to a system that gets smarter with use.

    Clear responsibility boundaries pay off in observability and replaceability. When execution fails, you can quickly tell whether the problem lies in the scheduling policy or a missing tool capability, instead of repeatedly digging through monolithic logic.

    3. Tiered Memory Architecture: Persistence Design Modeled on Cognition

    A single vector store struggles to be both memorable and searchable at the same time. A more mature approach in the industry is tiered memory:

    1. Working memory: the context and intermediate results of the current task, short-lived and frequently accessed.
    2. Episodic memory: records task goals, execution processes, and outcomes along a timeline, used for retrospection and review.
    3. Semantic memory: accumulates user preferences, working habits, domain terminology, and constraint rules as stable long-term knowledge.
    4. Procedural memory: stores “how to do it” in the form of skills, indexed in association with episodic memory.

    Retrieval usually follows a hybrid strategy: first a coarse filter using keywords or structured tags, then fine ranking by vector similarity, and finally weighting by time decay and importance. The logic looks like this:

    1. def recall(query, user_id, top_k=5):
    2. # 1) Structured coarse filtering: filter by user, time window, and task type
    3. candidates = store.filter(user_id=user_id, window="90d")
    4. # 2) Vector fine ranking: semantic similarity
    5. ranked = vector_rank(query, candidates)
    6. # 3) Rerank: combine time decay and importance weights
    7. return rerank(ranked, decay=0.02, weight={"pref": 1.5, "skill": 1.2})[:top_k]

    Engineering work must also account for privacy and compliance: sensitive fields should be masked before storage, with support for per-user deletion and export, so that memory does not become a compliance risk.

    4. Skill Self-Evolution: Abstracting Solutions into Reusable Assets

    Skill self-evolution is essentially a form of after-the-fact induction. Once a task is complete, the system compresses the trace and extracts trigger conditions, prerequisites, execution steps, failure fallbacks, and verification methods to generate a structured skill file. A minimal viable skill description can be abstracted as:

    1. skill:
    2. name: periodic_report_collect
    3. trigger: "When the user asks to summarize periodic metrics"
    4. inputs: [time range, metric list, data source]
    5. steps:
    6. - Pull data and validate completeness
    7. - Calculate year-over-year and period-over-period changes
    8. - Generate charts and a summary
    9. fallback: Use a cached snapshot when data is missing, and label it
    10. verify: Sample-check key metrics against the source system

    The skill library needs governance, or it will quickly bloat and conflict with itself. It is advisable to introduce four metrics: version number, hit count, success rate, and average latency. Skills with low hit counts or low success rates are automatically down-weighted and moved to a review queue. Keep a manual review entry point as well, to prevent incorrect experience from being solidified and spread.

    5. Tool Ecosystem and Multi-Model Routing

    The number of tools correlates positively with task coverage, but more tools also raise the cost of selection. In practice, dozens of general-purpose tools are usually built in, covering file operations, web browsing, code execution, structured queries, and other scenarios, with the adapter pattern used to extend to external systems. Tool descriptions should include applicable scenarios, parameter constraints, and failure semantics so the scheduling layer can make accurate choices.

    On the model side, binding to a single vendor is not recommended. Routing through a unified abstraction layer lets you split traffic by task type: lightweight models for structured extraction to reduce cost, more capable models for complex reasoning, and privately deployed models for sensitive scenarios. Routing policies can be adjusted dynamically based on rules, cost budgets, and real-time quality feedback.

    1. route(task):
    2. if task.type in {"extract", "classify"}: return small_model
    3. if task.sensitivity == "high": return private_model
    4. return strong_model

    6. Long-Horizon Tasks and Automated Orchestration

    The stability of long-horizon tasks depends on three things: task decomposition, state persistence, and failure recovery. A common recommendation is to model a large task as a directed acyclic graph, where nodes are independently verifiable subtasks and edges represent dependencies. Write a checkpoint before each node executes, and on failure retry from the most recent checkpoint rather than starting over.

    Periodic tasks are triggered centrally by a scheduler, paired with idempotent design to avoid duplicate execution. Branches that can run in parallel are handed to multiple sub-agents at the same time, then aggregated and verified by the main agent. Parallelism needs an upper limit along with timeouts and circuit breaking, to prevent resources from being exhausted by a single task.

    7. Deployment Suggestions on Baidu AI Cloud

    To build similar capabilities in a Baidu AI Cloud environment, you can combine general cloud product categories: use a container platform to host the execution layer and scheduler, object storage to hold skill files and task snapshots, a message queue for task distribution and peak shaving, and log and monitoring services with alerting for full-chain tracing. A key management service can host model credentials and data source passwords. At the model layer, the multi-model access and evaluation capabilities offered by the Qianfan large model platform can support routing and effectiveness comparison.

    8. Evaluation and Iteration

    A four-dimension evaluation is recommended: task success rate, average completion time, human intervention rate, and cost per task. In the early stage after launch, rely mainly on manual review and gradually transition to sampling review; periodically inspect the quality of the skill library and memory library, cleaning up conflicting and outdated entries. Only by solidifying the evaluation loop does an autonomous agent gain a foundation for sustainable evolution.