completion_guard.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """find_agent 基于持久化运行状态的结束守卫。"""
  2. from __future__ import annotations
  3. from collections.abc import Sequence
  4. from typing import TYPE_CHECKING
  5. from supply_agent.types import CompletionGuard, Message
  6. from supply_infra.services.video_discovery_service import (
  7. get_video_discovery_service,
  8. )
  9. if TYPE_CHECKING:
  10. from supply_agent.agent.core import Agent
  11. _TERMINAL_STATUSES = {"finished", "failed"}
  12. def create_find_completion_guard(run_id: str) -> CompletionGuard:
  13. """创建只允许已进入 finished / failed 终态的 find_agent 结束守卫。"""
  14. normalized_run_id = str(run_id or "").strip()[:64]
  15. def guard(_response: Message, _messages: Sequence[Message]) -> str | None:
  16. if not normalized_run_id:
  17. return (
  18. "当前用户消息中缺少 run_id,无法确认运行状态。"
  19. "请不要直接输出最终结果。"
  20. )
  21. run = get_video_discovery_service().lookup_run(normalized_run_id)
  22. if run is None:
  23. return (
  24. f"run_id={normalized_run_id} 不存在,无法确认运行状态。"
  25. "请不要直接输出最终结果。"
  26. )
  27. status = str(run.get("status") or "").strip()
  28. if status in _TERMINAL_STATUSES:
  29. return None
  30. return (
  31. f"当前 run.status 仍为 {status or 'unknown'}。"
  32. "请继续处理;正常完成后先调用 "
  33. "update_video_discovery_run_status 将状态更新为 finished,"
  34. "无法完成时将状态更新为 failed,再输出最终结果。"
  35. )
  36. return guard
  37. def configure_find_agent_completion_guard(agent: Agent, run_id: str) -> None:
  38. """在 find_agent 循环创建前按需注入状态结束守卫。"""
  39. if getattr(agent, "completion_guard", None) is not None:
  40. return
  41. agent.completion_guard = create_find_completion_guard(run_id)
  42. __all__ = [
  43. "configure_find_agent_completion_guard",
  44. "create_find_completion_guard",
  45. ]