context.py 2.3 KB

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