agent_mode.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. class AgentMode(str, Enum):
  21. """Agent 对外暴露的两种运行模式。
  22. `legacy` 保留旧的一层委托,`recursive` 启用递归任务协议与资源边界。
  23. """
  24. LEGACY = "legacy"
  25. RECURSIVE = "recursive"
  26. @dataclass(frozen=True)
  27. class AgentPolicy:
  28. """某棵 Trace 树不可变的模式策略快照。
  29. Runner 将其写入根 Trace,Sub-Agent 创建子 Trace 时继承,各运行门禁据此判断能力。
  30. """
  31. mode: AgentMode
  32. revision: int
  33. max_depth: int
  34. max_children_per_parent: int | None
  35. accumulate_sub_trace_ids: bool
  36. show_sub_trace_shortcuts: bool
  37. @property
  38. def requires_task_protocol(self) -> bool:
  39. """Recursive revision 2 是否必须走结构化任务报告和审核流程。"""
  40. return self.mode is AgentMode.RECURSIVE and self.revision >= 2
  41. def to_context(self) -> dict[str, Any]:
  42. return {
  43. AGENT_MODE_CONTEXT_KEY: self.mode.value,
  44. AGENT_MODE_REVISION_CONTEXT_KEY: self.revision,
  45. }
  46. def _policy(mode: AgentMode, revision: int = 1) -> AgentPolicy:
  47. if mode is AgentMode.LEGACY:
  48. return AgentPolicy(
  49. mode=mode,
  50. revision=1,
  51. max_depth=1,
  52. max_children_per_parent=None,
  53. accumulate_sub_trace_ids=False,
  54. show_sub_trace_shortcuts=False,
  55. )
  56. return AgentPolicy(
  57. mode=mode,
  58. revision=revision,
  59. max_depth=5,
  60. max_children_per_parent=6,
  61. accumulate_sub_trace_ids=True,
  62. show_sub_trace_shortcuts=True,
  63. )
  64. def assert_removed_config_absent() -> None:
  65. """拒绝已删除的递归开关,避免运行时继续使用含糊配置。
  66. Runner 准备 Trace 和 ``agent`` 工具入口都会调用,新根 Trace 解析模式时也会间接调用。
  67. """
  68. if REMOVED_RECURSION_ENV in os.environ:
  69. raise ValueError(
  70. f"{REMOVED_RECURSION_ENV} has been removed; "
  71. f"set {AGENT_MODE_ENV}=legacy or {AGENT_MODE_ENV}=recursive instead"
  72. )
  73. def policy_from_environment(*, recursive_revision: int = 1) -> AgentPolicy:
  74. """为新建根 Trace 解析一次环境模式。
  75. `AgentRunner._prepare_new_trace` 在任何 Trace 落库前调用,返回的策略随后被持久化。
  76. """
  77. assert_removed_config_absent()
  78. raw_mode = os.getenv(AGENT_MODE_ENV, AgentMode.LEGACY.value).strip().lower()
  79. try:
  80. mode = AgentMode(raw_mode)
  81. except ValueError as exc:
  82. allowed = ", ".join(mode.value for mode in AgentMode)
  83. raise ValueError(
  84. f"Invalid {AGENT_MODE_ENV}={raw_mode!r}; expected one of: {allowed}"
  85. ) from exc
  86. revision = recursive_revision if mode is AgentMode.RECURSIVE else 1
  87. return _policy(mode, revision)
  88. def policy_from_context(context: Mapping[str, Any] | None) -> AgentPolicy:
  89. """从 Trace context 恢复已持久化的模式策略。
  90. Runner、Sub-Agent 和 Goal 工具在恢复或执行时调用;无模式字段的历史 Trace 按 Legacy 处理。
  91. """
  92. context = context or {}
  93. raw_mode = context.get(AGENT_MODE_CONTEXT_KEY, AgentMode.LEGACY.value)
  94. try:
  95. mode = AgentMode(str(raw_mode).strip().lower())
  96. except ValueError as exc:
  97. raise ValueError(f"Invalid persisted agent mode: {raw_mode!r}") from exc
  98. raw_revision = context.get(AGENT_MODE_REVISION_CONTEXT_KEY, 1)
  99. if not isinstance(raw_revision, int) or raw_revision < 1:
  100. raise ValueError(f"Invalid persisted agent mode revision: {raw_revision!r}")
  101. return _policy(mode, raw_revision)
  102. def apply_policy_to_context(
  103. context: MutableMapping[str, Any] | None,
  104. policy: AgentPolicy,
  105. ) -> dict[str, Any]:
  106. """将模式和 revision 覆盖写入一份 Trace context 副本。
  107. Runner 创建根 Trace、Sub-Agent 创建或续跑子 Trace 时调用,保证子孙继承同一策略。
  108. """
  109. merged = dict(context or {})
  110. merged.update(policy.to_context())
  111. return merged
  112. def validate_recursive_child_execution(
  113. mode: Any,
  114. max_parallel_children: Any,
  115. ) -> tuple[str, int]:
  116. """校验单批 Recursive 子 Agent 的串并行策略和硬上限。
  117. Runner 创建/恢复根 Trace 以及 `agent()` 调度子任务前调用,防止模型或 context 提高并发。
  118. """
  119. if mode not in {"sequential", "parallel"}:
  120. raise ValueError(
  121. "child_execution_mode must be 'sequential' or 'parallel'"
  122. )
  123. if (
  124. isinstance(max_parallel_children, bool)
  125. or not isinstance(max_parallel_children, int)
  126. or not 1 <= max_parallel_children <= MAX_PARALLEL_RECURSIVE_CHILDREN
  127. ):
  128. raise ValueError(
  129. "max_parallel_children must be an integer between 1 and "
  130. f"{MAX_PARALLEL_RECURSIVE_CHILDREN}"
  131. )
  132. return mode, max_parallel_children