模拟 AI 的回复。 参数: messages: 整个对话历史(所有聊天记录) 返回: 一个字典,表示 AI 的回复。格式有两种: - {"type": "text", "text": "..."} 表示普通文字回复 - {"type": "tool_use", "name": "...", "input": "..."} 表示要调用工具
(self, messages: list[Message])
| 82 | self.call_count = 0 # 记录被调用了几次 |
| 83 | |
| 84 | def chat(self, messages: list[Message]) -> dict: |
| 85 | """ |
| 86 | 模拟 AI 的回复。 |
| 87 | |
| 88 | 参数: |
| 89 | messages: 整个对话历史(所有聊天记录) |
| 90 | 返回: |
| 91 | 一个字典,表示 AI 的回复。格式有两种: |
| 92 | - {"type": "text", "text": "..."} 表示普通文字回复 |
| 93 | - {"type": "tool_use", "name": "...", "input": "..."} 表示要调用工具 |
| 94 | """ |
| 95 | self.call_count += 1 |
| 96 | |
| 97 | if self.call_count == 1: |
| 98 | # 第一次:AI 决定使用工具 |
| 99 | print(" [FakeAI] 第 1 次调用 → 我决定使用 'add' 工具") |
| 100 | return { |
| 101 | "type": "tool_use", |
| 102 | "name": "add", # 工具名称 |
| 103 | "input": "2,2", # 传给工具的参数 |
| 104 | } |
| 105 | else: |
| 106 | # 第二次:AI 看到了工具结果,给出最终回答 |
| 107 | # 先找到工具返回的结果 |
| 108 | tool_result = "" |
| 109 | for msg in messages: |
| 110 | if msg.role == "tool": |
| 111 | tool_result = msg.content |
| 112 | |
| 113 | print(f" [FakeAI] 第 2 次调用 → 我看到工具结果是 {tool_result},给出最终回答") |
| 114 | return { |
| 115 | "type": "text", |
| 116 | "text": f"2 + 2 的答案是 {tool_result}。", |
| 117 | } |
| 118 | |
| 119 | |
| 120 | # ============================================================ |