Coverage for mt_ai/sb_agents.py: 100.00%
64 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
1"""MT AI answered by the sb-agents core instead of the in-app ADK agent (SB-1500).
3`SbAgentsRunner` stands in for `mt_ai.agent.run_turn`: `ChatService` calls it
4the same way and gets the same `TurnOutcome`, so MT still owns the user, the
5auth and the conversation record (`ai_messages`). sb-agents keeps its own short
6memory keyed by conversation_id, so no history is sent.
8 POST {url}/v1/chat Authorization: Bearer {token}
9 {"conversation_id", "user_id", "text"}
10 → {"text", "outcome", "escalation", "routed_to", "tables"}
12Any failure to get an answer — network, non-200, a body that is not the
13contract — is an `AIRunError`, so the turn is saved as ai_failed and the
14client gets the usual 502.
16The backend has no OpenTelemetry tracer configured, so no trace context is
17propagated to sb-agents yet.
18"""
20from collections.abc import Callable
21from dataclasses import dataclass, field
22from typing import Any
24import httpx
25import structlog
26from pydantic import BaseModel, ValidationError, model_validator
28from mt_ai.agent import AIRunError, HistoryTurn, McpAccess, TurnOutcome
29from mt_ai.budget import Budget
30from mt_ai.tools import ToolDeps, Viewer
32logger = structlog.get_logger()
34# What the assistant row's `model` records for a turn sb-agents answered.
35SB_AGENTS_MODEL = "sb-agents"
36TIMEOUT_S = 90.0
39class ChatTable(BaseModel):
40 """One table sb-agents attached to an answer. An extra: the text stands alone."""
42 title: str
43 columns: list[str]
44 rows: list[list[str]]
45 notes: list[str] = []
46 highlight: list[int] = []
48 @model_validator(mode="after")
49 def rectangular(self) -> "ChatTable":
50 if not self.columns or any(len(row) != len(self.columns) for row in self.rows):
51 raise ValueError("every row needs one cell per column")
52 self.highlight = [i for i in self.highlight if 0 <= i < len(self.rows)]
53 return self
56def clean_tables(raw: Any) -> tuple[dict[str, Any], ...]:
57 """The well-formed tables; a malformed one is dropped, never fails the turn."""
58 if not isinstance(raw, list):
59 return ()
60 tables = []
61 for item in raw:
62 try:
63 tables.append(ChatTable.model_validate(item).model_dump())
64 except ValidationError:
65 logger.warning("mt_ai sb-agents table dropped")
66 return tuple(tables)
69@dataclass(frozen=True)
70class SbAgentsRunner:
71 url: str
72 token: str = field(repr=False)
73 timeout_s: float = TIMEOUT_S
74 transport: httpx.AsyncBaseTransport | None = None # tests inject httpx.MockTransport
75 # Mints the user's 5-minute delegated mt-mcp token (SB-1529); None sends no identity.
76 mint: Callable[[str], str] | None = field(default=None, repr=False)
78 async def __call__(
79 self,
80 model: Any,
81 deps: ToolDeps,
82 viewer: Viewer,
83 history: list[HistoryTurn],
84 message: str,
85 budget: Budget,
86 session_id: str,
87 mcp: McpAccess | None = None,
88 user_id: str | None = None,
89 ) -> TurnOutcome:
90 body = {"conversation_id": session_id, "user_id": user_id, "text": message}
91 if user_id and self.mint is not None:
92 body["user_token"] = self.mint(user_id) # never logged
93 headers = {"Authorization": f"Bearer {self.token}"}
94 try:
95 async with httpx.AsyncClient(timeout=self.timeout_s, transport=self.transport) as client:
96 response = await client.post(f"{self.url.rstrip('/')}/v1/chat", json=body, headers=headers)
97 except httpx.HTTPError as exc:
98 logger.warning("mt_ai sb-agents unreachable", session_id=session_id, error=type(exc).__name__)
99 raise AIRunError(f"sb-agents unreachable: {type(exc).__name__}") from exc
100 if response.status_code != 200:
101 logger.warning("mt_ai sb-agents refused", session_id=session_id, status=response.status_code)
102 raise AIRunError(f"sb-agents answered {response.status_code}")
103 try:
104 data = response.json()
105 except ValueError as exc:
106 raise AIRunError("sb-agents answered with a body that is not JSON") from exc
107 text = data.get("text") if isinstance(data, dict) else None
108 if not isinstance(text, str) or not text.strip():
109 raise AIRunError("sb-agents returned no text")
111 outcome, escalation, routed_to = data.get("outcome"), data.get("escalation"), data.get("routed_to")
112 return TurnOutcome(
113 "ok",
114 text.strip(),
115 llm_calls=0, # unknown: sb-agents does not report them
116 tool_calls=0,
117 outcome=outcome if isinstance(outcome, str) else None,
118 escalation=escalation if isinstance(escalation, str) else None,
119 routed_to=tuple(r for r in routed_to if isinstance(r, str)) if isinstance(routed_to, list) else (),
120 tables=clean_tables(data.get("tables")),
121 )