Coverage for app / services / inference_routes.py: 95%

132 statements  

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

1""" 

2How this deployment reaches a model: the vendor's own API, or Amazon Bedrock. 

3 

4A catalogue model is a *model* — "Claude Sonnet 5", ``anthropic/claude- 

5sonnet-5`` — and every agent, rule, evaluation and dashboard tile refers to it 

6by that identity. Which endpoint serves it is the deployment's choice 

7(``INFERENCE_BACKEND``): 

8 

9* ``direct`` — the vendor's API with the vendor's key. Local development. 

10* ``bedrock`` — Amazon Bedrock in ``BEDROCK_REGION``: one AWS bill, one place 

11 to cap spend, and inference that runs in the UK or the EU where the model 

12 is offered there (``docs/system/deployment/bedrock-migration.md``). 

13 

14The same catalogue row is served either way, so nothing that refers to a 

15model changes when a deployment moves; the catalogue's prices and data region 

16follow the route (the seeder writes them), and a model with no route on this 

17backend is marked unavailable rather than silently swapped for another. 

18 

19``resolve(provider, model)`` is the one place that decides. Everything that 

20builds a client asks it: the LangChain path (``llm.build_langchain_llm``), 

21the LiteLLM path (``llm.run_model`` / ``stream_model``) and the capability 

22table (``model_capabilities``), which is per route because Bedrock accepts a 

23different request than the vendor does. 

24 

25A model registered under the ``bedrock`` provider itself names a Bedrock 

26model or inference profile id directly and is served by Bedrock on any 

27backend. 

28""" 

29 

30from __future__ import annotations 

31 

32import re 

33from dataclasses import dataclass 

34from functools import lru_cache 

35from typing import Any 

36 

37from app.services import model_errors 

38 

39DIRECT = "direct" 

40BEDROCK = "bedrock" 

41BACKENDS = (DIRECT, BEDROCK) 

42 

43#: What a person is told runs the models on any backend but ``direct``: the 

44#: platform, not the cloud it runs on. The cloud is a sub-processor 

45#: (``docs/business/sub-processors.md``), not something a person choosing a 

46#: model needs to see; fe-core says the same (``objects/modelOrigin.ts``). 

47#: Fixed rather than built from ``app_name``, which deployments set to 

48#: ``CHAINR``. 

49SERVING_PLATFORM = "CHAIN-R Cloud" 

50 

51#: Inference-profile prefixes a Bedrock model id may start with; the vendor 

52#: follows (``eu.anthropic.claude-…`` is Anthropic's, ``amazon.nova-…`` 

53#: Amazon's). 

54_PROFILE_PREFIXES = ("global.", "eu.", "us.", "apac.", "jp.", "au.", "in.", "ca.") 

55 

56 

57@dataclass(frozen=True) 

58class Route: 

59 """Where one model's calls go on this deployment.""" 

60 

61 #: ``direct`` or ``bedrock``. 

62 backend: str 

63 #: The catalogue identity — what the call is metered and priced as. 

64 provider: str 

65 model: str 

66 #: What the client is given: the vendor's model name, or a Bedrock model 

67 #: or inference-profile id. 

68 model_id: str 

69 #: The vendor whose model this is (``anthropic`` / ``openai``), for the 

70 #: capability table; ``""`` when a Bedrock id names an unknown vendor. 

71 vendor: str 

72 #: Whether this route decodes to a JSON schema natively. Bedrock's 

73 #: support differs from the vendor's (no Claude 5.x, for one). 

74 native_structured_output: bool | None = None 

75 #: Whether a call may force the model to use a tool on this route 

76 #: (``BedrockRoute.forced_tool_choice``); None where nothing seeded says. 

77 forced_tool_choice: bool | None = None 

78 #: Whether a tool's arguments may be held to its schema on this route 

79 #: (``BedrockRoute.strict_tools``); None where nothing seeded says. 

80 strict_tools: bool | None = None 

81 #: Whether the model reasons before it answers on this route, as the 

82 #: reply probe measured it (``BedrockRoute.reasons_before_answering``); 

83 #: None where nothing seeded says. 

84 reasons_before_answering: bool | None = None 

85 

86 @property 

87 def is_bedrock(self) -> bool: 

88 return self.backend == BEDROCK 

89 

90 

91class RouteUnavailable(model_errors.ModelUnavailableError): 

92 """The model has no route on this deployment's inference backend.""" 

93 

94 def __init__(self, provider: str, model: str, backend: str) -> None: 

95 super().__init__(model_errors.FatalKind.MODEL_NOT_FOUND, None, provider) 

96 self.args = (f"{provider}/{model} has no route on the {backend} backend",) 

97 self.backend = backend 

98 

99 @property 

100 def user_message(self) -> str: 

101 where = ( 

102 f"{SERVING_PLATFORM}, this deployment's AI service" 

103 if self.backend == BEDROCK 

104 else "this deployment's AI service" 

105 ) 

106 return ( 

107 f"This model is not available on {where}. Choose another model " 

108 "for this agent." 

109 ) 

110 

111 

112def backend() -> str: 

113 """This deployment's inference backend (``INFERENCE_BACKEND``).""" 

114 from app.common.settings import get_settings 

115 

116 value = (get_settings().INFERENCE_BACKEND or DIRECT).strip().lower() 

117 return value if value in BACKENDS else DIRECT 

118 

119 

120def region() -> str: 

121 """The AWS region Bedrock is called in (``BEDROCK_REGION``).""" 

122 from app.common.settings import get_settings 

123 

124 return (get_settings().BEDROCK_REGION or "eu-west-2").strip() 

125 

126 

127@lru_cache(maxsize=1) 

128def _bedrock_routes() -> dict[tuple[str, str], dict[str, Any]]: 

129 """``(provider, model_name) → bedrock route`` from the seeded catalogue.""" 

130 from app.db.postgres.providers.registry import BUILTIN_MODELS, BUILTIN_PROVIDERS 

131 

132 names = {p["id"]: str(p["name"]) for p in BUILTIN_PROVIDERS.values()} 

133 routes: dict[tuple[str, str], dict[str, Any]] = {} 

134 for seed in BUILTIN_MODELS.values(): 

135 route = seed.get("bedrock") 

136 if route: 

137 routes[(names[seed["provider_id"]], seed["model_name"])] = route 

138 return routes 

139 

140 

141@lru_cache(maxsize=1) 

142def _seed_regions() -> dict[tuple[str, str], str]: 

143 """``(provider, model_name) → data region`` as the vendor's API serves 

144 each seeded model.""" 

145 from app.db.postgres.providers.registry import BUILTIN_MODELS, BUILTIN_PROVIDERS 

146 

147 names = {p["id"]: str(p["name"]) for p in BUILTIN_PROVIDERS.values()} 

148 return { 

149 (names[seed["provider_id"]], seed["model_name"]): str(seed["data_region"]) 

150 for seed in BUILTIN_MODELS.values() 

151 if seed.get("data_region") 

152 } 

153 

154 

155def bedrock_vendor(model_id: str) -> str: 

156 """The vendor a Bedrock model id names (``eu.anthropic.claude-…`` → 

157 ``anthropic``, ``eu.amazon.nova-…`` → ``amazon``), or ``""``.""" 

158 bare = model_id.lower() 

159 for prefix in _PROFILE_PREFIXES: 

160 if bare.startswith(prefix): 

161 bare = bare[len(prefix) :] 

162 break 

163 vendor, dot, _ = bare.partition(".") 

164 return vendor if dot else "" 

165 

166 

167def maker_of(provider: str, model: str) -> str: 

168 """Who made ``provider/model``: the catalogue provider, or for a model 

169 registered under ``bedrock`` itself the vendor its id names 

170 (``bedrock/qwen.qwen3-…`` → ``qwen``). Every model Bedrock alone serves 

171 is registered under ``bedrock``, so the provider does not tell two such 

172 makers apart; svc-core's lighter model, native sibling and benchmark 

173 compare this instead (served as the catalogue's ``maker``). fe-core reads 

174 the same rule (``objects/modelOrigin.ts`` ``makerKey``).""" 

175 provider = (provider or "").strip().lower() 

176 if provider == BEDROCK: 

177 return bedrock_vendor(model or "") 

178 return provider 

179 

180 

181def seeded_route_of(model_id: str) -> dict[str, Any] | None: 

182 """The seeded route that calls Bedrock as ``model_id`` — what it decodes 

183 natively, whether it may force a tool or hold one to its schema — or None 

184 for an id no seeded route uses.""" 

185 for (provider, model), route in _bedrock_routes().items(): 

186 if route.get("model_id", model if provider == BEDROCK else None) == model_id: 

187 return route 

188 return None 

189 

190 

191def seeded_output_ceiling(model_id: str) -> int | None: 

192 """The most a seeded Bedrock route writes in one reply, by the catalogue 

193 (the route's own limit, else the model's), or None for an id no seeded 

194 route uses.""" 

195 from app.db.postgres.providers.registry import BUILTIN_MODELS 

196 

197 for seed in BUILTIN_MODELS.values(): 

198 route = seed.get("bedrock") 

199 if route and route["model_id"] == model_id: 

200 return route.get("max_output_tokens") or seed.get("max_output_tokens") 

201 return None 

202 

203 

204def model_access() -> frozenset[str] | None: 

205 """The vendors this account may use on Bedrock (``BEDROCK_MODEL_ACCESS``), 

206 or None for all of them.""" 

207 from app.common.settings import get_settings 

208 

209 raw = (get_settings().BEDROCK_MODEL_ACCESS or "").strip().lower() 

210 if raw in ("", "all"): 

211 return None 

212 return frozenset(v.strip() for v in raw.split(",") if v.strip()) 

213 

214 

215def has_access(vendor: str) -> bool: 

216 """Whether the account may use ``vendor``'s models on Bedrock.""" 

217 access = model_access() 

218 return access is None or (vendor or "").lower() in access 

219 

220 

221def resolve(provider: str, model: str) -> Route: 

222 """The route ``provider/model`` takes on this deployment. 

223 

224 Raises ``RouteUnavailable`` (a fatal model error: the turn ends once, 

225 saying so) for a catalogue model with no route on this backend. 

226 """ 

227 provider = (provider or "").strip().lower() 

228 model = (model or "").strip() 

229 if provider == BEDROCK: 

230 vendor = bedrock_vendor(model) 

231 if not has_access(vendor): 

232 raise RouteUnavailable(provider, model, BEDROCK) 

233 # A seeded Bedrock-only model (Qwen3) states its own route, native 

234 # schema support included; one registered by hand states nothing. 

235 seeded = _bedrock_routes().get((provider, model)) 

236 return Route( 

237 BEDROCK, 

238 provider, 

239 model, 

240 model, 

241 vendor, 

242 native_structured_output=( 

243 bool(seeded.get("native_structured_output")) if seeded else None 

244 ), 

245 forced_tool_choice=( 

246 bool(seeded.get("forced_tool_choice")) if seeded else None 

247 ), 

248 strict_tools=bool(seeded.get("strict_tools")) if seeded else None, 

249 reasons_before_answering=( 

250 bool(seeded.get("reasons_before_answering")) if seeded else None 

251 ), 

252 ) 

253 if backend() == BEDROCK: 

254 route = _bedrock_routes().get((provider, model)) 

255 if route is None or not has_access(provider): 

256 raise RouteUnavailable(provider, model, BEDROCK) 

257 return Route( 

258 BEDROCK, 

259 provider, 

260 model, 

261 route["model_id"], 

262 provider, 

263 native_structured_output=bool(route.get("native_structured_output")), 

264 forced_tool_choice=bool(route.get("forced_tool_choice")), 

265 strict_tools=bool(route.get("strict_tools")), 

266 reasons_before_answering=bool(route.get("reasons_before_answering")), 

267 ) 

268 return Route(DIRECT, provider, model, model, provider) 

269 

270 

271def data_region(provider: str, model: str) -> str | None: 

272 """Where a call to ``provider/model`` is processed on this deployment — 

273 the route's region on Bedrock, the vendor's otherwise — as the seeder 

274 writes it to the catalogue; None for a model nothing seeded describes. 

275 

276 Two models compared by region (a structured step moved to a native 

277 sibling, ``services/native_sibling.py``) must both say theirs: an 

278 unknown region is never taken to match.""" 

279 provider = (provider or "").strip().lower() 

280 model = (model or "").strip() 

281 if provider == BEDROCK or backend() == BEDROCK: 

282 route = _bedrock_routes().get((provider, model)) 

283 return str(route["data_region"]) if route else None 

284 return _seed_regions().get((provider, model)) 

285 

286 

287#: A model id that names one fixed version: a date (``…-20251001``, 

288#: ``…-2024-08-06``) or Bedrock's version qualifier (``…-v1:0``, ``…-1:0``). 

289_PINNED = re.compile(r"(?:-\d{8}|-\d{4}-\d{2}-\d{2}|:\d+)$") 

290 

291 

292def version_pinned(provider: str, model: str) -> bool: 

293 """Whether the model this deployment calls is one fixed version, which 

294 a provider cannot change under the same name. Judged on the id the 

295 route sends (a Bedrock id carries its version where the catalogue name 

296 may not), or on the catalogue name when the model has no route here. 

297 svc-core's platform benchmark never re-measures a pinned model for age.""" 

298 try: 

299 model_id = resolve(provider, model).model_id 

300 except RouteUnavailable: 

301 model_id = model 

302 return bool(_PINNED.search((model_id or "").strip())) 

303 

304 

305def available(provider: str, model: str, *, direct: bool = True) -> bool: 

306 """Whether a catalogue model can be served on this backend. ``direct`` is 

307 whether the vendor's own API serves it at all.""" 

308 if (provider or "").lower() == BEDROCK: 

309 return has_access(bedrock_vendor(model)) 

310 if backend() == BEDROCK: 

311 return (provider.lower(), model) in _bedrock_routes() and has_access(provider) 

312 return direct 

313 

314 

315def bedrock_client_config( 

316 read_timeout_s: float, 

317 *, 

318 retry_mode: str = "standard", 

319 max_attempts: int | None = None, 

320) -> Any: 

321 """botocore settings for a Bedrock client: the retry budget the vendor 

322 SDKs get (``standard`` mode retries throttling, 5xx and connection 

323 errors, never a 400) and the model family's timeout. 

324 

325 The embedder asks for ``adaptive`` mode, which also slows the client 

326 down when Bedrock throttles: indexing sends many small requests, and 

327 Titan is limited by requests per minute.""" 

328 from botocore.config import Config 

329 

330 from app.services.llm import MODEL_CALL_RETRIES 

331 

332 return Config( 

333 region_name=region(), 

334 retries={ 

335 "max_attempts": max_attempts or MODEL_CALL_RETRIES + 1, 

336 "mode": retry_mode, 

337 }, 

338 connect_timeout=10, 

339 read_timeout=read_timeout_s, 

340 ) 

341 

342 

343def clear_cache() -> None: 

344 """Forget the route table (tests that change the registry).""" 

345 _bedrock_routes.cache_clear() 

346 _seed_regions.cache_clear()