agent_mode.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. """Agent 委托模式及其统一运行策略。
  2. Runner 仅在创建根 Trace 时读取环境模式,随后将策略持久化并传给所有本地子孙。
  3. Runner、Sub-Agent 工具和 Goal 工具共同使用该策略,保证运行中的任务树不被环境变更改变。
  4. """
  5. from __future__ import annotations
  6. from dataclasses import dataclass
  7. from enum import Enum
  8. import os
  9. from typing import Any, Mapping, MutableMapping
  10. AGENT_MODE_ENV = "AGENT_MODE"
  11. REMOVED_RECURSION_ENV = "AGENT_RECURSION_ENABLED"
  12. AGENT_MODE_CONTEXT_KEY = "agent_mode"
  13. AGENT_MODE_REVISION_CONTEXT_KEY = "agent_mode_revision"
  14. # Runner 注入给本地 agent 工具的内部上下文。它们不来自 LLM 参数,也不持久化
  15. # 到 Trace;Recursive 子级只能继承调用方在本次运行中实际拥有的能力与调度策略。
  16. RECURSIVE_CAPABILITY_TOOLS_CONTEXT_KEY = "_recursive_capability_tool_names"
  17. RECURSIVE_CHILD_EXECUTION_MODE_CONTEXT_KEY = "_recursive_child_execution_mode"
  18. RECURSIVE_MAX_PARALLEL_CHILDREN_CONTEXT_KEY = "_recursive_max_parallel_children"
  19. MAX_PARALLEL_RECURSIVE_CHILDREN = 2
  20. RECURSIVE_REVISION_READ_ONLY_ERROR = "recursive_revision_2_read_only"
  21. CURRENT_RECURSIVE_REVISION = 3
  22. class AgentMode(str, Enum):
  23. """Agent 对外暴露的两种运行模式。
  24. `legacy` 保留旧的一层委托,`recursive` 启用递归任务协议与资源边界。
  25. """
  26. LEGACY = "legacy"
  27. RECURSIVE = "recursive"
  28. @dataclass(frozen=True)
  29. class AgentPolicy:
  30. """某棵 Trace 树不可变的模式策略快照。
  31. Runner 将其写入根 Trace,Sub-Agent 创建子 Trace 时继承,各运行门禁据此判断能力。
  32. """
  33. mode: AgentMode
  34. revision: int
  35. max_depth: int
  36. max_children_per_parent: int | None
  37. accumulate_sub_trace_ids: bool
  38. show_sub_trace_shortcuts: bool
  39. @property
  40. def requires_task_protocol(self) -> bool:
  41. """Recursive revision 2+ 是否使用结构化任务协议。"""
  42. return self.mode is AgentMode.RECURSIVE and self.revision >= 2
  43. @property
  44. def requires_task_progress(self) -> bool:
  45. """Recursive revision 3 是否强制使用 TaskProgress。"""
  46. return self.mode is AgentMode.RECURSIVE and self.revision >= 3
  47. @property
  48. def is_read_only(self) -> bool:
  49. """历史 Recursive revision 2 只保留读取和导出。"""
  50. return self.mode is AgentMode.RECURSIVE and self.revision == 2
  51. def to_context(self) -> dict[str, Any]:
  52. return {
  53. AGENT_MODE_CONTEXT_KEY: self.mode.value,
  54. AGENT_MODE_REVISION_CONTEXT_KEY: self.revision,
  55. }
  56. def _policy(mode: AgentMode, revision: int = 1) -> AgentPolicy:
  57. if mode is AgentMode.LEGACY:
  58. return AgentPolicy(
  59. mode=mode,
  60. revision=1,
  61. max_depth=1,
  62. max_children_per_parent=None,
  63. accumulate_sub_trace_ids=False,
  64. show_sub_trace_shortcuts=False,
  65. )
  66. return AgentPolicy(
  67. mode=mode,
  68. revision=revision,
  69. max_depth=5,
  70. max_children_per_parent=6,
  71. accumulate_sub_trace_ids=True,
  72. show_sub_trace_shortcuts=True,
  73. )
  74. def assert_removed_config_absent() -> None:
  75. """拒绝已删除的递归开关,避免运行时继续使用含糊配置。
  76. Runner 准备 Trace 和 ``agent`` 工具入口都会调用,新根 Trace 解析模式时也会间接调用。
  77. """
  78. if REMOVED_RECURSION_ENV in os.environ:
  79. raise ValueError(
  80. f"{REMOVED_RECURSION_ENV} has been removed; "
  81. f"set {AGENT_MODE_ENV}=legacy or {AGENT_MODE_ENV}=recursive instead"
  82. )
  83. def policy_from_environment(*, recursive_revision: int = 1) -> AgentPolicy:
  84. """为新建根 Trace 解析一次环境模式。
  85. `AgentRunner._prepare_new_trace` 在任何 Trace 落库前调用,返回的策略随后被持久化。
  86. """
  87. assert_removed_config_absent()
  88. raw_mode = os.getenv(AGENT_MODE_ENV, AgentMode.LEGACY.value).strip().lower()
  89. try:
  90. mode = AgentMode(raw_mode)
  91. except ValueError as exc:
  92. allowed = ", ".join(mode.value for mode in AgentMode)
  93. raise ValueError(
  94. f"Invalid {AGENT_MODE_ENV}={raw_mode!r}; expected one of: {allowed}"
  95. ) from exc
  96. revision = recursive_revision if mode is AgentMode.RECURSIVE else 1
  97. return _policy(mode, revision)
  98. def policy_from_context(context: Mapping[str, Any] | None) -> AgentPolicy:
  99. """从 Trace context 恢复已持久化的模式策略。
  100. Runner、Sub-Agent 和 Goal 工具在恢复或执行时调用;无模式字段的历史 Trace 按 Legacy 处理。
  101. """
  102. context = context or {}
  103. raw_mode = context.get(AGENT_MODE_CONTEXT_KEY, AgentMode.LEGACY.value)
  104. try:
  105. mode = AgentMode(str(raw_mode).strip().lower())
  106. except ValueError as exc:
  107. raise ValueError(f"Invalid persisted agent mode: {raw_mode!r}") from exc
  108. raw_revision = context.get(AGENT_MODE_REVISION_CONTEXT_KEY, 1)
  109. if not isinstance(raw_revision, int) or raw_revision < 1:
  110. raise ValueError(f"Invalid persisted agent mode revision: {raw_revision!r}")
  111. return _policy(mode, raw_revision)
  112. def apply_policy_to_context(
  113. context: MutableMapping[str, Any] | None,
  114. policy: AgentPolicy,
  115. ) -> dict[str, Any]:
  116. """将模式和 revision 覆盖写入一份 Trace context 副本。
  117. Runner 创建根 Trace、Sub-Agent 创建或续跑子 Trace 时调用,保证子孙继承同一策略。
  118. """
  119. merged = dict(context or {})
  120. merged.update(policy.to_context())
  121. return merged
  122. def require_mutable_trace_policy(context: Mapping[str, Any] | None) -> AgentPolicy:
  123. """返回可写 Trace 的持久化策略,并统一拒绝已退役的 revision 2。"""
  124. policy = policy_from_context(context)
  125. if policy.is_read_only:
  126. raise ValueError(RECURSIVE_REVISION_READ_ONLY_ERROR)
  127. return policy
  128. def validate_recursive_child_execution(
  129. mode: Any,
  130. max_parallel_children: Any,
  131. ) -> tuple[str, int]:
  132. """校验单批 Recursive 子 Agent 的串并行策略和硬上限。
  133. Runner 创建/恢复根 Trace 以及 `agent()` 调度子任务前调用,防止模型或 context 提高并发。
  134. """
  135. if mode not in {"sequential", "parallel"}:
  136. raise ValueError(
  137. "child_execution_mode must be 'sequential' or 'parallel'"
  138. )
  139. if (
  140. isinstance(max_parallel_children, bool)
  141. or not isinstance(max_parallel_children, int)
  142. or not 1 <= max_parallel_children <= MAX_PARALLEL_RECURSIVE_CHILDREN
  143. ):
  144. raise ValueError(
  145. "max_parallel_children must be an integer between 1 and "
  146. f"{MAX_PARALLEL_RECURSIVE_CHILDREN}"
  147. )
  148. return mode, max_parallel_children