context.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. # Fallback 也检查 IM 通知
  45. im_config = trace.context.get("im_config") if trace else None
  46. if im_config:
  47. contact_id = im_config.get("contact_id")
  48. chat_id = im_config.get("chat_id")
  49. if contact_id and chat_id:
  50. try:
  51. from agent.tools.builtin.im import chat as im_chat
  52. notification = im_chat._notifications.get((contact_id, chat_id))
  53. if notification:
  54. count = notification.get("count", 0)
  55. senders = notification.get("from", [])
  56. senders_str = ", ".join(senders)
  57. context_content += (
  58. f"\n\n## IM 消息通知\n\n"
  59. f"你有 {count} 条新消息,来自: {senders_str}\n"
  60. f"使用 `im_receive_messages(contact_id=\"{contact_id}\", chat_id=\"{chat_id}\")` 查看消息内容。"
  61. )
  62. else:
  63. context_content += "\n\n## IM 消息通知\n\n暂无新消息"
  64. except (ImportError, AttributeError):
  65. pass
  66. if not context_content:
  67. context_content = "当前无需要刷新的上下文信息"
  68. return ToolResult(
  69. title="📋 当前执行上下文",
  70. output=context_content,
  71. long_term_memory="已刷新执行上下文",
  72. )