turn_scripted_prelude.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Scripted prelude: tool calls a prompt built-in plays before the turn's first model call.
  2. A prelude is a generator owned by the caller that starts the turn (the desktop onboarding opening is the
  3. intended one). Each step it yields ``(content, tool_name, args)``: the assistant text and the one
  4. tool call that row carries. The loop runs it through the unchanged ``run_tool_round`` (row persisted
  5. before the tool runs, interim text and tool events emitted, tool hooks fired) and sends the tool's
  6. result string back into the generator, so a later step can use an earlier answer.
  7. It runs before any provider call, so the rows sit between this turn's user message and the first
  8. model call: nothing cached is mutated, the system prompt is untouched, no user row is added, and
  9. roles alternate ``user -> assistant(tool_calls) -> tool -> ... -> assistant(model)``. No API call is
  10. counted and no ``pre/post_api_request`` hook fires for a step.
  11. """
  12. from __future__ import annotations
  13. import json
  14. from typing import Any, Generator, Optional, Tuple
  15. from agent.message_sanitization import deterministic_call_id
  16. from agent.transports.types import NormalizedResponse, build_tool_call
  17. from agent.turn_tool_round import run_tool_round
  18. Prelude = Generator[tuple[str, str, dict], Optional[str], None]
  19. def prelude_call_id(session_id: str, name: str, args: dict, index: int) -> str:
  20. """Seeded by the session, the call and its place in history: no two chats share an id (a rerun plays
  21. the same card at the same place), and it stays byte-stable on replay."""
  22. return deterministic_call_id(name, f"{session_id}:{json.dumps(args, sort_keys=True)}", index)
  23. def run_scripted_prelude(agent: Any, s: Any, prelude: Prelude) -> Any:
  24. """Play ``prelude`` into the loop state ``s``; returns the last tool round's verdict, or None when
  25. no step ran. The caller ends the turn on ``return`` and skips the model on ``break``."""
  26. from agent.conversation_loop import _run_phase
  27. verdict, result = None, None
  28. while not agent._interrupt_requested:
  29. try:
  30. content, name, args = prelude.send(result)
  31. except StopIteration:
  32. break
  33. s.finish_reason = "tool_calls"
  34. s.assistant_message = NormalizedResponse(
  35. content=content, finish_reason="tool_calls",
  36. tool_calls=[build_tool_call(prelude_call_id(agent.session_id, name, args, len(s.messages)), name, args)])
  37. verdict = _run_phase(run_tool_round, agent, s)
  38. if verdict.action != "continue":
  39. break
  40. tail = s.messages[-1] if s.messages else {}
  41. result = tail.get("content") if tail.get("role") == "tool" else None
  42. prelude.close()
  43. return verdict
  44. def play_prelude(agent: Any, s: Any, prelude: Optional[Prelude]) -> tuple[str, Any]:
  45. """``("return", result)`` ends the turn now, ``("break", None)`` skips the model call, ``("run", None)`` runs
  46. the loop as usual (also when there is no prelude)."""
  47. verdict = run_scripted_prelude(agent, s, prelude) if prelude is not None else None
  48. if verdict is not None and verdict.action in ("return", "break"):
  49. return verdict.action, verdict.result
  50. return "run", None