context.py 3.1 KB

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