* 带上下文的智能工具调用聊天
(message: string)
| 715 | * 带上下文的智能工具调用聊天 |
| 716 | */ |
| 717 | public async smartChatWithContext(message: string): Promise<AgentResponse> { |
| 718 | const contextComponent = this.getContextComponent(); |
| 719 | |
| 720 | if (!contextComponent || !contextComponent.isContextReady()) { |
| 721 | // 如果没有上下文组件或未就绪,降级到普通智能聊天 |
| 722 | this.log('上下文组件未就绪,使用普通智能聊天模式'); |
| 723 | return await this.smartChat(message); |
| 724 | } |
| 725 | |
| 726 | try { |
| 727 | // 构建包含上下文的消息列表 |
| 728 | const messages = await contextComponent.buildMessagesWithContext(message); |
| 729 | |
| 730 | // 转换为LLM消息格式 |
| 731 | const llmMessages: LLMMessage[] = messages.map(msg => ({ |
| 732 | role: msg.role as 'user' | 'assistant' | 'system', |
| 733 | content: msg.content, |
| 734 | })); |
| 735 | |
| 736 | // 分析是否需要工具调用(基于包含上下文的消息) |
| 737 | const toolAnalysis = await this.analyzeToolNeed(message); |
| 738 | |
| 739 | if (!toolAnalysis.needsTool) { |
| 740 | // 不需要工具,使用上下文进行对话 |
| 741 | const response = await this.llmManager.conversation(llmMessages); |
| 742 | |
| 743 | // 将助手回复添加到上下文 |
| 744 | await contextComponent.addAssistantMessage(response); |
| 745 | |
| 746 | return { |
| 747 | content: response, |
| 748 | reasoning: '基于上下文的对话,无需工具调用', |
| 749 | }; |
| 750 | } |
| 751 | |
| 752 | // 需要工具调用,执行工具 |
| 753 | const toolResults: ToolCallResult[] = []; |
| 754 | |
| 755 | for (const toolCall of toolAnalysis.toolCalls) { |
| 756 | try { |
| 757 | this.log(`调用工具: ${toolCall.toolName}`); |
| 758 | const result = await this.callToolSmart(toolCall); |
| 759 | toolResults.push(result); |
| 760 | } catch (error) { |
| 761 | const errorResult: ToolCallResult = { |
| 762 | toolName: toolCall.toolName, |
| 763 | success: false, |
| 764 | result: null, |
| 765 | error: (error as Error).message, |
| 766 | }; |
| 767 | toolResults.push(errorResult); |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | // 基于工具结果和上下文生成最终回答 |
| 772 | const finalAnswer = await this.generateAnswerWithToolResults(message, toolResults); |
| 773 | |
| 774 | // 将助手回复添加到上下文 |
no test coverage detected