Coverage for mt_ai/service.py: 96.25%

192 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 15:10 +0000

1"""Conversation lifecycle for /api/ai/chat (SB-1143). 

2 

3 request → load or create conversation → rebuild history → run one turn 

4 → persist the turn (always, even when it failed) → result 

5 

6The service knows about conversations and outcomes, not about HTTP or ADK: 

7the route turns `ChatError`s into status codes, and `mt_ai.agent` hides ADK. 

8 

9After a turn is saved, its trace (tool calls, timings) is saved best-effort 

10(SB-1197). `ConversationReader` serves the conversation endpoints: a user 

11sees their own questions and answers; an admin also sees traces, timings and 

12the model, which client responses otherwise never name. 

13""" 

14 

15import time 

16from collections.abc import Awaitable, Callable 

17from dataclasses import asdict, dataclass 

18from typing import Any, Literal, Protocol 

19 

20import structlog 

21 

22from mt_ai.agent import AGENT_VERSION, AIRunError, HistoryTurn, McpAccess, TurnOutcome, model_name, run_turn 

23from mt_ai.budget import Budget 

24from mt_ai.tools import ToolDeps, Viewer 

25from mt_ai.trace import ToolCallRecord 

26 

27logger = structlog.get_logger() 

28 

29BUDGET_MESSAGE = "I couldn't finish that within my limits. Try asking about one team at a time." 

30 

31 

32class ConversationStore(Protocol): 

33 def create_conversation(self, user_id: str, agent_version: str) -> dict: ... 33 ↛ exitline 33 didn't return from function 'create_conversation' because

34 

35 def get_conversation(self, conversation_id: str, user_id: str) -> dict | None: ... 35 ↛ exitline 35 didn't return from function 'get_conversation' because

36 

37 def list_messages(self, conversation_id: str) -> list[dict]: ... 37 ↛ exitline 37 didn't return from function 'list_messages' because

38 

39 def add_turn( 39 ↛ exitline 39 didn't return from function 'add_turn' because

40 self, conversation_id: str, turn: int, user_row: dict[str, Any], assistant_row: dict[str, Any] 

41 ) -> None: ... 

42 

43 def record_trace( 43 ↛ exitline 43 didn't return from function 'record_trace' because

44 self, conversation_id: str, turn: int, timings: dict[str, int | None], calls: list[dict[str, Any]] 

45 ) -> None: ... 

46 

47 

48class ChatError(Exception): 

49 """An expected failure, with the status code and client-safe message to return.""" 

50 

51 status_code = 500 

52 detail = "MT AI could not answer that." 

53 

54 def __init__(self, detail: str | None = None) -> None: 

55 super().__init__(detail or self.detail) 

56 if detail: 56 ↛ 57line 56 didn't jump to line 57 because the condition on line 56 was never true

57 self.detail = detail 

58 

59 

60class NotAllowedToChatError(ChatError): 

61 status_code = 403 

62 detail = "This account cannot use MT AI." 

63 

64 

65class ConversationNotFoundError(ChatError): 

66 status_code = 404 

67 detail = "Conversation not found." 

68 

69 

70class AIFailedError(ChatError): 

71 status_code = 502 

72 detail = "MT AI could not answer right now. Please try again." 

73 

74 

75class PersistenceFailedError(ChatError): 

76 status_code = 503 

77 detail = "MT AI could not save this conversation right now. Please try again." 

78 

79 

80class AdminOnlyError(ChatError): 

81 status_code = 403 

82 detail = "Admin access required." 

83 

84 

85class ReadFailedError(ChatError): 

86 status_code = 503 

87 detail = "MT AI conversations are unavailable right now. Please try again." 

88 

89 

90@dataclass(frozen=True) 

91class ChatResult: 

92 conversation_id: str 

93 turn: int 

94 status: Literal["ok", "budget_exhausted"] 

95 answer: str | None 

96 message: str | None = None # why there is no answer, when status is not ok 

97 # What the sb-agents backend adds to an answer (SB-1500); empty for the in-app agent. 

98 outcome: str | None = None 

99 escalation: str | None = None 

100 routed_to: tuple[str, ...] = () 

101 tables: tuple[dict[str, Any], ...] = () 

102 

103 

104RunTurn = Callable[..., Awaitable[TurnOutcome]] 

105 

106 

107class ChatService: 

108 def __init__( 

109 self, 

110 store: ConversationStore, 

111 deps: ToolDeps, 

112 model: Any, 

113 budget: Budget | None = None, 

114 run: RunTurn = run_turn, 

115 mcp_url: str | None = None, 

116 pass_user_id: bool = False, 

117 ) -> None: 

118 self.store, self.deps, self.model = store, deps, model 

119 self.budget = budget or Budget() 

120 self.run = run 

121 # Where mt-mcp is (SB-1302); None keeps every tool in-process. 

122 self.mcp_url = mcp_url 

123 # The sb-agents runner (SB-1500) needs to know who is asking; run_turn does not. 

124 self.pass_user_id = pass_user_id 

125 

126 async def chat( 

127 self, user: dict[str, Any], message: str, conversation_id: str | None, bearer: str | None = None 

128 ) -> ChatResult: 

129 if not user.get("user_id"): 

130 # A conversation needs a user_profiles owner; a service account has none. 

131 raise NotAllowedToChatError() 

132 user_id = str(user["user_id"]) 

133 conversation_id, history, turn = self._open(user_id, conversation_id) 

134 

135 # Tools reached over MCP run as the caller, with the caller's own token. 

136 extra: dict[str, Any] = {} 

137 if self.mcp_url and bearer: 

138 extra["mcp"] = McpAccess(url=self.mcp_url, bearer=bearer) 

139 if self.pass_user_id: 

140 extra["user_id"] = user_id 

141 

142 started = time.monotonic() 

143 try: 

144 outcome = await self.run( 

145 self.model, 

146 self.deps, 

147 Viewer.from_user(user), 

148 history, 

149 message, 

150 self.budget, 

151 session_id=conversation_id, 

152 **extra, 

153 ) 

154 except AIRunError as exc: 

155 try: 

156 self._save(conversation_id, turn, message, status="ai_failed") 

157 self._save_trace(conversation_id, turn, _ms_since(started), exc.trace, exc.llm_ms) 

158 except PersistenceFailedError: 

159 pass # already logged; the AI failure is what the client needs to hear 

160 raise AIFailedError() from None 

161 

162 self._save(conversation_id, turn, message, status=outcome.status, outcome=outcome) 

163 self._save_trace(conversation_id, turn, _ms_since(started), outcome.trace, outcome.llm_ms) 

164 if outcome.status == "budget_exhausted": 

165 logger.info("mt_ai budget exhausted", conversation_id=conversation_id, limit=outcome.exhausted) 

166 return ChatResult(conversation_id, turn, "budget_exhausted", None, BUDGET_MESSAGE) 

167 return ChatResult( 

168 conversation_id, 

169 turn, 

170 "ok", 

171 outcome.answer, 

172 outcome=outcome.outcome, 

173 escalation=outcome.escalation, 

174 routed_to=outcome.routed_to, 

175 tables=outcome.tables, 

176 ) 

177 

178 def _open(self, user_id: str, conversation_id: str | None) -> tuple[str, list[HistoryTurn], int]: 

179 try: 

180 if conversation_id is None: 

181 created = self.store.create_conversation(user_id, AGENT_VERSION) 

182 return str(created["id"]), [], 1 

183 if self.store.get_conversation(conversation_id, user_id) is None: 

184 # Someone else's conversation is indistinguishable from a missing one. 

185 raise ConversationNotFoundError() 

186 rows = self.store.list_messages(conversation_id) 

187 except ChatError: 

188 raise 

189 except Exception: 

190 logger.exception("mt_ai conversation load failed", conversation_id=conversation_id) 

191 raise PersistenceFailedError() from None 

192 return conversation_id, rebuild_history(rows), max((r["turn"] for r in rows), default=0) + 1 

193 

194 def _save( 

195 self, conversation_id: str, turn: int, message: str, status: str, outcome: TurnOutcome | None = None 

196 ) -> None: 

197 assistant = { 

198 "content": outcome.answer if outcome else None, 

199 "status": status, 

200 "model": model_name(self.model), 

201 "agent_version": AGENT_VERSION, 

202 "llm_calls": outcome.llm_calls if outcome else None, 

203 "tool_calls": outcome.tool_calls if outcome else None, 

204 } 

205 try: 

206 self.store.add_turn(conversation_id, turn, {"content": message}, assistant) 

207 except Exception: 

208 logger.exception("mt_ai turn save failed", conversation_id=conversation_id, turn=turn) 

209 raise PersistenceFailedError() from None 

210 

211 def _save_trace( 

212 self, 

213 conversation_id: str, 

214 turn: int, 

215 duration_ms: int, 

216 trace: tuple[ToolCallRecord, ...], 

217 llm_ms: int | None, 

218 ) -> None: 

219 """Best-effort: the turn is already saved, and a trace must never fail it.""" 

220 try: 

221 self.store.record_trace( 

222 conversation_id, 

223 turn, 

224 {"duration_ms": duration_ms, "llm_ms": llm_ms}, 

225 [asdict(call) for call in trace], 

226 ) 

227 except Exception: 

228 logger.warning("mt_ai trace save failed", conversation_id=conversation_id, turn=turn, exc_info=True) 

229 

230 

231def _ms_since(started: float) -> int: 

232 return round((time.monotonic() - started) * 1000) 

233 

234 

235def rebuild_history(rows: list[dict]) -> list[HistoryTurn]: 

236 """Completed turns only: a turn whose answer failed is left out of what the model sees.""" 

237 by_turn: dict[int, dict[str, dict]] = {} 

238 for row in rows: 

239 by_turn.setdefault(row["turn"], {})[row["role"]] = row 

240 history = [] 

241 for turn in sorted(by_turn): 

242 user, assistant = by_turn[turn].get("user"), by_turn[turn].get("assistant") 

243 if user and assistant and assistant.get("status") == "ok" and assistant.get("content"): 

244 history.append(HistoryTurn(user=user["content"], assistant=assistant["content"])) 

245 return history 

246 

247 

248# --- Reading conversations (SB-1197) ------------------------------------------- 

249 

250MAX_PAGE = 100 

251 

252 

253class ConversationReader: 

254 """GET /api/ai/conversations and /api/ai/conversations/{id}. 

255 

256 Ownership is enforced here, not trusted to the client: a user reads only 

257 their own conversations, and someone else's is a 404, like a missing one. 

258 Admins may read any and see the trace. 

259 """ 

260 

261 def __init__(self, store: Any) -> None: 

262 self.store = store 

263 

264 def list_for(self, user: dict[str, Any], scope: Literal["mine", "all"], limit: int, offset: int) -> dict[str, Any]: 

265 admin = _is_admin(user) 

266 if scope == "all" and not admin: 

267 raise AdminOnlyError() 

268 owner = None if scope == "all" else _owner(user) 

269 try: 

270 rows = self.store.list_conversations(owner, limit, offset) 

271 except Exception: 

272 logger.exception("mt_ai conversation list failed") 

273 raise ReadFailedError() from None 

274 keys = ("id", "created_at", "updated_at", "agent_version", "first_question") 

275 if scope == "all": 

276 keys = (*keys, "user_id") 

277 return { 

278 "conversations": [{k: row.get(k) for k in keys} for row in rows], 

279 "limit": limit, 

280 "offset": offset, 

281 } 

282 

283 def get_for(self, user: dict[str, Any], conversation_id: str) -> dict[str, Any]: 

284 admin = _is_admin(user) 

285 try: 

286 conversation = self.store.get_conversation(conversation_id, None if admin else _owner(user)) 

287 except Exception: 

288 logger.exception("mt_ai conversation read failed", conversation_id=conversation_id) 

289 raise ReadFailedError() from None 

290 if conversation is None: 

291 raise ConversationNotFoundError() 

292 

293 rows, timings_recorded = self._messages(conversation_id, admin) 

294 body: dict[str, Any] = { 

295 "id": conversation["id"], 

296 "created_at": conversation.get("created_at"), 

297 "updated_at": conversation.get("updated_at"), 

298 "agent_version": conversation.get("agent_version"), 

299 "turns": _turns(rows, admin), 

300 } 

301 if admin: 

302 body["user_id"] = conversation.get("user_id") 

303 body["timings_recorded"] = timings_recorded 

304 _attach_traces(body["turns"], self._tool_calls(conversation_id)) 

305 return body 

306 

307 def _messages(self, conversation_id: str, admin: bool) -> tuple[list[dict], bool]: 

308 """Rows, and whether SB-1197's timing columns could be read.""" 

309 try: 

310 if admin: 

311 try: 

312 return self.store.list_messages_detail(conversation_id), True 

313 except Exception: 

314 logger.warning("mt_ai message detail unavailable", conversation_id=conversation_id, exc_info=True) 

315 return self.store.list_messages(conversation_id), False 

316 except Exception: 

317 logger.exception("mt_ai conversation read failed", conversation_id=conversation_id) 

318 raise ReadFailedError() from None 

319 

320 def _tool_calls(self, conversation_id: str) -> list[dict] | None: 

321 """The trace rows, or None when they couldn't be read (absent, not empty).""" 

322 try: 

323 return self.store.list_tool_calls(conversation_id) 

324 except Exception: 

325 logger.warning("mt_ai tool calls unavailable", conversation_id=conversation_id, exc_info=True) 

326 return None 

327 

328 

329ADMIN_TURN_FIELDS = ("model", "agent_version", "llm_calls", "tool_calls", "duration_ms", "llm_ms") 

330 

331 

332def _turns(rows: list[dict], admin: bool) -> list[dict[str, Any]]: 

333 """One entry per turn: the question, and the answer or why there is none.""" 

334 by_turn: dict[int, dict[str, dict]] = {} 

335 for row in rows: 

336 by_turn.setdefault(row["turn"], {})[row["role"]] = row 

337 turns = [] 

338 for number in sorted(by_turn): 

339 user, assistant = by_turn[number].get("user") or {}, by_turn[number].get("assistant") or {} 

340 entry: dict[str, Any] = { 

341 "turn": number, 

342 "question": user.get("content"), 

343 "answer": assistant.get("content"), 

344 "status": assistant.get("status"), 

345 } 

346 if admin: 

347 entry.update({k: assistant.get(k) for k in ADMIN_TURN_FIELDS}) 

348 turns.append(entry) 

349 return turns 

350 

351 

352def _attach_traces(turns: list[dict[str, Any]], calls: list[dict] | None) -> None: 

353 """Each turn's tool calls, in order. `trace` is None when traces couldn't be 

354 read, and [] when the turn called no tool (or predates SB-1197).""" 

355 for entry in turns: 

356 if calls is None: 

357 entry["trace"] = None 

358 continue 

359 entry["trace"] = [ 

360 {k: c.get(k) for k in ("seq", "tool_name", "args", "result", "error_kind", "duration_ms")} 

361 for c in sorted(calls, key=lambda c: c.get("seq", 0)) 

362 if c.get("turn") == entry["turn"] 

363 ] 

364 

365 

366def _is_admin(user: dict[str, Any]) -> bool: 

367 return user.get("role") == "admin" 

368 

369 

370def _owner(user: dict[str, Any]) -> str: 

371 if not user.get("user_id"): 371 ↛ 372line 371 didn't jump to line 372 because the condition on line 371 was never true

372 raise NotAllowedToChatError() 

373 return str(user["user_id"])