( messages: ChatMessage[] )
| 361 | * @param messages 消息列表 |
| 362 | */ |
| 363 | export async function analyzeTopicSegments( |
| 364 | messages: ChatMessage[] |
| 365 | ): Promise<TopicSegmentationResult> { |
| 366 | const { llmConfig, modelConfig } = getDefaultConfigs() |
| 367 | |
| 368 | if (!llmConfig) { |
| 369 | return { segments: [], success: false, error: '未配置 LLM' } |
| 370 | } |
| 371 | |
| 372 | if (messages.length === 0) { |
| 373 | return { segments: [], success: true } |
| 374 | } |
| 375 | |
| 376 | try { |
| 377 | // 构建对话内容(带序号) |
| 378 | const conversationStr = messages |
| 379 | .map((m, idx) => `[${idx}] ${m.role}: ${truncateContent(m.content, 150)}`) |
| 380 | .join('\n\n') |
| 381 | |
| 382 | const prompt = TOPIC_SEGMENTATION_PROMPT.replace('{conversation}', conversationStr) |
| 383 | const result = await generateWithAI(prompt, llmConfig, modelConfig || undefined) |
| 384 | |
| 385 | // 解析 JSON 结果 |
| 386 | const cleanResult = result.trim() |
| 387 | // 尝试提取 JSON 数组 |
| 388 | const jsonMatch = cleanResult.match(/\[[\s\S]*\]/) |
| 389 | if (!jsonMatch) { |
| 390 | console.error('Failed to parse topic segments: no JSON array found', cleanResult) |
| 391 | return { segments: [], success: false, error: '无法解析分段结果' } |
| 392 | } |
| 393 | |
| 394 | const segments: TopicSegment[] = JSON.parse(jsonMatch[0]) |
| 395 | |
| 396 | // 验证并清理结果 |
| 397 | const validSegments = segments |
| 398 | .filter( |
| 399 | (s) => |
| 400 | typeof s.index === 'number' && |
| 401 | s.index >= 0 && |
| 402 | s.index < messages.length && |
| 403 | typeof s.topic === 'string' && |
| 404 | s.topic.trim().length > 0 |
| 405 | ) |
| 406 | .map((s) => ({ |
| 407 | index: s.index, |
| 408 | topic: s.topic.trim().slice(0, 15) |
| 409 | })) |
| 410 | |
| 411 | return { segments: validSegments, success: true } |
| 412 | } catch (error) { |
| 413 | console.error('Failed to analyze topic segments:', error) |
| 414 | return { segments: [], success: false, error: String(error) } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // ==================== 带选项的生成函数 ==================== |
| 419 |
no test coverage detected