插件 API
本文档详细介绍了 XAI-SDK 插件系统的 API 接口和使用方法。
核心接口
Plugin 接口
typescript
interface Plugin {
// 基本信息
name: string
version: string
description?: string
author?: string
homepage?: string
// 生命周期方法
initialize?(config?: any): Promise<void>
activate?(): Promise<void>
deactivate?(): Promise<void>
destroy?(): Promise<void>
// 状态属性
readonly isInitialized: boolean
readonly isActive: boolean
readonly config: any
}
BasePlugin 基类
typescript
abstract class BasePlugin<T = any> implements Plugin {
abstract name: string
abstract version: string
description?: string
author?: string
homepage?: string
protected sdk: XAI
protected logger: Logger
protected config: T
// 生命周期钩子
protected abstract onInitialize?(config?: T): Promise<void>
protected abstract onActivate?(): Promise<void>
protected abstract onDeactivate?(): Promise<void>
protected abstract onDestroy?(): Promise<void>
// 事件方法
protected emit(event: string, data?: any): void
protected on(event: string, handler: Function): void
protected off(event: string, handler: Function): void
}
插件配置
PluginConfig 接口
typescript
interface PluginConfig {
// 基础配置
enabled?: boolean
priority?: number
// 日志配置
logging?: {
level?: 'debug' | 'info' | 'warn' | 'error'
prefix?: string
}
// 错误处理
errorHandling?: {
retries?: number
timeout?: number
fallback?: boolean
}
}
配置验证
typescript
interface ConfigValidator {
validate(config: any): Promise<ValidationResult>
}
interface ValidationResult {
valid: boolean
errors?: string[]
warnings?: string[]
}
提供商插件 API
BaseProvider 基类
typescript
abstract class BaseProvider {
abstract name: string
abstract version: string
// 核心方法
abstract chat(options: ChatOptions): Promise<ChatResponse>
abstract stream?(options: ChatOptions): AsyncIterable<StreamChunk>
// 可选方法
embeddings?(options: EmbeddingOptions): Promise<EmbeddingResponse>
completions?(options: CompletionOptions): Promise<CompletionResponse>
// 配置方法
configure?(config: ProviderConfig): void
validate?(options: any): Promise<boolean>
}
聊天接口
typescript
interface ChatOptions {
messages: Message[]
model?: string
temperature?: number
maxTokens?: number
stream?: boolean
tools?: Tool[]
systemPrompt?: string
}
interface ChatResponse {
message: Message
usage?: TokenUsage
model?: string
finishReason?: 'stop' | 'length' | 'tool_calls'
}
interface StreamChunk {
delta: {
role?: string
content?: string
toolCalls?: ToolCall[]
}
usage?: TokenUsage
finishReason?: string
}
嵌入接口
typescript
interface EmbeddingOptions {
input: string | string[]
model?: string
dimensions?: number
}
interface EmbeddingResponse {
embeddings: number[][]
usage?: TokenUsage
model?: string
}
工具插件 API
Tool 接口
typescript
interface Tool {
name: string
description: string
parameters: ToolParameters
execute: ToolExecutor
// 可选属性
version?: string
category?: string
tags?: string[]
permissions?: ToolPermissions
}
interface ToolParameters {
type: 'object'
properties: Record<string, ParameterSchema>
required?: string[]
}
interface ParameterSchema {
type: 'string' | 'number' | 'boolean' | 'array' | 'object'
description?: string
enum?: any[]
default?: any
minimum?: number
maximum?: number
items?: ParameterSchema
}
工具执行器
typescript
type ToolExecutor = (
parameters: Record<string, any>,
context?: ToolContext
) => Promise<ToolResult>
interface ToolContext {
user?: User
session?: Session
sdk: XAI
logger: Logger
}
interface ToolResult {
success: boolean
data?: any
error?: string
metadata?: Record<string, any>
}
工具权限
typescript
interface ToolPermissions {
// 访问权限
read?: string[]
write?: string[]
execute?: string[]
// 资源限制
maxExecutionTime?: number
maxMemoryUsage?: number
maxFileSize?: number
// 网络权限
allowedDomains?: string[]
allowedPorts?: number[]
}
中间件插件 API
PluginMiddleware 接口
typescript
interface PluginMiddleware {
name: string
priority?: number
// 请求中间件
onRequest?(event: RequestEvent): Promise<void>
onRequestError?(event: RequestErrorEvent): Promise<void>
// 响应中间件
onResponse?(event: ResponseEvent): Promise<void>
onResponseError?(event: ResponseErrorEvent): Promise<void>
// 流式中间件
onStreamStart?(event: StreamStartEvent): Promise<void>
onStreamChunk?(event: StreamChunkEvent): Promise<void>
onStreamEnd?(event: StreamEndEvent): Promise<void>
}
事件类型
typescript
interface RequestEvent {
request: ChatOptions
timestamp: Date
requestId: string
userId?: string
}
interface ResponseEvent {
request: ChatOptions
response: ChatResponse
timestamp: Date
requestId: string
duration: number
}
interface StreamChunkEvent {
chunk: StreamChunk
timestamp: Date
requestId: string
chunkIndex: number
}
插件管理 API
PluginManager 接口
typescript
interface PluginManager {
// 插件注册
register(plugin: Plugin, config?: any): Promise<void>
unregister(name: string): Promise<void>
// 插件控制
activate(name: string): Promise<void>
deactivate(name: string): Promise<void>
// 插件查询
list(): Plugin[]
get(name: string): Plugin | undefined
isActive(name: string): boolean
// 批量操作
activateAll(): Promise<void>
deactivateAll(): Promise<void>
}
插件注册
typescript
// 注册单个插件
await sdk.plugins.register(myPlugin, {
apiKey: 'your-api-key',
enabled: true
})
// 批量注册插件
await sdk.plugins.registerMany([
{ plugin: plugin1, config: config1 },
{ plugin: plugin2, config: config2 }
])
// 从包注册
await sdk.plugins.registerFromPackage('xai-sdk-plugin-openai')
事件系统 API
事件发射器
typescript
interface EventEmitter {
on(event: string, handler: EventHandler): void
off(event: string, handler: EventHandler): void
once(event: string, handler: EventHandler): void
emit(event: string, data?: any): void
// 通配符支持
onAny(handler: (event: string, data: any) => void): void
offAny(handler: Function): void
}
type EventHandler = (data?: any) => void | Promise<void>
内置事件
typescript
// SDK 生命周期事件
'sdk:initialized'
'sdk:destroyed'
// 插件生命周期事件
'plugin:registered'
'plugin:activated'
'plugin:deactivated'
'plugin:unregistered'
// 聊天事件
'chat:start'
'chat:end'
'chat:error'
'chat:stream:start'
'chat:stream:chunk'
'chat:stream:end'
// 工具事件
'tool:execute:start'
'tool:execute:end'
'tool:execute:error'
日志系统 API
Logger 接口
typescript
interface Logger {
debug(message: string, meta?: any): void
info(message: string, meta?: any): void
warn(message: string, meta?: any): void
error(message: string, meta?: any): void
// 子日志器
child(namespace: string): Logger
// 配置
setLevel(level: LogLevel): void
getLevel(): LogLevel
}
type LogLevel = 'debug' | 'info' | 'warn' | 'error'
日志配置
typescript
interface LoggerConfig {
level: LogLevel
format?: 'json' | 'text'
timestamp?: boolean
colorize?: boolean
// 输出配置
transports?: LogTransport[]
}
interface LogTransport {
type: 'console' | 'file' | 'http'
options?: any
}
错误处理 API
错误类型
typescript
class PluginError extends Error {
constructor(
message: string,
public code: string,
public plugin: string,
public cause?: Error
)
}
class ConfigurationError extends PluginError {}
class ValidationError extends PluginError {}
class ExecutionError extends PluginError {}
错误处理器
typescript
interface ErrorHandler {
handle(error: Error, context?: ErrorContext): Promise<void>
}
interface ErrorContext {
plugin?: string
operation?: string
requestId?: string
userId?: string
}
实用工具 API
配置工具
typescript
class ConfigUtils {
static merge(base: any, override: any): any
static validate(config: any, schema: any): ValidationResult
static resolve(config: any, context: any): any
}
类型工具
typescript
class TypeUtils {
static isPlugin(obj: any): obj is Plugin
static isProvider(obj: any): obj is BaseProvider
static isTool(obj: any): obj is Tool
static isMiddleware(obj: any): obj is PluginMiddleware
}
异步工具
typescript
class AsyncUtils {
static timeout<T>(promise: Promise<T>, ms: number): Promise<T>
static retry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T>
static parallel<T>(tasks: (() => Promise<T>)[], limit?: number): Promise<T[]>
}
interface RetryOptions {
retries: number
delay?: number
backoff?: 'linear' | 'exponential'
}
使用示例
创建提供商插件
typescript
import { BaseProvider, ChatOptions, ChatResponse } from 'xai-sdk'
export class MyProvider extends BaseProvider {
name = 'my-provider'
version = '1.0.0'
async chat(options: ChatOptions): Promise<ChatResponse> {
// 实现聊天逻辑
const response = await this.callAPI(options)
return {
message: {
role: 'assistant',
content: response.content
},
usage: response.usage
}
}
private async callAPI(options: ChatOptions): Promise<any> {
// API 调用逻辑
}
}
创建工具插件
typescript
import { Tool, ToolResult } from 'xai-sdk'
export const weatherTool: Tool = {
name: 'get-weather',
description: '获取指定城市的天气信息',
parameters: {
type: 'object',
properties: {
city: {
type: 'string',
description: '城市名称'
},
unit: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
default: 'celsius'
}
},
required: ['city']
},
async execute(parameters, context): Promise<ToolResult> {
const { city, unit } = parameters
try {
const weather = await fetchWeather(city, unit)
return {
success: true,
data: {
city,
temperature: weather.temperature,
description: weather.description,
unit
}
}
} catch (error) {
return {
success: false,
error: `无法获取 ${city} 的天气信息: ${error.message}`
}
}
}
}
创建中间件插件
typescript
import { PluginMiddleware, RequestEvent, ResponseEvent } from 'xai-sdk'
export const loggingMiddleware: PluginMiddleware = {
name: 'logging-middleware',
priority: 100,
async onRequest(event: RequestEvent): Promise<void> {
console.log(`[${event.requestId}] Request:`, {
model: event.request.model,
messageCount: event.request.messages.length,
timestamp: event.timestamp
})
},
async onResponse(event: ResponseEvent): Promise<void> {
console.log(`[${event.requestId}] Response:`, {
content: event.response.message.content?.substring(0, 100),
usage: event.response.usage,
duration: event.duration
})
}
}