File size: 5,013 Bytes
1ffd0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""
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),
        )