XAI-SDK 插件系统开发指南
欢迎来到 XAI-SDK 插件系统开发指南!本文档将详细介绍如何开发、使用和发布 XAI-SDK 插件。
📋 目录
插件系统概述
什么是插件系统?
XAI-SDK 的插件系统是一个可扩展的架构,允许开发者创建自定义功能模块来扩展 SDK 的核心能力。通过插件系统,您可以:
- 扩展工具集:添加新的代码分析、文件操作、网络请求等工具
- 集成AI服务:连接不同的AI模型和服务提供商
- 适配新框架:为新的前端框架或开发环境提供支持
- 定制业务逻辑:实现企业特定的业务需求
核心特性
- ✅ 标准化接口:所有插件遵循统一的 Plugin 接口规范
- ✅ 生命周期管理:完整的插件生命周期(初始化→启用→禁用→销毁)
- ✅ 依赖管理:支持插件间的依赖关系声明和自动解析
- ✅ 环境适配:支持 Node.js、浏览器等不同运行环境
- ✅ 事件系统:基于事件驱动的插件通信机制
- ✅ 配置管理:灵活的插件配置和参数管理
- ✅ 错误处理:完善的错误处理和状态管理
- ✅ 热插拔:运行时动态加载和卸载插件
快速开始
环境准备
bash
# 创建插件项目
mkdir my-xai-plugin
cd my-xai-plugin
# 初始化项目
npm init -y
bash
# 安装依赖
npm install xai-sdk
npm install -D typescript @types/node jest
第一个插件
创建一个简单的工具插件:
typescript
// src/MyFirstPlugin.ts
import { BasePlugin } from 'xai-sdk/core';
import type { PluginMetadata, ToolDefinition } from 'xai-sdk/types';
export class MyFirstPlugin extends BasePlugin {
public readonly name = 'my-first-plugin';
public readonly version = '1.0.0';
public readonly metadata: PluginMetadata = {
description: '我的第一个插件',
author: 'Your Name',
tags: ['example', 'tutorial'],
homepage: 'https://github.com/your-name/my-first-plugin',
repository: 'https://github.com/your-name/my-first-plugin'
};
// 插件提供的工具
public tools: Record<string, ToolDefinition> = {
'hello-world': {
name: 'hello-world',
description: '输出 Hello World 消息',
parameters: {
name: {
type: 'string',
required: false,
description: '要问候的名字'
}
},
handler: this.helloWorld.bind(this)
}
};
// 插件初始化
protected async onInitialize(): Promise<void> {
this.log('info', '初始化 MyFirstPlugin');
}
// 插件启用
protected async onEnable(): Promise<void> {
this.log('info', 'MyFirstPlugin 已启用');
}
// 工具实现
private async helloWorld(params: { name?: string }): Promise<{ message: string }> {
const name = params.name || 'World';
const message = `Hello, ${name}! 来自 MyFirstPlugin`;
this.log('info', `执行 hello-world 工具: ${message}`);
return { message };
}
}
使用插件
typescript
// example.ts
import { XAI_SDK } from 'xai-sdk';
import { MyFirstPlugin } from './src/MyFirstPlugin';
async function main() {
// 创建 SDK 实例
const sdk = new XAI_SDK({
environment: 'node'
});
// 注册插件
const plugin = new MyFirstPlugin();
await sdk.registerPlugin(plugin);
// 初始化 SDK
await sdk.initialize();
// 使用插件提供的工具
const result = await sdk.executeTool('hello-world', { name: 'Developer' });
console.log(result); // { message: "Hello, Developer! 来自 MyFirstPlugin" }
}
main().catch(console.error);
插件类型和使用场景
工具插件 (Tool Plugins)
用途:扩展 SDK 的工具集合
使用场景:
- 📁 文件操作:文件压缩、解压、格式转换
- 🔍 代码分析:静态分析、复杂度计算、安全检查
- 🌐 网络操作:HTTP 请求、WebSocket 连接、API 集成
- 📊 数据处理:JSON/XML 解析、CSV 处理、数据验证
- 🛠️ 开发工具:代码格式化、依赖分析、构建工具集成
示例:
typescript
// 文件压缩工具插件
export class FileCompressionPlugin extends BasePlugin {
public tools = {
'compress-file': {
name: 'compress-file',
description: '压缩文件',
parameters: {
filePath: { type: 'string', required: true },
outputPath: { type: 'string', required: false }
},
handler: this.compressFile.bind(this)
}
};
}
适配器插件 (Adapter Plugins)
用途:为不同框架和环境提供适配
使用场景:
- ⚛️ 框架适配:React、Vue、Angular、Svelte 等
- 🏗️ 构建工具:Webpack、Vite、Rollup 等
- 🌍 环境适配:不同操作系统、容器环境等
- 🎨 UI 库:Ant Design、Material-UI、Element UI 等
AI 提供商插件 (Provider Plugins)
用途:集成不同的 AI 模型和服务
使用场景:
- 🤖 商业 AI 服务:OpenAI、Claude、Google AI 等
- 🏠 本地模型:Ollama、本地部署的模型等
- 🏢 企业 AI 服务:内部 AI 平台、定制模型等
- 🔧 专用 AI 工具:代码生成、翻译、图像处理等
UI 插件 (UI Plugins)
用途:提供用户界面组件和主题
使用场景:
- 🎨 主题系统:暗色主题、自定义主题等
- 📱 UI 组件:通用组件、特定业务组件等
- 📊 可视化:图表、报表、仪表板等
插件架构详解
插件接口
typescript
interface Plugin {
// 基本信息
readonly name: string;
readonly version: string;
readonly metadata: PluginMetadata;
// 可选属性
dependencies?: PluginDependency[];
supportedEnvironments?: Environment[];
requiredSDKVersion?: string;
tools?: Record<string, ToolDefinition>;
adapters?: Record<string, AdapterDefinition>;
// 生命周期方法
initialize(sdk?: XAISDKInstance): Promise<boolean>;
enable?(): Promise<boolean>;
disable?(): Promise<boolean>;
reload?(): Promise<boolean>;
destroy(): Promise<boolean>;
// 状态查询
getState(): PluginState;
isInitialized(): boolean;
}
插件元数据
typescript
interface PluginMetadata {
description: string; // 插件描述
author: string; // 作者信息
tags: string[]; // 标签
homepage?: string; // 主页URL
repository?: string; // 代码仓库URL
license?: string; // 许可证
keywords?: string[]; // 关键词
icon?: string; // 图标URL
screenshots?: string[]; // 截图URL列表
}
插件状态
typescript
type PluginState =
| 'uninitialized' // 未初始化
| 'initializing' // 初始化中
| 'initialized' // 已初始化
| 'enabling' // 启用中
| 'enabled' // 已启用
| 'disabling' // 禁用中
| 'disabled' // 已禁用
| 'reloading' // 重载中
| 'destroying' // 销毁中
| 'destroyed' // 已销毁
| 'error'; // 错误状态
开发插件
使用 BasePlugin 类
最推荐的方式是继承 BasePlugin
类:
typescript
import { BasePlugin } from 'xai-sdk/core';
import type { PluginMetadata, ToolDefinition } from 'xai-sdk/types';
export class MyAdvancedPlugin extends BasePlugin {
public readonly name = 'my-advanced-plugin';
public readonly version = '1.0.0';
public readonly metadata: PluginMetadata = {
description: '高级功能插件',
author: 'Your Name',
tags: ['advanced', 'tools'],
homepage: 'https://github.com/your-name/my-advanced-plugin',
repository: 'https://github.com/your-name/my-advanced-plugin'
};
// 环境兼容性
public supportedEnvironments = ['node', 'browser'];
// 插件依赖
public dependencies = [
{
name: 'basic-tools-plugin',
version: '^1.0.0',
optional: false
}
];
// 插件配置
private config = {
enableCache: true,
timeout: 5000
};
// 生命周期:初始化
protected async onInitialize(): Promise<void> {
this.log('info', '初始化高级插件...');
// 验证配置
this.validateConfig();
// 设置资源
await this.setupResources();
}
// 生命周期:启用
protected async onEnable(): Promise<void> {
this.log('info', '启用高级插件...');
// 注册事件监听器
this.setupEventListeners();
}
// 生命周期:禁用
protected async onDisable(): Promise<void> {
this.log('info', '禁用高级插件...');
// 清理事件监听器
this.cleanupEventListeners();
}
// 生命周期:销毁
protected async onDestroy(): Promise<void> {
this.log('info', '销毁高级插件...');
// 清理所有资源
await this.cleanupResources();
}
private validateConfig(): void {
// 配置验证逻辑
}
private async setupResources(): Promise<void> {
// 资源初始化逻辑
}
private setupEventListeners(): void {
// 事件监听器设置
this.sdkInstance?.on('tool:executed', this.handleToolExecuted.bind(this));
}
private cleanupEventListeners(): void {
// 清理事件监听器
this.sdkInstance?.removeAllListeners('tool:executed');
}
private async cleanupResources(): Promise<void> {
// 资源清理逻辑
}
private handleToolExecuted(event: any): void {
this.log('debug', `工具已执行: ${event.toolName}`);
}
}
使用 SimplePlugin 类
对于简单插件,可以使用 SimplePlugin
类:
typescript
import { SimplePlugin } from 'xai-sdk/core';
const mySimplePlugin = new SimplePlugin({
name: 'my-simple-plugin',
version: '1.0.0',
metadata: {
description: '简单插件示例',
author: 'Your Name',
tags: ['simple']
},
tools: {
'current-time': {
name: 'current-time',
description: '获取当前时间',
parameters: {},
handler: async () => ({ time: new Date().toISOString() })
}
},
handlers: {
initialize: async (sdk) => {
console.log('简单插件已初始化');
},
enable: async () => {
console.log('简单插件已启用');
}
}
});
使用 createPlugin 工厂函数
最简单的方式是使用工厂函数:
typescript
import { createPlugin } from 'xai-sdk/core';
const myFactoryPlugin = createPlugin({
name: 'my-factory-plugin',
version: '1.0.0',
metadata: {
description: '工厂函数创建的插件',
author: 'Your Name',
tags: ['factory']
},
tools: {
'random-number': {
name: 'random-number',
description: '生成随机数',
parameters: {
min: { type: 'number', required: false, default: 0 },
max: { type: 'number', required: false, default: 100 }
},
handler: async (params) => {
const min = params.min || 0;
const max = params.max || 100;
return {
number: Math.floor(Math.random() * (max - min + 1)) + min
};
}
}
},
handlers: {
initialize: async (sdk) => {
console.log('工厂插件已初始化');
}
}
});
插件生命周期
生命周期方法详解
initialize()
- 调用时机:插件注册到SDK时
- 用途:设置基础配置、验证环境、初始化资源
- 必须实现:是
typescript
protected async onInitialize(): Promise<void> {
// 1. 验证环境和配置
this.validateEnvironment();
this.validateConfig();
// 2. 初始化资源
await this.initializeDatabase();
await this.loadConfiguration();
// 3. 设置基础状态
this.isReady = true;
}
enable()
- 调用时机:插件初始化完成后,或从禁用状态恢复时
- 用途:启动服务、注册事件监听器、激活功能
- 必须实现:否(可选)
typescript
protected async onEnable(): Promise<void> {
// 1. 启动服务
await this.startServices();
// 2. 注册事件监听器
this.registerEventListeners();
// 3. 通知其他组件
this.emit('plugin:enabled');
}
disable()
- 调用时机:插件需要暂停时
- 用途:暂停服务、移除事件监听器、保存状态
- 必须实现:否(可选)
typescript
protected async onDisable(): Promise<void> {
// 1. 暂停服务
await this.pauseServices();
// 2. 移除事件监听器
this.removeEventListeners();
// 3. 保存当前状态
await this.saveState();
}
destroy()
- 调用时机:插件被卸载时
- 用途:完全清理所有资源、关闭连接、释放内存
- 必须实现:是
typescript
protected async onDestroy(): Promise<void> {
// 1. 停止所有服务
await this.stopAllServices();
// 2. 关闭数据库连接
await this.closeDatabaseConnections();
// 3. 清理缓存和临时文件
await this.cleanupCache();
// 4. 释放内存
this.releaseMemory();
}
🔗 相关链接
🆘 获取帮助
🎉 恭喜! 您现在已经掌握了 XAI-SDK 插件开发的基础知识。开始创建您的第一个插件吧!