* 智能聊天 - 支持工具调用的完整流程 * 这是 Agent 的核心协调逻辑
(message: string)
| 294 | * 这是 Agent 的核心协调逻辑 |
| 295 | */ |
| 296 | public async smartChat(message: string): Promise<AgentResponse> { |
| 297 | if (!this.llmManager.isAvailable()) { |
| 298 | throw new Error('LLM 未配置或不可用'); |
| 299 | } |
| 300 | |
| 301 | this.log(`开始智能聊天: ${message.substring(0, 50)}...`); |
| 302 | |
| 303 | // 第一步:分析用户意图,判断是否需要工具调用 |
| 304 | const toolAnalysis = await this.analyzeToolNeed(message); |
| 305 | |
| 306 | if (!toolAnalysis.needsTool) { |
| 307 | // 不需要工具,直接回答 |
| 308 | const content = await this.llmManager.chat(message); |
| 309 | return { |
| 310 | content, |
| 311 | reasoning: '无需工具调用,直接回答', |
| 312 | }; |
| 313 | } |
| 314 | |
| 315 | // 第二步:识别并调用工具 |
| 316 | const toolResults: ToolCallResult[] = []; |
| 317 | |
| 318 | for (const toolCall of toolAnalysis.toolCalls) { |
| 319 | try { |
| 320 | this.log(`调用工具: ${toolCall.toolName}`); |
| 321 | const result = await this.callToolSmart(toolCall); |
| 322 | toolResults.push(result); |
| 323 | } catch (error) { |
| 324 | const errorResult: ToolCallResult = { |
| 325 | toolName: toolCall.toolName, |
| 326 | success: false, |
| 327 | result: null, |
| 328 | error: (error as Error).message, |
| 329 | }; |
| 330 | toolResults.push(errorResult); |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // 第三步:基于工具结果生成最终回答 |
| 335 | const finalAnswer = await this.generateAnswerWithToolResults(message, toolResults); |
| 336 | |
| 337 | return { |
| 338 | content: finalAnswer, |
| 339 | toolCalls: toolResults, |
| 340 | reasoning: `使用了 ${toolResults.length} 个工具协助回答`, |
| 341 | }; |
| 342 | } |
| 343 | |
| 344 | /** |
| 345 | * 分析用户消息是否需要工具调用 |
no test coverage detected