context.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. 上下文工具 - 获取当前执行上下文
  3. 提供 get_current_context 工具,让 Agent 可以主动获取:
  4. - 当前计划(GoalTree)
  5. - 焦点提醒
  6. - 协作者状态
  7. 框架也会在特定轮次自动调用此工具进行周期性上下文刷新。
  8. """
  9. from agent.tools import tool, ToolResult, ToolContext
  10. @tool(
  11. description="获取当前执行上下文,包括计划状态、焦点提醒、协作者信息等。当你感到困惑或需要回顾当前任务状态时调用。",
  12. hidden_params=["context"]
  13. )
  14. async def get_current_context(
  15. context: ToolContext,
  16. ) -> ToolResult:
  17. """
  18. 获取当前执行上下文
  19. Returns:
  20. ToolResult: 包含 GoalTree、焦点提醒、协作者状态等信息
  21. """
  22. runner = context.get("runner")
  23. goal_tree = context.get("goal_tree")
  24. trace_id = context.get("trace_id")
  25. if not runner:
  26. return ToolResult(
  27. title="❌ 无法获取上下文",
  28. output="Runner 未初始化",
  29. error="Runner not available"
  30. )
  31. # 获取 trace 对象
  32. trace = None
  33. if runner.trace_store and trace_id:
  34. trace = await runner.trace_store.get_trace(trace_id)
  35. # 构建上下文内容(复用 runner 的 _build_context_injection 方法)
  36. if hasattr(runner, '_build_context_injection'):
  37. context_content = runner._build_context_injection(trace, goal_tree)
  38. else:
  39. # Fallback:只返回 GoalTree
  40. if goal_tree and goal_tree.goals:
  41. context_content = f"## Current Plan\n\n{goal_tree.to_prompt()}"
  42. else:
  43. context_content = "暂无计划信息"
  44. if not context_content:
  45. context_content = "当前无需要刷新的上下文信息"
  46. return ToolResult(
  47. title="📋 当前执行上下文",
  48. output=context_content,
  49. long_term_memory="已刷新执行上下文",
  50. )