* 带上下文的智能聊天
(
message: string,
systemPrompt?: string,
options?: ContextFilter
)
| 667 | * 带上下文的智能聊天 |
| 668 | */ |
| 669 | public async chatWithContext( |
| 670 | message: string, |
| 671 | systemPrompt?: string, |
| 672 | options?: ContextFilter |
| 673 | ): Promise<string> { |
| 674 | const contextComponent = this.getContextComponent(); |
| 675 | |
| 676 | if (!contextComponent || !contextComponent.isContextReady()) { |
| 677 | // 如果没有上下文组件或未就绪,降级到普通聊天 |
| 678 | this.log('上下文组件未就绪,使用普通聊天模式'); |
| 679 | return systemPrompt |
| 680 | ? await this.llmManager.chatWithSystem(systemPrompt, message) |
| 681 | : await this.llmManager.chat(message); |
| 682 | } |
| 683 | |
| 684 | try { |
| 685 | // 构建包含上下文的消息列表 |
| 686 | const messages = await contextComponent.buildMessagesWithContext( |
| 687 | message, |
| 688 | systemPrompt, |
| 689 | options |
| 690 | ); |
| 691 | |
| 692 | // 转换为LLM消息格式 |
| 693 | const llmMessages: LLMMessage[] = messages.map(msg => ({ |
| 694 | role: msg.role as 'user' | 'assistant' | 'system', |
| 695 | content: msg.content, |
| 696 | })); |
| 697 | |
| 698 | // 进行对话 |
| 699 | const response = await this.llmManager.conversation(llmMessages); |
| 700 | |
| 701 | // 将助手回复添加到上下文 |
| 702 | await contextComponent.addAssistantMessage(response); |
| 703 | |
| 704 | return response; |
| 705 | } catch (error) { |
| 706 | this.log(`上下文聊天失败,降级到普通聊天: ${error}`); |
| 707 | // 降级到普通聊天 |
| 708 | return systemPrompt |
| 709 | ? await this.llmManager.chatWithSystem(systemPrompt, message) |
| 710 | : await this.llmManager.chat(message); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | /** |
| 715 | * 带上下文的智能工具调用聊天 |
no test coverage detected