agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """Outer round orchestrator for the isolated find agent."""
  2. from __future__ import annotations
  3. import asyncio
  4. import json
  5. from dataclasses import dataclass
  6. from find_agent_v2.context import build_node_slots
  7. from find_agent_v2.graph import FindAgentRoundGraph, NodeRunner
  8. from find_agent_v2.observability import ObagentObserver
  9. from find_agent_v2.prompts import REPORT_PROMPT
  10. from find_agent_v2.runtime import FindAgentNodeHost, normalize_models
  11. from find_agent_v2.service import (
  12. RUN_TIMEOUT_REASON,
  13. RUN_TIMEOUT_SECONDS,
  14. FindAgentV2Service,
  15. get_find_agent_v2_service,
  16. )
  17. from find_agent_v2.state import DiscoverySnapshot, FindAgentResult, FindAgentState
  18. from find_agent_v2.tools import REPORT_TOOLS
  19. from supply_agent.config import Settings
  20. @dataclass(frozen=True)
  21. class ExplorationDecision:
  22. continue_exploring: bool
  23. reason: str
  24. new_candidate_count: int
  25. new_evaluated_count: int
  26. round_pass_rate: float
  27. cumulative_pass_rate: float
  28. def decide_continued_exploration(
  29. previous: DiscoverySnapshot, current: DiscoverySnapshot,
  30. ) -> ExplorationDecision:
  31. """Decide whether to continue from discovery volume and evaluation yield."""
  32. new_candidates = max(0, current.candidate_count - previous.candidate_count)
  33. previous_evaluated = previous.primary_count + previous.rejected_count
  34. current_evaluated = current.primary_count + current.rejected_count
  35. new_evaluated = max(0, current_evaluated - previous_evaluated)
  36. new_passed = max(0, current.valid_primary_count - previous.valid_primary_count)
  37. round_rate = new_passed / new_evaluated if new_evaluated else 0.0
  38. cumulative_rate = (
  39. current.valid_primary_count / current_evaluated if current_evaluated else 0.0
  40. )
  41. if new_candidates == 0:
  42. keep_going = False
  43. reason = "本轮没有新增候选,搜索前沿已无信息增益"
  44. elif current_evaluated < 8:
  45. keep_going = True
  46. reason = "已评估样本不足 8 条,继续探索以形成可靠通过率"
  47. elif new_evaluated and round_rate == 0:
  48. keep_going = False
  49. reason = "本轮有足够评估样本但通过率为 0,继续搜索的预期收益低"
  50. elif new_candidates >= 2 and (round_rate >= 0.10 or cumulative_rate >= 0.10):
  51. keep_going = True
  52. reason = "本轮仍有候选增量且评估保持正向通过率,继续探索"
  53. else:
  54. keep_going = False
  55. reason = "候选增量或评估通过率不足,停止探索"
  56. return ExplorationDecision(
  57. continue_exploring=keep_going,
  58. reason=reason,
  59. new_candidate_count=new_candidates,
  60. new_evaluated_count=new_evaluated,
  61. round_pass_rate=round(round_rate, 4),
  62. cumulative_pass_rate=round(cumulative_rate, 4),
  63. )
  64. class FindAgentV2:
  65. """Python outer loop + guarded Supervisor graph + node-local ReAct."""
  66. def __init__(
  67. self,
  68. *,
  69. service: FindAgentV2Service | None = None,
  70. node_runner: NodeRunner | None = None,
  71. settings: Settings | None = None,
  72. models_by_role: dict[str, str] | None = None,
  73. max_rounds: int = 2,
  74. max_actions_per_round: int = 16,
  75. max_search_actions_per_round: int = 3,
  76. max_runtime_seconds: float = RUN_TIMEOUT_SECONDS,
  77. observer: ObagentObserver | None = None,
  78. ) -> None:
  79. self.service = service or get_find_agent_v2_service()
  80. self.observer = observer or ObagentObserver()
  81. self.node_runner = node_runner or FindAgentNodeHost(
  82. settings=settings,
  83. models_by_role=models_by_role,
  84. observer=self.observer,
  85. )
  86. self.models_by_role = dict(models_by_role or {})
  87. self.max_rounds = max(1, int(max_rounds))
  88. self.max_actions_per_round = max(4, int(max_actions_per_round))
  89. self.max_search_actions_per_round = max(1, int(max_search_actions_per_round))
  90. self.max_runtime_seconds = max(0.01, float(max_runtime_seconds))
  91. async def arun(
  92. self, *, run_id: str, user_input: str, resume: bool = False,
  93. ) -> FindAgentResult:
  94. run = self.service.require_run(run_id)
  95. if resume and str(run.get("status") or "") != "running":
  96. run = self.service.prepare_resume(run_id)
  97. if str(run.get("status") or "") != "running":
  98. raise ValueError(f"run_id={run_id} 当前状态不可执行: {run.get('status')}")
  99. state = FindAgentState(run_id=run_id, user_input=user_input)
  100. graph = FindAgentRoundGraph(
  101. service=self.service, runner=self.node_runner, observer=self.observer,
  102. max_actions=self.max_actions_per_round,
  103. max_search_actions=self.max_search_actions_per_round,
  104. )
  105. reset_usage = getattr(self.node_runner, "reset_usage", None)
  106. if callable(reset_usage):
  107. reset_usage()
  108. default_model = self.models_by_role.get("supervisor", "google/gemini-3-flash-preview")
  109. with self.observer.run(
  110. run_id=run_id,
  111. demand_word=str(run.get("demand_word") or ""),
  112. model=default_model,
  113. models_by_role=self.models_by_role,
  114. ) as observation_run:
  115. self.service.set_obagent_run_uid(
  116. run_id, getattr(observation_run, "run_uid", None),
  117. )
  118. try:
  119. result = await asyncio.wait_for(
  120. self._arun_inner(
  121. state=state, graph=graph,
  122. start_round=int(run.get("current_round") or 0) + 1,
  123. ),
  124. timeout=self.max_runtime_seconds,
  125. )
  126. except TimeoutError:
  127. self.service.fail_run(run_id, RUN_TIMEOUT_REASON)
  128. final_run = self.service.require_run(run_id)
  129. result = FindAgentResult(
  130. run_id=run_id,
  131. status="failed",
  132. succeeded=False,
  133. business_outcome="failed",
  134. valid_primary_count=int(final_run.get("valid_primary_count") or 0),
  135. rounds=state.round_index,
  136. final_output=f"find_agent_v2 failed:{RUN_TIMEOUT_REASON}",
  137. node_runs=tuple(state.node_runs),
  138. stop_reason=RUN_TIMEOUT_REASON,
  139. )
  140. usage = getattr(self.node_runner, "usage", None)
  141. if isinstance(usage, dict):
  142. self.service.add_usage(run_id, usage)
  143. observation_run.finish(final_output=result.final_output)
  144. return result
  145. async def _arun_inner(
  146. self, *, state: FindAgentState, graph: FindAgentRoundGraph, start_round: int = 1,
  147. ) -> FindAgentResult:
  148. run_id = state.run_id
  149. end_reason = ""
  150. failed = False
  151. try:
  152. end_round = start_round + self.max_rounds
  153. for round_index in range(start_round, end_round):
  154. state.round_index = round_index
  155. state.previous_snapshot = self.service.snapshot(run_id)
  156. self.service.begin_round(run_id, round_index, state.previous_snapshot)
  157. await graph.invoke(state)
  158. current = state.snapshot or self.service.snapshot(run_id)
  159. if current.pending_count:
  160. failed = True
  161. end_reason = f"第 {round_index} 轮结束仍有 {current.pending_count} 条待评估候选"
  162. break
  163. exploration = decide_continued_exploration(
  164. state.previous_snapshot, current,
  165. )
  166. if not exploration.continue_exploring:
  167. end_reason = exploration.reason
  168. break
  169. if round_index == end_round - 1:
  170. end_reason = (
  171. f"达到最大业务轮数 {self.max_rounds};{exploration.reason};"
  172. f"本轮新增={exploration.new_candidate_count},"
  173. f"本轮通过率={exploration.round_pass_rate:.1%},"
  174. f"累计通过率={exploration.cumulative_pass_rate:.1%}"
  175. )
  176. except Exception as exc:
  177. failed = True
  178. end_reason = f"{type(exc).__name__}: {exc}"
  179. state.failures.append({"round": state.round_index, "error": end_reason})
  180. if state.round_index:
  181. try:
  182. self.service.update_round(
  183. run_id, state.round_index, status="failed", error=end_reason,
  184. )
  185. except Exception:
  186. pass
  187. final_run = self.service.finalize(
  188. run_id,
  189. failed=failed,
  190. reason=end_reason,
  191. )
  192. final_output = (
  193. f"find_agent_v2 {final_run['outcome_status']},"
  194. f"有效 primary={final_run['valid_primary_count']}。"
  195. )
  196. if not failed:
  197. try:
  198. report = await self.node_runner.run_node(
  199. node="report",
  200. round_index=state.round_index,
  201. system_prompt=REPORT_PROMPT,
  202. user_content=json.dumps(
  203. self.service.get_full_state(run_id),
  204. ensure_ascii=False,
  205. default=str,
  206. ),
  207. tools=REPORT_TOOLS,
  208. max_iterations=4,
  209. slots=build_node_slots(
  210. user_input=state.user_input,
  211. full_state=self.service.get_full_state(run_id),
  212. round_index=state.round_index,
  213. plan=state.plan,
  214. ),
  215. )
  216. state.node_runs.append(report)
  217. final_output = report.content or final_output
  218. except Exception as exc:
  219. state.failures.append({"round": state.round_index, "node": "report", "error": str(exc)})
  220. outcome = str(final_run.get("outcome_status") or "failed")
  221. return FindAgentResult(
  222. run_id=run_id,
  223. status=outcome if outcome in {"goal_met", "partial", "no_match", "failed"} else "failed", # type: ignore[arg-type]
  224. succeeded=not failed and final_run.get("status") == "finished",
  225. business_outcome=outcome,
  226. valid_primary_count=int(final_run.get("valid_primary_count") or 0),
  227. rounds=state.round_index,
  228. final_output=final_output,
  229. node_runs=tuple(state.node_runs),
  230. stop_reason=end_reason,
  231. )
  232. def create_find_agent_v2(
  233. settings: Settings | None = None,
  234. *,
  235. model: str | None = None,
  236. planning_model: str | None = None,
  237. search_model: str | None = None,
  238. evidence_model: str | None = None,
  239. evaluation_model: str | None = None,
  240. report_model: str | None = None,
  241. max_rounds: int = 2,
  242. max_actions_per_round: int = 16,
  243. max_search_actions_per_round: int = 3,
  244. ) -> FindAgentV2:
  245. return FindAgentV2(
  246. settings=settings,
  247. models_by_role=normalize_models(
  248. model=model,
  249. planning=planning_model,
  250. search=search_model,
  251. evidence=evidence_model,
  252. evaluation=evaluation_model,
  253. report=report_model,
  254. ),
  255. max_rounds=max_rounds,
  256. max_actions_per_round=max_actions_per_round,
  257. max_search_actions_per_round=max_search_actions_per_round,
  258. )