插件使用指南
本指南专注于如何使用现有的 XAI-SDK 插件,包括安装、配置和使用插件的完整流程。
📋 目录
插件概述
什么是插件?
XAI-SDK 插件是扩展 SDK 功能的模块化组件。插件可以提供:
- 🛠️ 新工具:文件操作、代码分析、网络请求等
- 🤖 AI 集成:不同的 AI 模型和服务提供商
- ⚛️ 框架适配:React、Vue、Angular 等框架的专用功能
- 🎨 UI 组件:界面元素和主题
插件类型
类型 | 描述 | 示例 |
---|---|---|
工具插件 | 提供具体功能的工具 | 文件操作、代码分析 |
AI 提供商插件 | 集成 AI 服务 | OpenAI、Claude、本地模型 |
适配器插件 | 框架和环境适配 | React、Vue、Node.js |
UI 插件 | 界面组件和主题 | 组件库、主题包 |
插件安装
bash
# 安装官方插件
npm install @xai-sdk/file-tools
npm install @xai-sdk/openai-provider
npm install @xai-sdk/react-components
# 安装社区插件
npm install awesome-xai-plugin
npm install my-custom-tools
bash
yarn add @xai-sdk/file-tools
yarn add @xai-sdk/openai-provider
bash
pnpm add @xai-sdk/file-tools
pnpm add @xai-sdk/openai-provider
插件注册
基本注册
typescript
import { XAI_SDK } from 'xai-sdk';
import { FileToolsPlugin } from '@xai-sdk/file-tools';
import { OpenAIProviderPlugin } from '@xai-sdk/openai-provider';
// 创建 SDK 实例
const sdk = new XAI_SDK({
environment: 'node' // 或 'browser'
});
// 创建插件实例
const fileTools = new FileToolsPlugin();
const openaiProvider = new OpenAIProviderPlugin({
apiKey: process.env.OPENAI_API_KEY
});
// 注册插件
await sdk.registerPlugin(fileTools);
await sdk.registerPlugin(openaiProvider);
// 初始化 SDK
await sdk.initialize();
批量注册
typescript
const plugins = [
new FileToolsPlugin(),
new OpenAIProviderPlugin({ apiKey: process.env.OPENAI_API_KEY }),
new CodeAnalyzerPlugin({ enableLinting: true }),
new GitToolsPlugin()
];
// 批量注册
for (const plugin of plugins) {
await sdk.registerPlugin(plugin);
}
await sdk.initialize();
条件注册
typescript
// 根据环境注册不同插件
if (process.env.NODE_ENV === 'development') {
await sdk.registerPlugin(new DebugToolsPlugin());
}
// 根据配置注册插件
const config = await loadConfig();
if (config.enableAI) {
await sdk.registerPlugin(new OpenAIProviderPlugin({
apiKey: config.openaiApiKey
}));
}
// 根据环境能力注册插件
if (sdk.getEnvironment().supportsFileSystem) {
await sdk.registerPlugin(new FileToolsPlugin());
}
插件配置
配置方式
1. 构造函数配置
typescript
const plugin = new FileToolsPlugin({
maxFileSize: 10 * 1024 * 1024, // 10MB
allowedExtensions: ['.js', '.ts', '.json'],
enableCache: true
});
2. 配置文件
json
// .xai/plugins.json
{
"file-tools": {
"maxFileSize": 10485760,
"allowedExtensions": [".js", ".ts", ".json"],
"enableCache": true
},
"openai-provider": {
"apiKey": "${OPENAI_API_KEY}",
"model": "gpt-4",
"temperature": 0.7
}
}
typescript
// 从配置文件加载
const config = await sdk.loadPluginConfig('./xai/plugins.json');
const fileTools = new FileToolsPlugin(config['file-tools']);
3. 环境变量
bash
# .env
XAI_FILE_TOOLS_MAX_SIZE=10485760
XAI_OPENAI_API_KEY=your-api-key
XAI_OPENAI_MODEL=gpt-4
typescript
const fileTools = new FileToolsPlugin({
maxFileSize: process.env.XAI_FILE_TOOLS_MAX_SIZE,
});
const openaiProvider = new OpenAIProviderPlugin({
apiKey: process.env.XAI_OPENAI_API_KEY,
model: process.env.XAI_OPENAI_MODEL
});
4. 动态配置更新
typescript
// 获取插件实例
const fileTools = sdk.getPlugin('file-tools');
// 更新配置
fileTools.updateConfig({
maxFileSize: 20 * 1024 * 1024 // 增加到 20MB
});
// 重载插件以应用新配置
await fileTools.reload();
插件使用
使用插件工具
typescript
// 直接调用工具
const fileContent = await sdk.executeTool('read-file', {
path: './src/app.js',
encoding: 'utf-8'
});
const analysis = await sdk.executeTool('analyze-code', {
code: fileContent.content,
language: 'javascript'
});
// 在 AI 对话中使用工具
const response = await sdk.chat({
messages: [{
role: 'user',
content: '请帮我分析 src/app.js 文件中的代码质量'
}],
tools: ['read-file', 'analyze-code'] // 指定可用工具
});
使用插件提供的 AI 服务
typescript
// 指定 AI 提供商
const response = await sdk.chat({
messages: [{
role: 'user',
content: '请帮我写一个 React 组件'
}],
provider: 'openai', // 使用 OpenAI 插件
model: 'gpt-4'
});
// 流式对话
const stream = sdk.chatStream({
messages: [{ role: 'user', content: '解释 async/await' }],
provider: 'claude'
});
for await (const chunk of stream) {
console.log(chunk.content);
}
使用插件适配器
typescript
// 使用框架适配器
const reactComponent = await sdk.executeAdapter('react-adapter', 'generateComponent', {
name: 'UserCard',
props: {
user: { type: 'object', required: true },
showAvatar: { type: 'boolean', default: true }
}
});
// 使用环境适配器
const browserFeatures = await sdk.executeAdapter('browser-adapter', 'getCapabilities');
插件管理
查看已安装插件
typescript
// 获取所有插件
const plugins = sdk.getAllPlugins();
plugins.forEach(plugin => {
console.log(`${plugin.name} v${plugin.version} - ${plugin.metadata.description}`);
});
// 获取特定插件
const fileTools = sdk.getPlugin('file-tools');
if (fileTools) {
console.log(`插件状态: ${fileTools.getState()}`);
}
// 检查插件是否已注册
const isRegistered = sdk.isPluginRegistered('openai-provider');
插件生命周期管理
typescript
// 启用/禁用插件
await sdk.enablePlugin('file-tools');
await sdk.disablePlugin('debug-tools');
// 重载插件
await sdk.reloadPlugin('openai-provider');
// 卸载插件
await sdk.unregisterPlugin('unused-plugin');
监听插件事件
typescript
// 监听插件事件
sdk.on('plugin:registered', (event) => {
console.log(`插件已注册: ${event.plugin}`);
});
sdk.on('plugin:error', (event) => {
console.error(`插件错误: ${event.plugin} - ${event.error}`);
});
sdk.on('tool:executed', (event) => {
console.log(`工具已执行: ${event.toolName}`);
});
常用插件
官方插件
@xai-sdk/file-tools
文件操作工具集
typescript
import { FileToolsPlugin } from '@xai-sdk/file-tools';
const fileTools = new FileToolsPlugin({
maxFileSize: 10 * 1024 * 1024, // 10MB
allowedExtensions: ['.js', '.ts', '.json', '.md']
});
// 可用工具
// - read-file: 读取文件
// - write-file: 写入文件
// - list-files: 列出文件
// - delete-file: 删除文件
// - compress-files: 压缩文件
@xai-sdk/code-analyzer
代码分析工具
typescript
import { CodeAnalyzerPlugin } from '@xai-sdk/code-analyzer';
const codeAnalyzer = new CodeAnalyzerPlugin({
enableLinting: true,
enableSecurity: true,
enableComplexity: true
});
// 可用工具
// - analyze-code: 代码分析
// - check-syntax: 语法检查
// - calculate-complexity: 复杂度计算
// - security-scan: 安全扫描
@xai-sdk/openai-provider
OpenAI 服务集成
typescript
import { OpenAIProviderPlugin } from '@xai-sdk/openai-provider';
const openaiProvider = new OpenAIProviderPlugin({
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4',
temperature: 0.7,
maxTokens: 2048
});
// 提供的服务
// - 文本生成
// - 代码生成
// - 对话聊天
// - 流式输出
@xai-sdk/git-tools
Git 操作工具
typescript
import { GitToolsPlugin } from '@xai-sdk/git-tools';
const gitTools = new GitToolsPlugin({
autoCommit: false,
defaultBranch: 'main'
});
// 可用工具
// - git-status: 查看状态
// - git-diff: 查看差异
// - git-commit: 提交代码
// - git-branch: 分支操作
社区插件
数据库插件
@community/xai-mysql-plugin
: MySQL 数据库操作@community/xai-mongodb-plugin
: MongoDB 数据库操作@community/xai-redis-plugin
: Redis 缓存操作
网络插件
@community/xai-http-client
: HTTP 请求工具@community/xai-websocket
: WebSocket 连接@community/xai-graphql
: GraphQL 客户端
测试插件
@community/xai-jest-runner
: Jest 测试运行器@community/xai-playwright
: Playwright 测试工具@community/xai-coverage
: 代码覆盖率分析
故障排除
常见问题
1. 插件注册失败
typescript
try {
await sdk.registerPlugin(plugin);
} catch (error) {
if (error.code === 'PLUGIN_ALREADY_REGISTERED') {
console.log('插件已经注册');
} else if (error.code === 'INCOMPATIBLE_ENVIRONMENT') {
console.log('插件不兼容当前环境');
} else if (error.code === 'MISSING_DEPENDENCIES') {
console.log('缺少插件依赖');
}
}
2. 插件配置错误
typescript
// 验证配置
const plugin = new FileToolsPlugin();
try {
plugin.validateConfig({
maxFileSize: 'invalid', // 应该是数字
allowedExtensions: '.js' // 应该是数组
});
} catch (error) {
console.error('配置验证失败:', error.message);
}
3. 工具执行失败
typescript
try {
const result = await sdk.executeTool('read-file', {
path: '/nonexistent/file.txt'
});
} catch (error) {
if (error.code === 'TOOL_NOT_FOUND') {
console.log('工具不存在,检查插件是否已注册');
} else if (error.code === 'INVALID_PARAMETERS') {
console.log('参数无效:', error.details);
} else if (error.code === 'EXECUTION_ERROR') {
console.log('工具执行失败:', error.message);
}
}
调试技巧
1. 启用调试日志
typescript
const sdk = new XAI_SDK({
environment: 'node',
config: {
logging: {
level: 'debug',
output: 'console'
}
}
});
// 监听日志事件
sdk.on('log', (entry) => {
if (entry.level === 'error') {
console.error('SDK Error:', entry);
}
});
2. 检查插件状态
typescript
const plugin = sdk.getPlugin('file-tools');
console.log('插件状态:', plugin.getState());
console.log('插件配置:', plugin.getConfig());
console.log('是否已初始化:', plugin.isInitialized());
3. 列出可用工具
typescript
const tools = sdk.getAvailableTools();
console.log('可用工具:', tools.map(tool => tool.name));
const toolInfo = sdk.getToolInfo('read-file');
console.log('工具信息:', toolInfo);
性能优化
1. 按需加载插件
typescript
// 延迟加载插件
async function loadFileToolsWhenNeeded() {
if (!sdk.isPluginRegistered('file-tools')) {
const { FileToolsPlugin } = await import('@xai-sdk/file-tools');
await sdk.registerPlugin(new FileToolsPlugin());
}
}
2. 插件缓存
typescript
const fileTools = new FileToolsPlugin({
enableCache: true,
cacheSize: 100,
cacheTTL: 60000 // 1分钟
});
3. 批量操作
typescript
// 批量文件操作
const files = ['file1.js', 'file2.js', 'file3.js'];
const results = await sdk.executeTool('batch-read-files', {
paths: files,
encoding: 'utf-8'
});
🔗 相关链接
🆘 获取帮助
🎉 恭喜! 您现在已经掌握了 XAI-SDK 插件的使用方法。开始探索丰富的插件生态系统,让您的开发更加高效!