""" Step 03 练习题:扩展 SimpleAgent ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🎯 练习目标: 1. 巩固 Agent 循环的运行机制 2. 增强 Brain 的决策能力 3. 体验 Tool 的注册流程 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ """ # ═══════════════════════════════════════════════════════════════════════════════ # 练习 1:实现 DateTimeTool 并注册到 Agent # ═══════════════════════════════════════════════════════════════════════════════ """ 任务: 在 SimpleAgent 中添加一个 DateTimeTool,提供「现在几点 / 今天日期」能力。 要求: 1. 继承 BaseTool 2. name = "datetime",description 描述清楚能做什么 3. execute(**kwargs) 接收 operation,支持: - "now" -> 返回当前时间字符串("%Y-%m-%d %H:%M:%S") - "today" -> 返回当前日期字符串("%Y-%m-%d") - "weekday" -> 返回今天是星期几(中文,如 "星期一") 4. 注册到 SimpleAgent.tools 字典中 5. 测试:用户输入「现在几点」时 Brain 能正确选择 datetime 工具 """ # ═══════════════════════════════════════════════════════════════════════════════ # 练习 2:改进 Brain 的工具匹配 # ═══════════════════════════════════════════════════════════════════════════════ """ 任务: 当前 AgentBrain.decide() 用「关键词 + 表达式正则」匹配 calculator, 对「iOS / Android 兼容性」「产品 A+」这种文本会误判。 要求: 1. 在 AgentBrain.decide() 中加入你新加的 DateTimeTool 的路由 2. 修复 calculator 匹配的脆弱性(例如优先匹配明确的算式语法) 3. 让 Brain 在没有工具可调时返回 {"action": "respond", "response": "..."} 提示: - 可用正则在 user_input 中提取首个形如「数字 运算符 数字」的子串 - 用 keyword in user_input 检测「现在」「今天」「星期」触发 datetime """ # ═══════════════════════════════════════════════════════════════════════════════ # 练习 3:让 Agent 暴露对话快照 # ═══════════════════════════════════════════════════════════════════════════════ """ 任务: 给 SimpleAgent 增加 snapshot()/restore(snap) 方法,用于保存和恢复会话。 要求: 1. snapshot() 返回 dict,包含 messages、tool_result、current_action 2. restore(snap) 用 snap 覆盖对应字段 3. 验证:snapshot -> 多轮对话 -> restore -> 状态回到 snapshot 时刻 提示: - copy.deepcopy() 避免引用共享 - 只恢复可序列化的字段,不要把 self.brain / self.tools 一起覆盖 """ # ═══════════════════════════════════════════════════════════════════════════════ # 测试 # ═══════════════════════════════════════════════════════════════════════════════ def test_exercises(): from step_03_simple_agent.concept import SimpleAgent agent = SimpleAgent() print("当前已注册工具:", list(agent.tools.keys())) # TODO: 你的测试 if __name__ == "__main__": test_exercises()