Plugin-Based Agent Architecture: Building Pluggable AI Products

    This article presents a practical architecture for building pluggable AI products with a minimal core and independently deployable plugins. It covers plugin protocol design, planning and execution separation, layered context caching, mixed-precision routing, controlled plugin generation, deployment and security, cost and performance evaluation, and common failure modes.

    1. Scope

    The approach discussed in this article is suitable for teams that need multiple capabilities at the same time—such as conversation, tool calling, code execution, and knowledge retrieval—and whose requirements change frequently. It does not promise to reproduce every AI product form, nor does it replace analysis of business requirements. Before adopting this architecture, teams need basic service deployment capabilities and execution processes for permissions and security review.

    2. Overall Architecture: Core and Plugin Layering

    Many AI applications place model calls, tools, memory, and permissions in the same module, so changing one part can affect other functionality. A more robust approach is to split the system into two layers.

    • Core: responsible only for scheduling, message passing, and plugin lifecycle management. It contains no specific business logic.
    • Plugin: implements concrete capabilities such as web search, code interpretation, database queries, and third-party API calls. Plugins connect to the core through a unified interface.

    This layering brings three direct benefits.

    1. Isolation and rollback: Plugins can be loaded, unloaded, and upgraded independently. If a plugin fails, as long as it runs in a separate process or container, the main process is usually unaffected, and rollback only requires switching to the previous version.
    2. Cross-team collaboration: As long as plugins follow the same interface—input/output format, parameter schema, and error format—plugins developed by different teams can share one scheduler. Existing command-line tools or internal APIs can also be integrated through thin wrappers.
    3. On-demand capability growth: New requirements are implemented by adding plugins rather than modifying the core, making it easier to assign owners and test scope by feature.

    Note that the more plugins there are, the more version matrices and dependency conflicts appear. Teams should define version numbering rules and compatibility requirements from the beginning.

    3. Plugin Protocol Design

    The plugin interface is the key to whether the entire system can be implemented. It is recommended that each plugin implement at least the following four parts: capability description, input validation, execution logic, and health check. Below is a runnable skeleton example. Specific timeout and retry policies need to be adjusted according to the business.

    1. from dataclasses import dataclass, field
    2. class PluginError(Exception):
    3. """Unified exception raised when plugin execution fails."""
    4. @dataclass
    5. class PluginMeta:
    6. name: str
    7. version: str # Semantic version, e.g., "1.2.0"
    8. permissions: list[str] = field(default_factory=list) # e.g., ["fs:read"], empty by default
    9. input_schema: dict = field(default_factory=dict) # Mapping from parameter name to type
    10. class PluginBase:
    11. def describe(self) -> PluginMeta:
    12. raise NotImplementedError
    13. def validate(self, payload: dict) -> None:
    14. """Check whether parameters match input_schema; raise PluginError if not."""
    15. schema = self.describe().input_schema
    16. for key, expected_type in schema.items():
    17. if key not in payload:
    18. raise PluginError(f"Missing parameter: {key}")
    19. if not isinstance(payload[key], expected_type):
    20. raise PluginError(f"Invalid type for parameter {key}")
    21. def execute(self, payload: dict, timeout_s: float) -> dict:
    22. """Execute business logic. The plugin itself must return or abort within timeout_s."""
    23. raise NotImplementedError
    24. def health_check(self) -> bool:
    25. return True
    26. def run_plugin(plugin: PluginBase, payload: dict,
    27. timeout_s: float = 30.0, retries: int = 0) -> dict:
    28. plugin.validate(payload)
    29. last_error = None
    30. for _ in range(retries + 1):
    31. try:
    32. result = plugin.execute(payload, timeout_s=timeout_s)
    33. if not isinstance(result, dict):
    34. raise PluginError("Return value must be a dict")
    35. return result
    36. except PluginError as err:
    37. last_error = err # Set retries > 0 only for idempotent operations
    38. raise PluginError(f"Plugin {plugin.describe().name} failed: {last_error}")

    Two points need clarification. First, retries are only suitable for read operations or idempotent operations. Before retrying operations such as writing to a database or sending a message, you must confirm that no duplicate side effects will occur. Second, ordinary Python functions cannot be forcibly interrupted, so timeouts must either be implemented inside the plugin—for example, by setting network request timeouts—or handled by running the plugin in a separate process and having the core kill the process.

    4. Inference Enhancements: Planning, Caching, and Routing

    Pluginization addresses “which capabilities the system can call,” while inference enhancement addresses “how well and how efficiently those capabilities are called.” This layer contains three components.

    4.1 Separation of Planning and Execution

    For complex tasks, a planner first generates a subtask graph with dependencies (DAG), and an executor then schedules tasks in dependency order. The planner is responsible only for decomposition logic and does not directly call tools. This makes the planning result independently reviewable and allows only failed nodes to be rerun when errors occur.

    In practice, the planner output should be structured data such as JSON and should be validated: node IDs are unique, dependencies are acyclic, and every plugin bound to each node is registered. If validation fails, the planner should be asked to regenerate rather than forcing the executor to run it.

    4.2 Layered Context Caching

    In long-running conversations and codebase tasks, instructions, project conventions, and tool descriptions are usually unchanged, while conversation content keeps growing. These can be divided into two layers: stable content goes into long-term cache, dynamic content goes into short-term cache, and each request appends only the changed part.

    Cache effectiveness depends on the model provider’s caching mechanism, whether the prefix is stable, context length, and request interval. Teams should define several metrics clearly:

    • Cache hit rate: the proportion of input tokens that hit the cache relative to total input tokens.
    • Token consumption per task: total consumption for the same task with caching enabled and disabled, compared using the same model version and the same task set.
    • Time to first token: the time from sending a request to receiving the first token.

    Only when these conditions are recorded clearly can one state how much cost caching saves.

    4.3 Mixed-Precision Routing

    Simple subtasks—such as format conversion, regex matching, and field extraction—can be sent to lightweight models, while complex reasoning—such as code refactoring and architecture design—can be sent to large models. The router is usually a small classifier, and it can itself be updated as a plugin. The following points need attention during implementation.

    • Training data: sample historical tasks by manually labeled difficulty and cover various task types.
    • Misroute fallback: when lightweight model output fails validation, automatically escalate to a large model for rerun and record the fallback.
    • Evaluation metrics: separately track routing accuracy, fallback ratio, and final success rate for each task type.
    • Monitoring and alerts: a sudden increase in fallback ratio usually indicates a change in input distribution or a problem with the lightweight model version.

    5. Dynamic Extension: Controlled Plugin Generation

    One appealing aspect of pluginization is that an agent can generate new plugins for missing capabilities during runtime. In production, however, this capability must be restricted within clear boundaries and cannot run unsupervised. The recommended process is as follows.

    1. The agent identifies a capability requirement that is not registered and selects a code framework from a reviewed template library.
    2. A code generation model produces plugin code and test cases.
    3. The new plugin runs tests in a sandbox: by default, no network and no file system write permissions; temporary permissions declared by the plugin are granted only after approval.
    4. After tests pass, the plugin enters a pending approval state. The approver checks the code, permission declarations, and dependency list.
    5. After approval, the plugin is installed after signature verification, and the capability routing table is updated.
    6. The installation record is written to the audit log, with retention period set according to company compliance requirements.

    Step 4 is necessary. Generated code may contain errors or introduce malicious dependencies. Automatically generated plugins should go through the same review process as manually written plugins, and review standards should not be lowered because “the agent generated it.”

    6. Practical Example: Automated Data Analysis Report

    Take an application that “reads data, performs statistical analysis, and generates a report” as an example. A declarative orchestration can describe the workflow. Each step is configured with a timeout and failure policy to prevent any step from waiting indefinitely.

    1. pipeline:
    2. - id: load
    3. agent: data_loader
    4. params: {source: csv, path: "./input/sales.csv"}
    5. timeout_s: 60
    6. retries: 2 # Read operation is idempotent; retries allowed
    7. on_failure: abort
    8. - id: analyze
    9. agent: stats_analyzer
    10. depends_on: [load]
    11. timeout_s: 120
    12. retries: 1
    13. on_failure: compensate:cleanup_tmp
    14. - id: report
    15. agent: report_writer
    16. depends_on: [analyze]
    17. timeout_s: 180
    18. retries: 0 # Do not retry automatically before writing files, to avoid side effects from overwriting
    19. on_failure: notify_owner

    The orchestrator needs to support three failure policies: abort terminates the workflow directly, compensate:<plugin_name> calls a compensation plugin to clean up intermediate results, and notify_owner notifies the owner and preserves the current state. Compensation plugins themselves must also be tested; otherwise, the compensation process may mask the original error.

    7. Cost and Performance Evaluation

    After adopting this architecture, teams often ask “how much can we save” and “what success rate can we reach.” These questions can only be answered by actual measurements. During evaluation, the following conditions should be fixed, and results should be recorded together with the conditions:

    • Model name and version, provider region, and API type;
    • Source, quantity, and difficulty distribution of the task set;
    • Sample size and the number of repeated runs per task;
    • Statistical basis, such as mean, median, or P95 and P99;
    • Control group setup, such as “no cache,” “single large model,” or “previous architecture.”

    Numbers lacking this information should not be used externally. If improvement is observed only on a certain internal task set, the article should explicitly state “observed on this task set” rather than generalizing it into a universal conclusion.

    8. Deployment and Security

    8.1 Permissions and Isolation

    • Plugins have no network or file write permissions by default. When needed, permissions are explicitly declared in permissions and temporary permissions are granted after approval.
    • Plugins run in separate processes or containers, with upper limits on resources such as CPU, memory, and execution time.
    • Credentials are injected through environment variables or a secret management service and are not written into plugin code or logs.

    8.2 Supply Chain Security

    • Plugin packages are signed, and the core loads only packages that pass signature verification.
    • Plugin sources are restricted to whitelisted repositories, and code is not pulled directly from arbitrary addresses.
    • Dependencies record hashes and lock versions, and upgrades require re-review.
    • Version rollback requires retaining the complete dependency combination of historical versions to ensure consistent behavior after rollback.

    8.3 Observability

    Generate a unique trace ID for each session and record the plugin name, version, parameter summary, duration, token consumption, and return status for each step. Do not record the original text of sensitive fields in logs. Log retention duration is determined by data protection requirements and kept consistent with the audit process.

    9. Comparison of Plugin Runtime Modes

    Runtime mode Fault isolation Call latency Operational overhead Suitable scenarios
    Local process (in-process call) Weak; a plugin crash may bring down the main process Lowest Low Development and debugging, trusted internal plugins
    Separate process (RPC call) Relatively strong Medium, depending on the local communication method Medium Common choice for production environments
    Container Strong Relatively high, depending on container network configuration Relatively high Untrusted plugins, scenarios requiring strong resource limits

    Specific latency should be measured in the target environment using P95 and P99, rather than directly applying numbers from elsewhere.

    10. Common Errors and Troubleshooting

    Symptom Possible cause Troubleshooting method
    Plugin call fails after loading Incompatible version or dependency hash mismatch Check the version and dependency lock file in the capability routing table
    Tasks frequently time out No network timeout inside the plugin, or timeout value is too small Check the duration of each step in the trace and inspect the plugin’s internal request timeout settings
    Low cache hit rate Instruction prefix changes every time, for example due to an embedded timestamp Compare the prefix content of two adjacent requests
    Routing fallback ratio keeps increasing Input distribution changed or lightweight model version is abnormal Track fallback ratio by task type and sample misrouted cases
    Duplicate data after retries Retries configured for non-idempotent operations Check retries in the pipeline; write operations should be set to 0
    Dynamically generated plugin cannot be installed Sandbox tests failed or signature verification failed Check sandbox logs and signature verification records

    11. Applicable Scenarios and Boundaries

    This approach is suitable for AI applications that require rapid iteration, such as intelligent customer service, code review assistants, automated operations, and research assistance tools. It also has clear boundaries.

    1. Latency-sensitive scenarios: Communication between plugins adds overhead. For millisecond-level interaction requirements, first evaluate whether in-process calls should be used, and rely on measured latency.
    2. Meta-plugin capabilities depend on model quality: When code generation model capability is insufficient, the success rate of dynamic extension decreases, and the review burden increases accordingly.
    3. Offline environments: When external model services are unavailable, a complete plugin library must be packaged in advance, and dynamic extension can only proceed when local models are available.
    4. Industries with high compliance requirements: Automatically generating and installing plugins may require additional approval and record keeping, which should be confirmed during solution design.

    Conclusion

    A plugin-based agent architecture breaks engineering capabilities into replaceable modules and then combines caching and routing to optimize inference cost. It can reduce the amount of business code that needs to be written, but configuration, testing, permission approval, and security review are still essential. Before adoption, teams should clarify their task sets and evaluation metrics, and use measured data to decide which optimizations are worth investing in.