( messages: ChatMessage[], maxLength: number = 20 )
| 603 | * @param maxLength 标题最大长度 |
| 604 | */ |
| 605 | export async function generateSessionTitle( |
| 606 | messages: ChatMessage[], |
| 607 | maxLength: number = 20 |
| 608 | ): Promise<TitleGenerationResult> { |
| 609 | const { llmConfig, modelConfig } = getDefaultConfigs() |
| 610 | |
| 611 | if (!llmConfig) { |
| 612 | return { title: '', success: false, error: '未配置 LLM' } |
| 613 | } |
| 614 | |
| 615 | if (messages.length === 0) { |
| 616 | return { title: '', success: false, error: '对话为空' } |
| 617 | } |
| 618 | |
| 619 | try { |
| 620 | // 构建对话内容摘要(取前几条消息) |
| 621 | const conversationContent = messages |
| 622 | .slice(0, 10) // 取前10条消息 |
| 623 | .map((m) => `[${m.role}]: ${truncateContent(m.content, 200)}`) |
| 624 | .join('\n') |
| 625 | |
| 626 | const prompt = SESSION_TITLE_GENERATION_PROMPT.replace( |
| 627 | '{content}', |
| 628 | truncateContent(conversationContent, 1500) |
| 629 | ) |
| 630 | const result = await generateWithAI(prompt, llmConfig, modelConfig || undefined) |
| 631 | |
| 632 | // 清理结果 |
| 633 | let title = result |
| 634 | .replace(/^["'""]|["'""]$/g, '') |
| 635 | .replace(/^(标题|对话标题)[::]\s*/i, '') |
| 636 | .trim() |
| 637 | |
| 638 | if (title.length > maxLength) { |
| 639 | title = title.slice(0, maxLength) |
| 640 | } |
| 641 | |
| 642 | return { title, success: true } |
| 643 | } catch (error) { |
| 644 | console.error('Failed to generate session title:', error) |
| 645 | return { title: '', success: false, error: String(error) } |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | /** |
| 650 | * 为对话生成标题(带选项) |
nothing calls this directly
no test coverage detected