Coverage for app / db / postgres / providers / seeder.py: 80%

125 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Seeder for built-in LLM providers and models. 

3 

4Called once during application startup (lifespan). Uses an upsert 

5pattern (insert-or-update-on-conflict) so re-deploying the service 

6keeps providers and models in sync with the registry without requiring 

7a new migration every time pricing or capability data changes. 

8""" 

9 

10from __future__ import annotations 

11 

12import logging 

13 

14from typing import Any 

15 

16from sqlalchemy.dialects.postgresql import insert 

17from sqlalchemy.orm import Session 

18 

19from app.db.postgres.enums import ModelEnum 

20from app.db.postgres.models import LLMModel, Provider 

21from app.db.postgres.providers.registry import ( 

22 BUILTIN_MODELS, 

23 BUILTIN_PROVIDERS, 

24 WITHDRAWN_MODELS, 

25 ModelSeed, 

26) 

27from app.services import inference_routes 

28from app.util.time import aware_utcnow 

29 

30logger = logging.getLogger(__name__) 

31 

32#: The fields a route decides: what a model costs, where it runs and what it 

33#: can take. On a ``bedrock`` deployment they come from the model's Bedrock 

34#: route; otherwise from the vendor's figures. 

35_ROUTE_PRICE_FIELDS = ( 

36 "input_cost_per_token", 

37 "output_cost_per_token", 

38 "cache_read_cost_per_token", 

39 "cache_write_cost_per_token", 

40 "cache_write_1h_cost_per_token", 

41) 

42 

43 

44def route_values(seed: ModelSeed, backend: str) -> dict[str, Any]: 

45 """The catalogue row's route-dependent values on ``backend``. 

46 

47 On Bedrock, a model with a route takes the route's prices, region, 

48 long-context tier and (where they differ) limits. A model with no route 

49 is unavailable. On the direct backend the vendor's figures stand, and a 

50 Bedrock-only model is unavailable. 

51 """ 

52 values: dict[str, Any] = { 

53 field: seed[field] 

54 for field in ( 

55 *_ROUTE_PRICE_FIELDS, 

56 "long_context_threshold", 

57 "long_context_input_multiplier", 

58 "long_context_output_multiplier", 

59 "data_region", 

60 "context_window", 

61 "max_output_tokens", 

62 ) 

63 } 

64 route = seed.get("bedrock") 

65 if backend != inference_routes.BEDROCK: 

66 values["is_available"] = seed.get("direct", True) 

67 return values 

68 # A route to a vendor this AWS account cannot use (BEDROCK_MODEL_ACCESS) 

69 # is unavailable too, so it is not offered and then refused. 

70 values["is_available"] = route is not None and inference_routes.has_access( 

71 route_vendor(seed) 

72 ) 

73 if route is None: 

74 return values 

75 for field in _ROUTE_PRICE_FIELDS: 

76 values[field] = route[field] 

77 for field in ( 

78 "long_context_threshold", 

79 "long_context_input_multiplier", 

80 "long_context_output_multiplier", 

81 ): 

82 values[field] = route.get(field) 

83 values["data_region"] = route["data_region"] 

84 if route.get("context_window"): 

85 values["context_window"] = route["context_window"] 

86 if route.get("max_output_tokens"): 

87 values["max_output_tokens"] = route["max_output_tokens"] 

88 return values 

89 

90 

91def route_vendor(seed: ModelSeed) -> str: 

92 """Whose model a seed's Bedrock route serves: its provider's, or for a 

93 model registered under ``bedrock`` itself, the vendor its id names.""" 

94 provider = next( 

95 ( 

96 str(p["name"]) 

97 for p in BUILTIN_PROVIDERS.values() 

98 if p["id"] == seed["provider_id"] 

99 ), 

100 "", 

101 ) 

102 route = seed.get("bedrock") 

103 return inference_routes.maker_of( 

104 provider, route["model_id"] if route else seed["model_name"] 

105 ) 

106 

107 

108def seed_builtin_providers_and_models(db: Session) -> None: 

109 """ 

110 Upsert all entries from BUILTIN_PROVIDERS and BUILTIN_MODELS into the DB. 

111 

112 Providers are upserted first (models have a FK to providers). 

113 On conflict the display_name and is_enabled flag are updated so 

114 registry changes are reflected on the next deploy. 

115 

116 Cost (the whole price card: input, output, cache and long-context rates), 

117 capability, token limit, effort/latency band and knowledge-cutoff 

118 fields on models are also updated on conflict, so a provider revising any 

119 of them is picked up on the next deploy without a migration. 

120 

121 ``is_default`` and ``is_recommended`` are written on INSERT only and 

122 deliberately left out of the conflict update: they are the platform's 

123 picks, an operator can change them in the UI, and re-asserting the 

124 registry's answer on every deploy would silently undo that. A migration 

125 moves them when the picks change (see migration 18) — but a migration 

126 runs *before* this seeder, so on a first boot it updates rows that do not 

127 exist yet, which is why the insert has to carry them. 

128 """ 

129 backend = inference_routes.backend() 

130 was_bedrock = _bedrock_was_enabled(db) 

131 _seed_providers(db, backend) 

132 _seed_models(db, backend) 

133 _archive_withdrawn(db) 

134 _apply_backend_default(db, backend, was_bedrock) 

135 _keep_default_usable(db, backend) 

136 

137 

138def _archive_withdrawn(db: Session) -> None: 

139 """Archive every built-in model the registry has withdrawn 

140 (``WITHDRAWN_MODELS``) and mark it unavailable. A withdrawn row is no 

141 longer seeded, so nothing else would ever update it, and a model 

142 registered under ``bedrock`` would otherwise stay resolvable. Restoring 

143 one by hand is undone on the next start: it has no route here. Runs 

144 before ``_keep_default_usable``, which moves the default off it.""" 

145 if not WITHDRAWN_MODELS: 

146 return 

147 try: 

148 archived = ( 

149 db.query(LLMModel) 

150 .filter( 

151 LLMModel.id.in_(list(WITHDRAWN_MODELS)), 

152 LLMModel.archived_at.is_(None), 

153 ) 

154 .update( 

155 {LLMModel.archived_at: aware_utcnow(), LLMModel.is_available: False}, 

156 synchronize_session=False, 

157 ) 

158 ) 

159 db.commit() 

160 if archived: 

161 logger.info("Archived %d withdrawn built-in model(s).", archived) 

162 except Exception: 

163 db.rollback() 

164 logger.exception("Failed to archive withdrawn built-in models.") 

165 raise 

166 

167 

168def _bedrock_was_enabled(db: Session) -> bool | None: 

169 """Whether the last start ran on Bedrock (the provider row's flag), or 

170 None on a first start.""" 

171 try: 

172 row = db.query(Provider).filter_by(name=ModelEnum.Provider.bedrock).first() 

173 except Exception: # noqa: BLE001 — a first start, before the enum value 

174 db.rollback() 

175 return None 

176 return None if row is None else bool(row.is_enabled) 

177 

178 

179def _apply_backend_default(db: Session, backend: str, was_bedrock: bool | None) -> None: 

180 """Move the default model when the backend changes. 

181 

182 ``is_default`` is otherwise written on insert only, so an operator's 

183 choice survives a deploy. A change of backend is the exception: on 

184 Bedrock the default is the model the residency decision names 

185 (``is_default_on_bedrock``, UK or EU); back on the vendors' APIs it is 

186 the registry's direct default again. A first start on Bedrock counts as 

187 a change. 

188 """ 

189 on_bedrock = backend == inference_routes.BEDROCK 

190 if bool(was_bedrock) == on_bedrock: 

191 return 

192 flag = "is_default_on_bedrock" if on_bedrock else "is_default" 

193 target = next((m for m in BUILTIN_MODELS.values() if m.get(flag)), None) 

194 if target is None: 

195 return 

196 _set_default(db, target, f"inference backend is now {backend}") 

197 

198 

199def _keep_default_usable(db: Session, backend: str) -> None: 

200 """On Bedrock, never leave the default on a model nobody can run. 

201 

202 The default is the model CHAINR Bot, built-in tiles and an unpinned agent 

203 answer with. While it is unavailable (its vendor is not in 

204 ``BEDROCK_MODEL_ACCESS``, say), the registry's Bedrock default stands in 

205 if it is available, otherwise the fallback (``is_fallback_default_on_bedrock``). 

206 Once the Bedrock default is available again, the fallback gives way to it. 

207 An operator's own choice of an available model is left alone. 

208 """ 

209 if backend != inference_routes.BEDROCK: 

210 return 

211 primary = next( 

212 (m for m in BUILTIN_MODELS.values() if m.get("is_default_on_bedrock")), None 

213 ) 

214 fallback = next( 

215 (m for m in BUILTIN_MODELS.values() if m.get("is_fallback_default_on_bedrock")), 

216 None, 

217 ) 

218 

219 def usable(seed: ModelSeed | None) -> bool: 

220 return seed is not None and bool(route_values(seed, backend)["is_available"]) 

221 

222 current = _current_default(db) 

223 if current is None or not current.is_available: 

224 target = primary if usable(primary) else fallback if usable(fallback) else None 

225 reason = "the default model is not available on Bedrock here" 

226 elif fallback and str(current.id) == fallback["id"] and usable(primary): 

227 target, reason = primary, "the Bedrock default is available again" 

228 else: 

229 return 

230 if target is not None and (current is None or str(current.id) != target["id"]): 

231 _set_default(db, target, reason) 

232 

233 

234def _current_default(db: Session) -> LLMModel | None: 

235 return db.query(LLMModel).filter(LLMModel.is_default.is_(True)).first() 

236 

237 

238def _set_default(db: Session, target: ModelSeed, reason: str) -> None: 

239 """Make ``target`` the one default model.""" 

240 try: 

241 db.query(LLMModel).filter(LLMModel.is_default.is_(True)).update( 

242 {LLMModel.is_default: False}, synchronize_session=False 

243 ) 

244 db.query(LLMModel).filter(LLMModel.id == target["id"]).update( 

245 {LLMModel.is_default: True}, synchronize_session=False 

246 ) 

247 db.commit() 

248 logger.info("Default model set to %s: %s.", target["display_name"], reason) 

249 except Exception: 

250 db.rollback() 

251 logger.exception("Failed to move the default model (%s).", reason) 

252 raise 

253 

254 

255def _seed_providers(db: Session, backend: str) -> None: 

256 if not BUILTIN_PROVIDERS: 

257 return 

258 

259 stmt = insert(Provider).values( 

260 [ 

261 { 

262 "id": p["id"], 

263 "name": p["name"], 

264 "display_name": p["display_name"], 

265 "is_enabled": ( 

266 backend == inference_routes.BEDROCK 

267 if p["name"] == ModelEnum.Provider.bedrock 

268 else p["is_enabled"] 

269 ), 

270 } 

271 for p in BUILTIN_PROVIDERS.values() 

272 ] 

273 ) 

274 stmt = stmt.on_conflict_do_update( 

275 index_elements=["name"], 

276 set_={ 

277 "display_name": stmt.excluded.display_name, 

278 "is_enabled": stmt.excluded.is_enabled, 

279 }, 

280 ) 

281 

282 try: 

283 db.execute(stmt) 

284 db.commit() 

285 logger.info("Seeded %d built-in providers.", len(BUILTIN_PROVIDERS)) 

286 except Exception: 

287 db.rollback() 

288 logger.exception("Failed to seed built-in providers.") 

289 raise 

290 

291 

292def _seed_models(db: Session, backend: str) -> None: 

293 if not BUILTIN_MODELS: 

294 return 

295 

296 stmt = insert(LLMModel).values( 

297 [ 

298 { 

299 "id": m["id"], 

300 "provider_id": m["provider_id"], 

301 "model_name": m["model_name"], 

302 "display_name": m["display_name"], 

303 "description": m["description"], 

304 "is_chat": m["is_chat"], 

305 "is_embedding": m["is_embedding"], 

306 "is_vision": m["is_vision"], 

307 "is_default": m["is_default"], 

308 "is_recommended": m["is_recommended"], 

309 **route_values(m, backend), 

310 "effort": m["effort"], 

311 "latency": m["latency"], 

312 "knowledge_cutoff": m["knowledge_cutoff"], 

313 } 

314 for m in BUILTIN_MODELS.values() 

315 ] 

316 ) 

317 stmt = stmt.on_conflict_do_update( 

318 index_elements=["provider_id", "model_name"], 

319 set_={ 

320 "display_name": stmt.excluded.display_name, 

321 "description": stmt.excluded.description, 

322 "is_chat": stmt.excluded.is_chat, 

323 "is_embedding": stmt.excluded.is_embedding, 

324 "is_vision": stmt.excluded.is_vision, 

325 "is_available": stmt.excluded.is_available, 

326 "context_window": stmt.excluded.context_window, 

327 "max_output_tokens": stmt.excluded.max_output_tokens, 

328 "input_cost_per_token": stmt.excluded.input_cost_per_token, 

329 "output_cost_per_token": stmt.excluded.output_cost_per_token, 

330 "cache_read_cost_per_token": stmt.excluded.cache_read_cost_per_token, 

331 "cache_write_cost_per_token": stmt.excluded.cache_write_cost_per_token, 

332 "cache_write_1h_cost_per_token": stmt.excluded.cache_write_1h_cost_per_token, 

333 "long_context_threshold": stmt.excluded.long_context_threshold, 

334 "long_context_input_multiplier": stmt.excluded.long_context_input_multiplier, 

335 "long_context_output_multiplier": stmt.excluded.long_context_output_multiplier, 

336 "data_region": stmt.excluded.data_region, 

337 "effort": stmt.excluded.effort, 

338 "latency": stmt.excluded.latency, 

339 "knowledge_cutoff": stmt.excluded.knowledge_cutoff, 

340 }, 

341 ) 

342 

343 try: 

344 db.execute(stmt) 

345 db.commit() 

346 logger.info("Seeded %d built-in LLM models.", len(BUILTIN_MODELS)) 

347 except Exception: 

348 db.rollback() 

349 logger.exception("Failed to seed built-in LLM models.") 

350 raise