()
| 230 | # ============================================================ |
| 231 | |
| 232 | def main(): |
| 233 | print("=" * 60) |
| 234 | print("Tutorial 01: Agentic Loop 基础演示") |
| 235 | print("=" * 60) |
| 236 | print() |
| 237 | print("场景:用户问 '2+2 等于几?'") |
| 238 | print("AI 不直接回答,而是先调用 add 工具,再根据结果回答。") |
| 239 | print() |
| 240 | |
| 241 | ai = FakeAI() |
| 242 | session = [] # 空的对话历史 |
| 243 | |
| 244 | # 执行一个对话轮次 |
| 245 | session = run_turn(ai, session, "2+2 等于几?") |
| 246 | |
| 247 | # 打印最终的完整对话历史 |
| 248 | print("\n" + "=" * 60) |
| 249 | print("完整对话历史:") |
| 250 | print("=" * 60) |
| 251 | for i, msg in enumerate(session): |
| 252 | print(f" [{i}] {msg}") |
| 253 | |
| 254 | # 解说 |
| 255 | print("\n" + "=" * 60) |
| 256 | print("关键理解要点:") |
| 257 | print("=" * 60) |
| 258 | print(""" |
| 259 | 1. Agentic Loop 的核心是一个 while True 循环 |
| 260 | 2. 每轮循环调用一次 AI,AI 可能回复文字,也可能要求使用工具 |
| 261 | 3. 如果 AI 要用工具 → 执行工具 → 把结果加入对话 → 继续循环 |
| 262 | 4. 如果 AI 回复文字 → 循环结束 |
| 263 | 5. 对话历史(session)是 AI 的"记忆",每次调用都传入全部历史 |
| 264 | |
| 265 | 对应 Claude Code 源码: |
| 266 | - conversation.rs:170 → run_turn() 函数入口 |
| 267 | - conversation.rs:183 → while True 循环开始 |
| 268 | - conversation.rs:196 → 调用 API (api_client.stream) |
| 269 | - conversation.rs:214 → 判断是否有 tool_use(break 条件) |
| 270 | - conversation.rs:218 → 遍历 pending_tool_uses 并执行 |
| 271 | """) |
| 272 | |
| 273 | |
| 274 | if __name__ == "__main__": |
no test coverage detected