goal_tool.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. """
  2. Goal 工具 - 计划管理
  3. 提供 goal 工具供 LLM 管理执行计划。
  4. """
  5. from typing import Optional, List, TYPE_CHECKING
  6. from agent.tools import tool
  7. if TYPE_CHECKING:
  8. from .goal_models import GoalTree
  9. from .protocols import TraceStore
  10. # ===== 全局 GoalTree 状态管理 =====
  11. _current_goal_tree = None
  12. def set_goal_tree(tree):
  13. """设置当前 GoalTree(由 AgentRunner 调用)"""
  14. global _current_goal_tree
  15. _current_goal_tree = tree
  16. def get_goal_tree():
  17. """获取当前 GoalTree"""
  18. return _current_goal_tree
  19. # ===== LLM 可调用的 goal 工具 =====
  20. @tool(description="管理执行计划,添加/完成/放弃目标,切换焦点")
  21. async def goal(
  22. add: Optional[str] = None,
  23. reason: Optional[str] = None,
  24. after: Optional[str] = None,
  25. under: Optional[str] = None,
  26. done: Optional[str] = None,
  27. abandon: Optional[str] = None,
  28. focus: Optional[str] = None,
  29. context: Optional[dict] = None
  30. ) -> str:
  31. """
  32. 管理执行计划,添加/完成/放弃目标,切换焦点。
  33. Args:
  34. add: 添加目标(逗号分隔多个)
  35. reason: 创建理由(逗号分隔多个,与 add 一一对应)
  36. after: 在指定目标后面添加(同层级)
  37. under: 为指定目标添加子目标
  38. done: 完成当前目标,值为 summary
  39. abandon: 放弃当前目标,值为原因
  40. focus: 切换焦点到指定 ID
  41. context: 工具执行上下文(包含 store 和 trace_id)
  42. Returns:
  43. str: 更新后的计划状态文本
  44. """
  45. tree = get_goal_tree()
  46. if tree is None:
  47. return "错误:GoalTree 未初始化"
  48. # 从 context 获取 store 和 trace_id
  49. store = context.get("store") if context else None
  50. trace_id = context.get("trace_id") if context else None
  51. return await goal_tool(
  52. tree=tree,
  53. store=store,
  54. trace_id=trace_id,
  55. add=add,
  56. reason=reason,
  57. after=after,
  58. under=under,
  59. done=done,
  60. abandon=abandon,
  61. focus=focus
  62. )
  63. # ===== 核心逻辑函数 =====
  64. async def goal_tool(
  65. tree: "GoalTree",
  66. store: Optional["TraceStore"] = None,
  67. trace_id: Optional[str] = None,
  68. add: Optional[str] = None,
  69. reason: Optional[str] = None,
  70. after: Optional[str] = None,
  71. under: Optional[str] = None,
  72. done: Optional[str] = None,
  73. abandon: Optional[str] = None,
  74. focus: Optional[str] = None,
  75. ) -> str:
  76. """
  77. 管理执行计划。
  78. Args:
  79. tree: GoalTree 实例
  80. store: TraceStore 实例(用于推送事件)
  81. trace_id: 当前 Trace ID
  82. add: 添加目标(逗号分隔多个)
  83. reason: 创建理由(逗号分隔多个,与 add 一一对应)
  84. after: 在指定目标后面添加(同层级)
  85. under: 为指定目标添加子目标
  86. done: 完成当前目标,值为 summary
  87. abandon: 放弃当前目标,值为原因
  88. focus: 切换焦点到指定 ID
  89. Returns:
  90. 更新后的计划状态文本
  91. """
  92. changes = []
  93. # 1. 处理 done(完成当前目标)
  94. if done is not None:
  95. if not tree.current_id:
  96. return f"错误:没有当前目标可以完成。当前焦点为空,请先使用 focus 参数切换到要完成的目标。\n\n当前计划:\n{tree.to_prompt()}"
  97. # 完成当前目标
  98. # 如果同时指定了 focus,则不清空焦点(后面会切换到新目标)
  99. # 如果只有 done,则清空焦点
  100. clear_focus = (focus is None)
  101. goal = tree.complete(tree.current_id, done, clear_focus=clear_focus)
  102. display_id = tree._generate_display_id(goal)
  103. changes.append(f"已完成: {display_id}. {goal.description}")
  104. # 推送事件
  105. if store and trace_id:
  106. print(f"[DEBUG] goal_tool: calling store.update_goal for done: goal_id={goal.id}")
  107. await store.update_goal(trace_id, goal.id, status="completed", summary=done)
  108. else:
  109. print(f"[DEBUG] goal_tool: skip event push (store={store}, trace_id={trace_id})")
  110. # 检查是否有级联完成的父目标(complete方法已经处理,这里只需要记录)
  111. if goal.parent_id:
  112. parent = tree.find(goal.parent_id)
  113. if parent and parent.status == "completed":
  114. parent_display_id = tree._generate_display_id(parent)
  115. changes.append(f"自动完成: {parent_display_id}. {parent.description}(所有子目标已完成)")
  116. # 2. 处理 focus(切换焦点到新目标)
  117. if focus is not None:
  118. goal = tree.find_by_display_id(focus)
  119. if not goal:
  120. return f"错误:找不到目标 {focus}\n\n当前计划:\n{tree.to_prompt()}"
  121. tree.focus(goal.id)
  122. display_id = tree._generate_display_id(goal)
  123. changes.append(f"切换焦点: {display_id}. {goal.description}")
  124. # 3. 处理 abandon(放弃当前目标)
  125. if abandon is not None:
  126. if not tree.current_id:
  127. return f"错误:没有当前目标可以放弃。当前焦点为空。\n\n当前计划:\n{tree.to_prompt()}"
  128. goal = tree.abandon(tree.current_id, abandon)
  129. display_id = tree._generate_display_id(goal)
  130. changes.append(f"已放弃: {display_id}. {goal.description}")
  131. # 推送事件
  132. if store and trace_id:
  133. print(f"[DEBUG] goal_tool: calling store.update_goal for abandon: goal_id={goal.id}")
  134. await store.update_goal(trace_id, goal.id, status="abandoned", summary=abandon)
  135. else:
  136. print(f"[DEBUG] goal_tool: skip event push (store={store}, trace_id={trace_id})")
  137. # 4. 处理 add
  138. if add is not None:
  139. # 检查 after 和 under 互斥
  140. if after is not None and under is not None:
  141. return "错误:after 和 under 参数不能同时指定"
  142. descriptions = [d.strip() for d in add.split(",") if d.strip()]
  143. if descriptions:
  144. # 解析 reasons(与 descriptions 一一对应)
  145. reasons = None
  146. if reason:
  147. reasons = [r.strip() for r in reason.split(",")]
  148. # 如果 reasons 数量少于 descriptions,补空字符串
  149. while len(reasons) < len(descriptions):
  150. reasons.append("")
  151. # 确定添加位置
  152. if after is not None:
  153. # 在指定 goal 后面添加(同层级)
  154. target_goal = tree.find_by_display_id(after)
  155. if not target_goal:
  156. return f"错误:找不到目标 {after}\n\n当前计划:\n{tree.to_prompt()}"
  157. new_goals = tree.add_goals_after(target_goal.id, descriptions, reasons=reasons)
  158. changes.append(f"在 {tree._generate_display_id(target_goal)} 后面添加 {len(new_goals)} 个同级目标")
  159. elif under is not None:
  160. # 为指定 goal 添加子目标
  161. parent_goal = tree.find_by_display_id(under)
  162. if not parent_goal:
  163. return f"错误:找不到目标 {under}\n\n当前计划:\n{tree.to_prompt()}"
  164. new_goals = tree.add_goals(descriptions, reasons=reasons, parent_id=parent_goal.id)
  165. changes.append(f"在 {tree._generate_display_id(parent_goal)} 下添加 {len(new_goals)} 个子目标")
  166. else:
  167. # 默认行为:添加到当前焦点下(如果有焦点),否则添加到顶层
  168. parent_id = tree.current_id
  169. new_goals = tree.add_goals(descriptions, reasons=reasons, parent_id=parent_id)
  170. if parent_id:
  171. parent_display_id = tree._generate_display_id(tree.find(parent_id))
  172. changes.append(f"在 {parent_display_id} 下添加 {len(new_goals)} 个子目标")
  173. else:
  174. changes.append(f"添加 {len(new_goals)} 个顶层目标")
  175. # 推送事件
  176. if store and trace_id:
  177. print(f"[DEBUG] goal_tool: calling store.add_goal for {len(new_goals)} new goals")
  178. for goal in new_goals:
  179. await store.add_goal(trace_id, goal)
  180. else:
  181. print(f"[DEBUG] goal_tool: skip event push (store={store}, trace_id={trace_id})")
  182. # 如果没有焦点且添加了目标,自动 focus 到第一个新目标
  183. if not tree.current_id and new_goals:
  184. tree.focus(new_goals[0].id)
  185. display_id = tree._generate_display_id(new_goals[0])
  186. changes.append(f"自动切换焦点: {display_id}")
  187. # 返回当前状态
  188. result = []
  189. if changes:
  190. result.append("## 更新")
  191. result.extend(f"- {c}" for c in changes)
  192. result.append("")
  193. result.append("## Current Plan")
  194. result.append(tree.to_prompt())
  195. return "\n".join(result)
  196. def create_goal_tool_schema() -> dict:
  197. """创建 goal 工具的 JSON Schema"""
  198. return {
  199. "name": "goal",
  200. "description": """管理执行计划。目标工具是灵活的支持系统,帮助你组织和追踪工作进度。
  201. 使用策略(按需选择):
  202. - 全局规划:先规划所有目标,再逐个执行
  203. - 渐进规划:走一步看一步,每次只创建下一个目标
  204. - 动态调整:行动中随时 abandon 不可行的目标,创建新目标
  205. 参数:
  206. - add: 添加目标(逗号分隔多个)
  207. - reason: 创建理由(逗号分隔,与 add 一一对应)
  208. - after: 在指定目标后面添加同级目标。使用目标 ID。
  209. - under: 为指定目标添加子目标。使用目标 ID。如已有子目标,追加到最后。
  210. - done: 完成当前目标,值为 summary(记录关键结论)
  211. - abandon: 放弃当前目标,值为原因
  212. - focus: 切换焦点到指定目标。使用目标 ID。
  213. 位置控制(优先使用 after):
  214. - 不指定 after/under: 添加到当前 focus 下作为子目标(无 focus 时添加到顶层)
  215. - after="X": 在目标 X 后面添加兄弟节点(同层级)
  216. - under="X": 为目标 X 添加子目标
  217. - after 和 under 不能同时指定
  218. 执行顺序:
  219. - done → focus → abandon → add
  220. - 如果同时指定 done 和 focus,会先完成当前目标,再切换焦点到新目标
  221. 示例:
  222. - goal(add="分析代码, 实现功能, 测试") - 添加顶层目标
  223. - goal(add="设计接口, 实现代码", under="2") - 为目标2添加子目标
  224. - goal(add="编写文档", after="3") - 在目标3后面添加同级任务
  225. - goal(add="集成测试", after="2.2") - 在目标2.2后面添加同级任务
  226. - goal(done="发现用户模型在 models/user.py") - 完成当前目标
  227. - goal(done="已完成调研", focus="2") - 完成当前目标,切换到目标2
  228. - goal(abandon="方案A需要Redis,环境没有") - 放弃当前目标
  229. 注意:
  230. - 目标 ID 的格式为 "1", "2", "2.1", "2.2" 等,在计划视图中可以看到
  231. - reason 应该与 add 的目标数量一致,如果数量不一致,缺少的 reason 将为空
  232. """,
  233. "parameters": {
  234. "type": "object",
  235. "properties": {
  236. "add": {
  237. "type": "string",
  238. "description": "添加目标(逗号分隔多个)"
  239. },
  240. "reason": {
  241. "type": "string",
  242. "description": "创建理由(逗号分隔多个,与 add 一一对应)。说明为什么要做这些目标。"
  243. },
  244. "after": {
  245. "type": "string",
  246. "description": "在指定目标后面添加(同层级)。使用目标的 ID,如 \"2\" 或 \"2.1\"。"
  247. },
  248. "under": {
  249. "type": "string",
  250. "description": "为指定目标添加子目标。使用目标的 ID,如 \"2\" 或 \"2.1\"。"
  251. },
  252. "done": {
  253. "type": "string",
  254. "description": "完成当前目标,值为 summary"
  255. },
  256. "abandon": {
  257. "type": "string",
  258. "description": "放弃当前目标,值为原因"
  259. },
  260. "focus": {
  261. "type": "string",
  262. "description": "切换焦点到指定目标。使用目标的 ID,如 \"2\" 或 \"2.1\"。"
  263. }
  264. },
  265. "required": []
  266. }
  267. }