Building a Plugin-Based AI Workshop from Scratch: Architecture and Best Practices
This article details the architecture and practical implementation of building a plugin-based AI workshop. It covers defining clear boundaries for core components—plugins, services, tools, context managers, and presets—as well as designing context management interfaces, standardizing model adapters, managing the plugin lifecycle, enforcing RBAC permissions, and preparing for system backups and migrations.
1. Defining the Boundaries of the Workshop
A plugin-based AI workshop consists of five categories of components, and the responsibilities of each category must be separated.
- Plugins: Independent modules that implement a specific function, such as a course conflict checker. They declare their own inputs, outputs, dependencies, and permissions.
- Services: The underlying infrastructure that plugins rely on at runtime, such as logging, object storage, message queues, and database connections. Plugins access them through service interfaces rather than direct connections.
- Tools: Functions exposed by plugins for the model to call. The model decides when to call them based on the tool name and parameter descriptions.
- Context Manager: Responsible for the storage, trimming, concurrency control, and snapshotting of session messages.
- Presets: A set of configurations including the enabled model, toolset, system prompts, and permission scope. Switching presets switches the working mode.
Once boundaries are defined, if any component fails, its impact is confined to its own layer. Plugins should not directly modify context storage, and the model adapter layer should not contain business logic.
2. Context Manager: Responsibilities and Interfaces
The context manager solves the problem of state consistency in multi-turn conversations and tool calls. It must handle at least four responsibilities: appending messages, extracting a message window based on a token budget, preventing a session from being corrupted by concurrent writes, and saving sessions as recoverable snapshots.
The minimal interface can be designed as follows:
class ContextManager:def append(self, session_id: str, message: Message) -> None:"""Append a message. Check if the session is locked before writing."""def window(self, session_id: str, max_tokens: int) -> list[Message]:"""Return a message window that does not exceed max_tokens.Keeps system messages and the most recent messages, compressing earlier ones into a summary."""def lock(self, session_id: str, timeout: float = 5.0) -> "ContextLock":"""Acquire a session write lock. Raises an exception on timeout; no silent overriding."""def snapshot(self, session_id: str) -> str:"""Save the current session and return a version ID."""def restore(self, session_id: str, version_id: str) -> None:"""Restore to the specified version. Automatically saves the current state before restoring for rollback purposes."""
The message structure must include at least the following fields: session_id, role (system, user, assistant, tool), content, tool_call_id, token_count, created_at, version. If tool_call_id is missing, tool results cannot be paired with their corresponding calls, causing the model to output confusing answers.
3. Model Adapter Layer: Unified Interface and Switching Steps
Different vendors’ APIs vary in parameter names, billing methods, and error codes. The adapter layer’s role is to shield these differences internally, allowing business code to interact with a single interface.
class ModelAdapter(Protocol):name: strdef chat(self, messages: list[Message], *, timeout: float,max_retries: int = 2) -> ChatResult: ...def embed(self, texts: list[str], *, timeout: float) -> list[list[float]]: ...def stream(self, messages: list[Message], *, timeout: float) -> Iterator[str]: ...@dataclassclass ChatResult:text: strinput_tokens: intoutput_tokens: intlatency_ms: interror_code: str | None
Error codes need unified mapping, with defined handling methods for each type:
| Error Code | Meaning | Handling Method |
|---|---|---|
| RATE_LIMITED | Rate limited | Exponential backoff retry; switch to fallback model if retries are exhausted |
| TIMEOUT | Response timeout | Retry once; switch to fallback model if it still fails |
| AUTH_FAILED | Invalid or expired API key | No retry; alert immediately |
| CONTEXT_TOO_LONG | Input exceeds limit | Call the context manager’s window to shrink the window, then retry |
| INVALID_TOOL_ARGS | Model generated invalid tool arguments | Return validation errors to the model; allow one correction attempt |
The steps for switching models are as follows:
- Add a new model entry in the configuration, filling in the name, endpoint, timeout, and billing unit price.
- Run
chatwith a fixed test set to check if the output format meets downstream parsing requirements. - Record the average latency, cost per call, and test set accuracy.
- Switch the model in the preset, keeping the old model configuration for rollback.
- Observe the error code distribution for a period before deciding whether to remove the old model.
When selecting models, compare them across the following dimensions. The data must come from your own test set; do not directly use numbers from others:
| Dimension | How to Test | Example Switching Threshold |
|---|---|---|
| Accuracy | Fixed sample set, judged manually or by rules | Do not switch if below baseline by 5 percentage points |
| Latency | P50 and P95 of the same batch of requests | Do not switch if P95 exceeds acceptable business duration |
| Cost per call | Multiply input/output token count by unit price | Convert to cost per 1,000 calls based on monthly budget |
| Permission risk | Vendor’s data retention and storage policies | Only use models meeting compliance requirements for sensitive data |
4. Tool Integration: A Calling Chain Example Using Course Management
Using “course management” as an example, the complete calling chain consists of four steps:
- Natural language input: The user says, “Move Wednesday afternoon’s Data Structures class to Friday.”
- Parameter generation: The model selects the tool
update_course_scheduleand generates parameters{"course": "Data Structures", "day": "Friday", "slot": "afternoon"}. - Execution and validation: The tool first validates the parameter format, applies modifications to the table, and reads back the data to confirm the result.
- Result return: The tool returns the differences before and after modification to the model, and the model informs the user in natural language.
The validation in step 3 cannot be omitted. The model might generate a seemingly reasonable but non-existent course name; the tool should query whether a matching record exists before writing. If no match is found, return a clear error rather than defaulting to creating a new record.
5. Plugin Lifecycle: Generation, Loading, Testing, Rollback, and Unloading
AI can generate plugins based on requirements, but the results must go through the same process before use.
5.1 Plugin Manifest and Validation
Every plugin directory must contain a manifest.json. Validate it with JSON Schema before loading:
{"$schema": "https://json-schema.org/draft/2020-12/schema","type": "object","required": ["plugin_name", "version", "entry_point", "permissions"],"properties": {"plugin_name": {"type": "string", "pattern": "^[a-z][a-z0-9_]{2,63}$"},"version": {"type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$"},"status": {"enum": ["active", "disabled", "unloaded"]},"entry_point": {"type": "string", "pattern": "^[\\w\\-]+\\.py$"},"dependencies": {"type": "object","additionalProperties": {"type": "string"}},"permissions": {"type": "array","items": {"type": "string", "pattern": "^(read|write|exec):[a-z_]+$"}},"timeout_seconds": {"type": "integer", "minimum": 1, "maximum": 300}},"additionalProperties": false}
dependencies must use exact version numbers, not ranges. Without locked dependencies, the same plugin might behave differently on two machines.
5.2 Lifecycle Commands
The following commands are a sample interface set; names can be replaced with your own CLI or API:
workshop plugin validate ./plugins/course_conflict_checkerworkshop plugin load course_conflict_checker --version 1.0.0workshop plugin test course_conflict_checker --cases tests/cases.yamlworkshop plugin disable course_conflict_checkerworkshop plugin rollback course_conflict_checker --to 0.9.2workshop plugin unload course_conflict_checker
The checkpoints for each phase are as follows:
- validate: Schema validation passes, entry point exists, and dependency versions are locked.
- load: Checks if the plugin’s declared permissions are a subset of those granted to the current user; rejects loading if not met. The plugin starts in a separate subprocess with a set timeout.
- test: Runs test cases including normal, empty, excessively long, and malformed inputs. Does not enter the
activestate if the pass rate is below the set threshold. - Fix: AI modifies code based on failure logs and generates a new version number, e.g., 1.0.1. The old version is retained in the directory and not directly overwritten.
- disable: Stops new requests from entering the plugin; running calls wait to complete or timeout.
- rollback: Points
statusto the old version and re-runstest. - unload: Releases connections and temporary files held by the plugin, deletes registered tool descriptions, and retains audit logs.
on_load and on_unload hooks should have timeout limits. If a hook hangs, the system should forcibly terminate the plugin process and log an error, rather than blocking the startup or shutdown of the entire workshop.
5.3 Considerations for Generated Plugins
AI-generated code should not directly receive write permissions without review. A recommended approach is that new plugins default to read-only permissions. Only after human review of the test report should an administrator manually grant write permissions.
6. Permission Policy and Execution Evidence
6.1 Permission Model
Use Role-Based Access Control (RBAC) and follow the principle of least privilege. Deny by default; only explicitly granted permissions can be used.
ROLE_PERMISSIONS = {"viewer": {"read:course_schedule"},"editor": {"read:course_schedule", "write:course_schedule"},"admin": {"read:course_schedule", "write:course_schedule","manage:plugins"},}def check_permission(role: str, permission: str) -> bool:# Unknown roles return an empty set, resulting in denialreturn permission in ROLE_PERMISSIONS.get(role, set())
The plugin’s declared permissions must match the permissions actually invoked at runtime. If a plugin invokes an undeclared permission, the call should be immediately aborted and recorded. Such errors should be caught during the testing phase, so test cases must cover every declared permission.
6.2 High-Risk Operation Interception
Deletions, batch modifications, sending external messages, and executing shell commands are considered high-risk operations. These operations require manual confirmation and cannot be self-approved by the model.
Example confirmation flow:
- The tool detects a high-risk operation and returns a “pending confirmation” status along with a one-time confirmation code.
- The user reviews the operation details in the UI and enters the confirmation code.
- The tool uses the code to execute the operation, and the code is immediately invalidated.
- If the confirmation code is not used within the set time, the operation is automatically canceled.
6.3 Audit Log Fields
Every tool call and model call must be written to the audit log. It is recommended to include the following fields:
{"trace_id": "9f2c...","timestamp": "2026-11-25T08:12:03Z","actor": "agent","user_role": "editor","session_id": "s_20261125_01","model_name": "model_a","model_version": "2026-10","tool_name": "update_course_schedule","tool_args_hash": "sha256:...","decision": "allowed","latency_ms": 842,"error_code": null}
Do not write API keys, complete personal information, or raw sensitive content into logs. Parameters can be stored as hashes or desensitized summaries. The log files themselves need strict access permissions to prevent access by ordinary roles.
7. Backup and Migration Checklist
Before migrating the workshop to a new machine or cloud environment, confirm each item on the following checklist:
- Export sessions and snapshots from the context storage, recording the version number at the time of export.
- Export presets, plugin directories, and each plugin’s
manifest.json. - Save dependency lock files, e.g.,
