Skip to content

AI 服务

本页介绍 AI 服务模块的设计和实现。

支持的服务商

服务商API 格式特点
MiniMax自有格式支持流式输出、思考过程
DeepSeekOpenAI 兼容性价比高
自定义OpenAI 兼容灵活配置

配置结构

typescript
interface APIConfig {
  provider: 'minimax' | 'deepseek' | 'custom'
  baseUrl: string
  apiKey: string
  model: string
  timeout?: number
}

核心功能

生成义项

typescript
async function generateDefinition(
  sentence: string,
  character: string
): Promise<string>

为句子中的指定字符生成义项解释。

批量生成

typescript
async function batchGenerateDefinitions(
  requests: AIDefinitionRequest[],
  options: {
    concurrency?: number
    onProgress?: (current: number, total: number) => void
  }
): Promise<AIDefinitionResult[]>

支持并发控制和进度回调。

找出重点字

typescript
async function findKeyCharacters(
  sentences: string[]
): Promise<KeyCharacterResult[]>

分析句子,找出需要注释的重点字。

流式响应处理

MiniMax 支持流式输出,包括思考过程:

typescript
// SSE 格式
data: {"choices":[{"delta":{"reasoning_content":"思考..."}}]}
data: {"choices":[{"delta":{"content":"回答..."}}]}
data: [DONE]

处理代码:

typescript
async function handleStream(response: Response) {
  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    
    const text = decoder.decode(value)
    // 解析 SSE 数据...
  }
}

并发控制

使用队列管理并发请求:

typescript
class ConcurrencyManager {
  private queue: Task[] = []
  private running = 0
  private maxConcurrent: number
  
  async execute<T>(task: () => Promise<T>): Promise<T> {
    while (this.running >= this.maxConcurrent) {
      await this.waitForSlot()
    }
    
    this.running++
    try {
      return await task()
    } finally {
      this.running--
      this.processQueue()
    }
  }
}

错误处理

typescript
try {
  const result = await generateDefinition(sentence, char)
} catch (error) {
  if (error.code === 'TIMEOUT') {
    // 超时处理
  } else if (error.code === 'RATE_LIMIT') {
    // 限流处理,等待后重试
  } else {
    // 其他错误
  }
}

使用示例

typescript
import { aiService } from '@/services/ai'

// 配置
aiService.configure({
  provider: 'minimax',
  apiKey: 'your-api-key',
  model: 'abab6.5s-chat'
})

// 生成单个义项
const definition = await aiService.generateDefinition(
  '学不可以已',
  '已'
)

// 批量生成
const results = await aiService.batchGenerateDefinitions(
  requests,
  {
    concurrency: 3,
    onProgress: (current, total) => {
      console.log(`${current}/${total}`)
    }
  }
)

基于 MIT 许可发布