""" Base agent runner — the single entry point every CIRO agent runs through. Why this is the only way to run an agent ---------------------------------------- Letting each phase call `Runner.run(...)` directly would mean each phase re-implements its own error boundary, its own trace logging, its own JSON parsing, and its own AgentResult assembly. By funneling everything through `run_agent()`: • every step in the pipeline yields a uniformly-shaped `AgentResult`, • exceptions never escape into FastAPI route handlers (they collapse into `success=False` results instead), • the agent-trace timeline in the UI gets consistent data without special-casing per stage. The runner itself is intentionally stateless — all context is passed explicitly so the same function can serve the synchronous pipeline, streaming endpoints, and tests. """ from __future__ import annotations from datetime import datetime, timezone from typing import Any from agents import Agent, Runner from pydantic import BaseModel, ValidationError from backend.models.agent_result import AgentResult def _coerce_output( final_output: Any, fallback_reasoning: str, ) -> tuple[dict[str, Any], str, float]: """Normalize whatever the agent returned into (output, reasoning, confidence). Agents may return: * a Pydantic model (when `output_type=...` is configured) — preferred, * a dict (loose structured output), * a plain string (e.g. the dummy/test agent). We always end up with a dict for `output`, leaving `reasoning` either as the model-provided field or the fallback text the runner generated. """ if isinstance(final_output, BaseModel): data = final_output.model_dump() reasoning = str(data.get("reasoning") or fallback_reasoning) confidence = float(data.get("confidence") or 0.0) return data, reasoning, confidence if isinstance(final_output, dict): reasoning = str(final_output.get("reasoning") or fallback_reasoning) confidence = float(final_output.get("confidence") or 0.0) return final_output, reasoning, confidence # Plain string / other — wrap so AgentResult.output stays a dict. return {"text": str(final_output)}, fallback_reasoning, 0.0 async def run_agent( agent: Agent[Any], input: str | list[dict[str, Any]], *, context: Any = None, max_turns: int = 10, ) -> AgentResult: """Run a single agent and return its result in canonical `AgentResult` form. This is the function every pipeline stage calls. It never raises — any exception from the SDK collapses into `AgentResult(success=False, ...)` so the orchestrator can decide whether to continue or short-circuit. Args: agent: A configured `agents.Agent` (model, instructions, tools, optional `output_type` for structured outputs). input: Either a string prompt or a list of `{"role", "content"}` message dicts for multi-turn input. context: Optional user-defined context object that tools receive through `RunContextWrapper`. The runner does not inspect it. max_turns: Safety cap on tool-call → model round-trips. 10 is fine for every current CIRO agent. Returns: An `AgentResult` describing what the agent did. On failure, `success=False` and `reasoning` carries the exception message. """ started_at = datetime.now(timezone.utc) try: run_result = await Runner.run( agent, input, context=context, max_turns=max_turns, ) except Exception as exc: # noqa: BLE001 — boundary; collapse all failures. return AgentResult( agent_name=agent.name, success=False, output={"error": exc.__class__.__name__}, reasoning=f"Agent run failed: {exc}", confidence=0.0, timestamp=started_at, ) fallback_reasoning = ( f"{agent.name} produced output without an explicit reasoning field." ) output, reasoning, confidence = _coerce_output( run_result.final_output, fallback_reasoning=fallback_reasoning, ) try: return AgentResult( agent_name=agent.name, success=True, output=output, reasoning=reasoning, confidence=confidence, timestamp=datetime.now(timezone.utc), ) except ValidationError as exc: # The agent returned something that violates the AgentResult shape # (e.g. confidence > 1). Treat as a soft failure rather than 500-ing. return AgentResult( agent_name=agent.name, success=False, output={"error": "INVALID_AGENT_OUTPUT", "raw": output}, reasoning=f"Output failed AgentResult validation: {exc}", confidence=0.0, timestamp=datetime.now(timezone.utc), )