Coverage for mt_ai/api.py: 94.44%

112 statements  

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

1"""MT AI's HTTP boundary: POST /api/ai/chat (SB-1143) and the conversation 

2reads GET /api/ai/conversations[/{id}] (SB-1197). 

3 

4The route validates, authenticates and translates `ChatError`s into status 

5codes. Everything else is in `mt_ai.service` (conversations) and 

6`mt_ai.agent` (ADK). 

7 

8MT AI is off unless MT_AI_ENABLED=true and the chosen backend is configured. 

9MT_AI_BACKEND picks who answers (SB-1500); MT owns the user, the auth and the 

10conversation record either way: 

11 in-app (default) the ADK agent in mt_ai.agent; needs 

12 MT_AI_MODEL=<model id> (Gemini ids need GOOGLE_API_KEY; 

13 ollama_chat/<model> runs a local Ollama model — mt_ai/models.py) 

14 sb-agents the sb-agents core over HTTP (mt_ai.sb_agents); needs 

15 MT_AI_SB_AGENTS_URL and MT_AI_SB_AGENTS_TOKEN, not MT_AI_MODEL 

16Rollback from sb-agents is MT_AI_BACKEND=in-app. No model id is hardcoded: 

17which model runs is configuration (mt2/ai.md). 

18 

19GET /api/ai/status tells a logged-in client whether chat is on, and which 

20backend answers, so the UI can hide the entry when it is off. 

21""" 

22 

23import hashlib 

24import os 

25import uuid 

26from typing import Any, Literal 

27 

28import structlog 

29from fastapi import APIRouter, Depends, HTTPException, Query, status 

30from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 

31from pydantic import BaseModel, Field, field_validator 

32 

33from auth import get_ai_user 

34from dao.ai_conversation_dao import AIConversationDAO 

35from dao.match_dao import SupabaseConnection 

36from mt_ai.models import ModelUnavailableError, resolve_model 

37from mt_ai.sb_agents import SB_AGENTS_MODEL, ChatTable, SbAgentsRunner 

38from mt_ai.service import MAX_PAGE, ChatError, ChatService, ConversationReader 

39from mt_ai.tools.deps import dao_tool_deps 

40from mt_mcp import config as mcp_config 

41 

42logger = structlog.get_logger() 

43 

44router = APIRouter(prefix="/api/ai", tags=["mt-ai"]) 

45 

46# The raw token, to forward to mt-mcp. get_ai_user has already authenticated it; 

47# this only reads it, so it never answers 401/403 itself. 

48_bearer = HTTPBearer(auto_error=False) 

49 

50MAX_MESSAGE_LENGTH = 2000 

51 

52Backend = Literal["in-app", "sb-agents"] 

53BACKENDS: tuple[Backend, ...] = ("in-app", "sb-agents") 

54REQUIRED_ENV: dict[Backend, tuple[str, ...]] = { 

55 "in-app": ("MT_AI_MODEL",), 

56 "sb-agents": ("MT_AI_SB_AGENTS_URL", "MT_AI_SB_AGENTS_TOKEN"), 

57} 

58 

59 

60class ChatRequest(BaseModel): 

61 message: str = Field(min_length=1, max_length=MAX_MESSAGE_LENGTH) 

62 conversation_id: uuid.UUID | None = None 

63 

64 @field_validator("message") 

65 @classmethod 

66 def not_blank(cls, value: str) -> str: 

67 if not value.strip(): 

68 raise ValueError("message must not be blank") 

69 return value.strip() 

70 

71 

72class ChatResponse(BaseModel): 

73 conversation_id: str 

74 turn: int 

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

76 answer: str | None 

77 message: str | None = None 

78 # Set only when sb-agents answered (SB-1500); in-app answers keep these defaults. 

79 outcome: str | None = None 

80 escalation: str | None = None 

81 routed_to: list[str] = [] 

82 tables: list[ChatTable] = [] 

83 

84 

85class AIStatusResponse(BaseModel): 

86 enabled: bool 

87 backend: Backend | None 

88 # Whether the web app shows its chat screen (SB-1500). Separate from `enabled`: 

89 # prod already answers /api/ai/chat for API clients, and the web screen is a launch 

90 # of its own (minors' data review first). Off unless MT_AI_WEB_CHAT=true. 

91 web_chat: bool = False 

92 

93 

94def web_chat_enabled() -> bool: 

95 return os.getenv("MT_AI_WEB_CHAT", "false").lower() == "true" 

96 

97 

98def mint_delegated_token(user_id: str) -> str: 

99 """The user's 5-minute mt-mcp token for one sb-agents turn (SB-1529).""" 

100 from app import auth_manager # same late import as auth.get_ai_user 

101 

102 return auth_manager.create_delegated_token(user_id) 

103 

104 

105def configured_backend() -> Backend | None: 

106 """The backend that answers chat, or None when MT AI is off or not configured. 

107 Logs which variable is missing — by name only, never a value.""" 

108 if os.getenv("MT_AI_ENABLED", "false").lower() != "true": 

109 return None 

110 backend = os.getenv("MT_AI_BACKEND") or "in-app" 

111 if backend not in BACKENDS: 

112 logger.warning("mt_ai unknown backend", backend=backend) 

113 return None 

114 missing = [name for name in REQUIRED_ENV[backend] if not os.getenv(name)] 

115 if missing: 

116 logger.warning("mt_ai not configured", backend=backend, missing=missing) 

117 return None 

118 return backend 

119 

120 

121_service: ChatService | None = None 

122_service_key: tuple[str | None, ...] | None = None 

123 

124 

125def get_chat_service() -> ChatService: 

126 global _service, _service_key 

127 backend = configured_backend() 

128 if backend is None: 

129 raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="MT AI is not enabled.") 

130 if backend == "sb-agents": 

131 url, token = os.environ["MT_AI_SB_AGENTS_URL"], os.environ["MT_AI_SB_AGENTS_TOKEN"] 

132 # A rotated token rebuilds the service; the key holds a digest, never the token. 

133 key = (backend, url, hashlib.sha256(token.encode()).hexdigest()) 

134 if _service is None or _service_key != key: 

135 _service = ChatService( 

136 AIConversationDAO(SupabaseConnection()), 

137 dao_tool_deps(), 

138 SB_AGENTS_MODEL, 

139 run=SbAgentsRunner(url, token, mint=mint_delegated_token), 

140 pass_user_id=True, 

141 ) 

142 _service_key = key 

143 return _service 

144 model_id = os.environ["MT_AI_MODEL"] 

145 mcp_url = mcp_config.internal_url() if mcp_config.mcp_enabled() else None 

146 if _service is None or _service_key != (backend, model_id, mcp_url): 146 ↛ 156line 146 didn't jump to line 156 because the condition on line 146 was always true

147 try: 

148 model = resolve_model(model_id) 

149 except ModelUnavailableError: 

150 logger.exception("mt_ai model unavailable", model=model_id) 

151 raise HTTPException( 

152 status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="MT AI is not enabled." 

153 ) from None 

154 _service = ChatService(AIConversationDAO(SupabaseConnection()), dao_tool_deps(), model, mcp_url=mcp_url) 

155 _service_key = (backend, model_id, mcp_url) 

156 return _service 

157 

158 

159@router.post("/chat", response_model=ChatResponse) 

160async def chat( 

161 payload: ChatRequest, 

162 current_user: dict[str, Any] = Depends(get_ai_user), 

163 credentials: HTTPAuthorizationCredentials | None = Depends(_bearer), 

164 service: ChatService = Depends(get_chat_service), 

165) -> ChatResponse: 

166 conversation_id = str(payload.conversation_id) if payload.conversation_id else None 

167 try: 

168 # The caller's own token goes to mt-mcp, so its tools run as the caller. 

169 result = await service.chat( 

170 current_user, payload.message, conversation_id, bearer=credentials.credentials if credentials else None 

171 ) 

172 except ChatError as exc: 

173 raise HTTPException(status_code=exc.status_code, detail=exc.detail) from None 

174 return ChatResponse( 

175 conversation_id=result.conversation_id, 

176 turn=result.turn, 

177 status=result.status, 

178 answer=result.answer, 

179 message=result.message, 

180 outcome=result.outcome, 

181 escalation=result.escalation, 

182 routed_to=list(result.routed_to), 

183 tables=[ChatTable(**table) for table in result.tables], 

184 ) 

185 

186 

187@router.get("/status", response_model=AIStatusResponse) 

188def ai_status(current_user: dict[str, Any] = Depends(get_ai_user)) -> AIStatusResponse: 

189 """Whether chat is on, and who answers. Never 503: off is `enabled: false`.""" 

190 backend = configured_backend() 

191 return AIStatusResponse( 

192 enabled=backend is not None, backend=backend, web_chat=backend is not None and web_chat_enabled() 

193 ) 

194 

195 

196def get_conversation_reader() -> ConversationReader: 

197 """Reading works whether or not MT AI is enabled: past conversations stay readable.""" 

198 return ConversationReader(AIConversationDAO(SupabaseConnection())) 

199 

200 

201@router.get("/conversations") 

202def list_conversations( 

203 scope: Literal["mine", "all"] = "mine", 

204 limit: int = Query(20, ge=1, le=MAX_PAGE), 

205 offset: int = Query(0, ge=0), 

206 current_user: dict[str, Any] = Depends(get_ai_user), 

207 reader: ConversationReader = Depends(get_conversation_reader), 

208) -> dict[str, Any]: 

209 """Your conversations, newest activity first, each with its first question. 

210 `scope=all` (admins only) lists everyone's, with the owner's user_id.""" 

211 try: 

212 return reader.list_for(current_user, scope, limit, offset) 

213 except ChatError as exc: 

214 raise HTTPException(status_code=exc.status_code, detail=exc.detail) from None 

215 

216 

217@router.get("/conversations/{conversation_id}") 

218def get_conversation( 

219 conversation_id: uuid.UUID, 

220 current_user: dict[str, Any] = Depends(get_ai_user), 

221 reader: ConversationReader = Depends(get_conversation_reader), 

222) -> dict[str, Any]: 

223 """One conversation's turns. Someone else's is a 404. Admins may read any, and 

224 also get each turn's model, call counts, timings and tool-call trace.""" 

225 try: 

226 return reader.get_for(current_user, str(conversation_id)) 

227 except ChatError as exc: 

228 raise HTTPException(status_code=exc.status_code, detail=exc.detail) from None