Skip to content

创建插件

本指南将帮助您从零开始创建一个 XAI-SDK 插件。

插件基础

什么是插件

插件是扩展 XAI-SDK 功能的独立模块。通过插件系统,您可以:

  • 添加新的 AI 提供商支持
  • 扩展工具功能
  • 自定义数据处理流程
  • 集成第三方服务
  • 添加自定义中间件

插件架构

plugin/
├── package.json          # 插件配置
├── src/
│   ├── index.ts         # 插件入口
│   ├── plugin.ts        # 插件主类
│   ├── types.ts         # 类型定义
│   └── utils/           # 工具函数
├── tests/               # 测试文件
└── README.md           # 插件文档

快速开始

1. 创建插件项目

bash
# 使用 CLI 创建插件模板
npx xai-sdk create-plugin my-plugin

# 或手动创建
mkdir my-plugin
cd my-plugin
npm init -y

2. 安装依赖

bash
npm install xai-sdk
npm install -D typescript @types/node

3. 创建插件类

typescript
// src/plugin.ts
import { BasePlugin, PluginConfig } from 'xai-sdk'

export interface MyPluginConfig extends PluginConfig {
  apiKey?: string
  endpoint?: string
}

export class MyPlugin extends BasePlugin<MyPluginConfig> {
  name = 'my-plugin'
  version = '1.0.0'
  description = '我的自定义插件'
  
  protected async onInitialize(config?: MyPluginConfig): Promise<void> {
    // 插件初始化逻辑
    this.logger.info('MyPlugin initialized')
    
    if (config?.apiKey) {
      this.config = { ...this.config, ...config }
    }
  }
  
  protected async onActivate(): Promise<void> {
    // 插件激活逻辑
    this.logger.info('MyPlugin activated')
  }
  
  protected async onDeactivate(): Promise<void> {
    // 插件停用逻辑
    this.logger.info('MyPlugin deactivated')
  }
}

4. 创建入口文件

typescript
// src/index.ts
export { MyPlugin } from './plugin'
export type { MyPluginConfig } from './plugin'

// 默认导出插件实例
export default new MyPlugin()

5. 配置 package.json

json
{
  "name": "xai-sdk-plugin-my-plugin",
  "version": "1.0.0",
  "description": "我的 XAI-SDK 插件",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "keywords": ["xai-sdk", "plugin", "ai"],
  "peerDependencies": {
    "xai-sdk": "^1.0.0"
  },
  "xai-sdk": {
    "plugin": true,
    "name": "my-plugin",
    "version": "1.0.0"
  }
}

插件类型

1. 提供商插件

扩展 AI 提供商支持:

typescript
import { BaseProvider, ChatOptions, ChatResponse } from 'xai-sdk'

export class MyProvider extends BaseProvider {
  name = 'my-provider'
  
  async chat(options: ChatOptions): Promise<ChatResponse> {
    // 实现聊天逻辑
    return {
      message: {
        role: 'assistant',
        content: 'Hello from my provider!'
      },
      usage: {
        promptTokens: 10,
        completionTokens: 5,
        totalTokens: 15
      }
    }
  }
}

2. 工具插件

添加新的工具功能:

typescript
import { Tool, ToolParameters, ToolResult } from 'xai-sdk'

export const myTool: Tool = {
  name: 'my-tool',
  description: '我的自定义工具',
  parameters: {
    type: 'object',
    properties: {
      input: {
        type: 'string',
        description: '输入文本'
      }
    },
    required: ['input']
  },
  execute: async (parameters: ToolParameters): Promise<ToolResult> => {
    const { input } = parameters
    
    // 工具执行逻辑
    const result = `处理结果: ${input}`
    
    return {
      success: true,
      data: result
    }
  }
}

3. 中间件插件

添加请求/响应处理中间件:

typescript
import { PluginMiddleware, RequestEvent, ResponseEvent } from 'xai-sdk'

export const myMiddleware: PluginMiddleware = {
  name: 'my-middleware',
  
  async onRequest(event: RequestEvent): Promise<void> {
    // 请求前处理
    console.log('Request:', event.request)
  },
  
  async onResponse(event: ResponseEvent): Promise<void> {
    // 响应后处理
    console.log('Response:', event.response)
  }
}

插件配置

配置接口

typescript
export interface MyPluginConfig extends PluginConfig {
  // 基础配置
  enabled?: boolean
  priority?: number
  
  // 自定义配置
  apiKey?: string
  endpoint?: string
  timeout?: number
  retries?: number
  
  // 功能开关
  features?: {
    logging?: boolean
    caching?: boolean
    validation?: boolean
  }
}

配置验证

typescript
import Joi from 'joi'

const configSchema = Joi.object({
  enabled: Joi.boolean().default(true),
  apiKey: Joi.string().required(),
  endpoint: Joi.string().uri().required(),
  timeout: Joi.number().min(1000).default(30000),
  retries: Joi.number().min(0).max(5).default(3)
})

export class MyPlugin extends BasePlugin<MyPluginConfig> {
  protected async validateConfig(config: MyPluginConfig): Promise<void> {
    const { error } = configSchema.validate(config)
    if (error) {
      throw new Error(`配置验证失败: ${error.message}`)
    }
  }
}

生命周期钩子

typescript
export class MyPlugin extends BasePlugin {
  // 插件初始化
  protected async onInitialize(config?: any): Promise<void> {
    // 设置配置、初始化资源
  }
  
  // 插件激活
  protected async onActivate(): Promise<void> {
    // 注册事件监听器、启动服务
  }
  
  // 插件停用
  protected async onDeactivate(): Promise<void> {
    // 清理资源、移除监听器
  }
  
  // 插件销毁
  protected async onDestroy(): Promise<void> {
    // 最终清理工作
  }
}

事件系统

监听事件

typescript
export class MyPlugin extends BasePlugin {
  protected async onActivate(): Promise<void> {
    // 监听 SDK 事件
    this.sdk.on('chat:start', this.onChatStart.bind(this))
    this.sdk.on('chat:end', this.onChatEnd.bind(this))
    this.sdk.on('error', this.onError.bind(this))
  }
  
  private async onChatStart(event: any): Promise<void> {
    this.logger.info('Chat started', event)
  }
  
  private async onChatEnd(event: any): Promise<void> {
    this.logger.info('Chat ended', event)
  }
  
  private async onError(event: any): Promise<void> {
    this.logger.error('Error occurred', event)
  }
}

发送事件

typescript
export class MyPlugin extends BasePlugin {
  async doSomething(): Promise<void> {
    // 发送自定义事件
    this.emit('my-plugin:action', {
      timestamp: new Date(),
      data: 'some data'
    })
  }
}

测试插件

单元测试

typescript
// tests/plugin.test.ts
import { MyPlugin } from '../src/plugin'

describe('MyPlugin', () => {
  let plugin: MyPlugin
  
  beforeEach(() => {
    plugin = new MyPlugin()
  })
  
  afterEach(async () => {
    await plugin.destroy()
  })
  
  test('should initialize correctly', async () => {
    await plugin.initialize({
      apiKey: 'test-key',
      endpoint: 'https://api.example.com'
    })
    
    expect(plugin.isInitialized).toBe(true)
  })
  
  test('should activate and deactivate', async () => {
    await plugin.initialize()
    await plugin.activate()
    
    expect(plugin.isActive).toBe(true)
    
    await plugin.deactivate()
    expect(plugin.isActive).toBe(false)
  })
})

集成测试

typescript
// tests/integration.test.ts
import { XAI } from 'xai-sdk'
import { MyPlugin } from '../src/plugin'

describe('MyPlugin Integration', () => {
  test('should work with SDK', async () => {
    const sdk = new XAI()
    const plugin = new MyPlugin()
    
    // 注册插件
    await sdk.use(plugin, {
      apiKey: 'test-key'
    })
    
    // 测试功能
    const response = await sdk.chat({
      messages: [{ role: 'user', content: 'Hello' }]
    })
    
    expect(response).toBeDefined()
  })
})

发布插件

1. 构建插件

bash
npm run build

2. 发布到 npm

bash
npm publish

3. 提交到插件市场

bash
# 提交到官方插件市场
npx xai-sdk submit-plugin

相关链接

Released under the MIT License.