模拟 AI 的回复。 第一次被调用时:返回一个工具调用请求("我要用计算器") 第二次被调用时:根据工具结果,返回最终回答 在真正的 Claude Code 里,这是通过 HTTP 请求调用 Anthropic API 实现的。 对应源码: rust/crates/api/src/client.rs (AnthropicClient)
| 68 | # 3. 让 AI 继续思考 |
| 69 | |
| 70 | class FakeAI: |
| 71 | """ |
| 72 | 模拟 AI 的回复。 |
| 73 | |
| 74 | 第一次被调用时:返回一个工具调用请求("我要用计算器") |
| 75 | 第二次被调用时:根据工具结果,返回最终回答 |
| 76 | |
| 77 | 在真正的 Claude Code 里,这是通过 HTTP 请求调用 Anthropic API 实现的。 |
| 78 | 对应源码: rust/crates/api/src/client.rs (AnthropicClient) |
| 79 | """ |
| 80 | |
| 81 | def __init__(self): |
| 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 | # ============================================================ |