Coverage for app / diagnostics / structured_probe.py: 83%

182 statements  

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

1"""What Bedrock's structured outputs cost and how they behave on this 

2deployment's routes: run by hand. 

3 

4Strict tool use is built for the platform's tools and left off 

5(``STRICT_BUILTIN_TOOLS``, ``app/tools/wire.py``): Bedrock compiles a grammar 

6for each schema it has not seen before answering — "may take up to a few 

7minutes", then cached 24 hours per account — and every agent's knowledge 

8tools make its tool set its own. This probe measures what that costs, and 

9checks the behaviours the switch depends on that no document settles. It 

10spends real money, cents in all, and is run only with approval:: 

11 

12 docker compose exec svc-ai python -m app.diagnostics.structured_probe 

13 docker compose exec svc-ai python -m app.diagnostics.structured_probe \\ 

14 --route bedrock/qwen.qwen3-235b-a22b-2507-v1:0 

15 

16It runs on every Bedrock chat route this account may use (or those named), 

17through the client production builds — so with its timeout, 300 s on a route 

18that decodes natively. Each call is one JSON line: route, case, call, 

19seconds, whether it was accepted (else the error's code), the stop reason, 

20whether the reply was JSON and matched its schema, which tools it called and 

21with which argument names, and output tokens. Never the reply's text, an 

22argument's value or a credential. 

23 

24A call that is "new" sends a schema Bedrock has never seen: a nonce, fresh 

25for each route on each run, is in a property or tool name. The cases 

26(``CASES``): 

27 

28* **A** a new reply schema (Converse ``outputConfig``), then the same again: 

29 the compile, then the cache. 

30* **A'** that schema with only a description changed: does a description 

31 recompile? 

32* **B** a new reply schema, streamed (ConverseStream). 

33* **C** one new strict tool, then the same again. 

34* **D** a typical strict tool set (the general tools and a knowledge tool): 

35 new, again, reordered, one tool more, one tool fewer — which change makes a 

36 new grammar. ``D-stream`` streams a new set. 

37* **E** a reply schema and strict tools together, on a question that needs 

38 the calculator: does the model still call its tool, and does its final 

39 reply match the schema? ``E-stream`` streams both rounds. 

40* **F** a forced tool choice, not strict: does the route take a forced call 

41 (``forced_tool_choice``)? 

42* **G** a strict tool with an optional argument the model has no reason to 

43 fill: is leaving it out accepted? 

44 

45What sets a route's ``strict_tools`` flag (``BedrockRoute``): D and E 

46accepted, a new typical set within about ten seconds of a cached one, and a 

47reordered set or one more tool not recompiling. The run of 20 October 2026 

48found all three on gpt-oss-120b and Qwen3 235B, so ``STRICT_BUILTIN_TOOLS`` 

49is on and the flag set on those two; the Claude routes were skipped (no 

50Anthropic access) and wait for a run. The results, and the command for the 

51dev host, are in ``docs/system/deployment/bedrock-migration.md``. 

52""" 

53 

54from __future__ import annotations 

55 

56import argparse 

57import asyncio 

58import json 

59import secrets 

60import time 

61from typing import Any, Literal 

62 

63from pydantic import BaseModel, Field, ValidationError, create_model 

64 

65from app.util.model_output import ModelOutput 

66 

67#: Each reply's output cap: enough for a tool call or a short JSON reply. 

68MAX_TOKENS = 1024 

69#: What every case asks: a sum the model can answer, or hand to its tool. 

70QUESTION = "What is 17 multiplied by 23?" 

71#: What the calculator answers it. 

72TOOL_RESULT = "391" 

73#: The knowledge base the typical set's knowledge tools search. 

74KNOWLEDGE = [ 

75 {"id": "probe-kb", "name": "Handbook", "type": "document", "description": "HR"} 

76] 

77 

78#: The cases, in the order each route runs them: (id, what it measures). 

79CASES: tuple[tuple[str, str], ...] = ( 

80 ("A", "a new reply schema, then the same again"), 

81 ("A'", "that schema with only a description changed"), 

82 ("B", "a new reply schema, streamed"), 

83 ("C", "one new strict tool, then the same again"), 

84 ("D", "a typical strict set: new, again, reordered, one more, one fewer"), 

85 ("D-stream", "a new typical strict set, streamed"), 

86 ("E", "a reply schema and strict tools together, over a tool round"), 

87 ("E-stream", "the same, streamed"), 

88 ("F", "a forced tool choice, not strict"), 

89 ("G", "a strict tool with an optional argument left unused"), 

90) 

91 

92 

93# ── What is sent ───────────────────────────────────────────────────────────── 

94 

95 

96def reply_schema(nonce: str, confidence: str = "How sure you are") -> type[BaseModel]: 

97 """The reply schema: new for each ``nonce`` (a property names it), and 

98 for case A' the same but for ``confidence``'s description.""" 

99 fields: dict[str, Any] = { 

100 "answer": (int, Field(description="The product, as a number")), 

101 "confidence": (Literal["low", "medium", "high"], Field(description=confidence)), 

102 f"checked_{nonce}": (bool, Field(description="Always true")), 

103 } 

104 return create_model(f"ProbeReply_{nonce}", __base__=ModelOutput, **fields) 

105 

106 

107def _renamed(spec: dict[str, Any], nonce: str) -> dict[str, Any]: 

108 function = dict(spec["function"]) 

109 function["name"] = f"{function['name']}_{nonce}" 

110 return {**spec, "function": function} 

111 

112 

113def _plain(tool: Any) -> dict[str, Any]: 

114 from langchain_core.utils.function_calling import convert_to_openai_tool 

115 

116 return convert_to_openai_tool(tool) 

117 

118 

119def typical_set(nonce: str) -> list[dict[str, Any]]: 

120 """The tools a plain agent with one knowledge base is bound, as 

121 production binds them with the switch on (``wire``): strict specs, the 

122 tools strict decoding cannot express plain. Every name carries 

123 ``nonce``, so the set is new to Bedrock.""" 

124 from app.tools import wire 

125 from app.tools.registry import general_tools, make_knowledge_tools 

126 

127 tools = [*general_tools(), *make_knowledge_tools(KNOWLEDGE)] 

128 return [_renamed(wire.strict_spec(t) or _plain(t), nonce) for t in tools] 

129 

130 

131def one_more(nonce: str) -> dict[str, Any]: 

132 """A tool the typical set lacks, as a strict spec.""" 

133 from app.tools import wire 

134 from app.tools.registry import resolve_tool 

135 

136 return _renamed(wire.strict_spec(resolve_tool("query_knowledge_base", {})), nonce) 

137 

138 

139def calculator(nonce: str) -> dict[str, Any]: 

140 from app.tools import wire 

141 from app.tools.registry import resolve_tool 

142 

143 return _renamed(wire.strict_spec(resolve_tool("calculate", {})), nonce) 

144 

145 

146class _OptionalArgs(BaseModel): 

147 expression: str = Field(description="The arithmetic to evaluate") 

148 precision: int | None = Field( 

149 default=None, description="Decimal places to round to; leave out for exact" 

150 ) 

151 

152 

153def with_optional_argument(nonce: str) -> dict[str, Any]: 

154 from app.util.model_output import strict_tool_schema 

155 

156 return { 

157 "type": "function", 

158 "function": { 

159 "name": f"evaluate_{nonce}", 

160 "description": "Evaluate an arithmetic expression.", 

161 "parameters": strict_tool_schema(_OptionalArgs), 

162 "strict": True, 

163 }, 

164 } 

165 

166 

167def forced(spec: dict[str, Any]) -> dict[str, Any]: 

168 """Converse's ``toolConfig`` forcing a call to ``spec``'s tool, not 

169 strict. Sent as it stands: langchain-aws refuses, before any request, a 

170 tool choice it believes the route will not take, and whether the route 

171 takes one is what case F asks.""" 

172 function = spec["function"] 

173 return { 

174 "tools": [ 

175 { 

176 "toolSpec": { 

177 "name": function["name"], 

178 "description": function["description"], 

179 "inputSchema": {"json": function["parameters"]}, 

180 } 

181 } 

182 ], 

183 "toolChoice": {"tool": {"name": function["name"]}}, 

184 } 

185 

186 

187# ── What is printed ────────────────────────────────────────────────────────── 

188 

189 

190def summarise( 

191 reply: Any, 

192 *, 

193 case: dict[str, Any], 

194 seconds: float, 

195 schema: type[BaseModel] | None = None, 

196) -> dict[str, Any]: 

197 """One accepted call as a JSON-able line: its shape, never its text.""" 

198 from app.services import reply_formats 

199 from app.util import safe_json 

200 

201 meta = getattr(reply, "response_metadata", None) or {} 

202 usage = getattr(reply, "usage_metadata", None) or {} 

203 calls = getattr(reply, "tool_calls", None) or [] 

204 line: dict[str, Any] = { 

205 **case, 

206 "seconds": round(seconds, 2), 

207 "accepted": True, 

208 "stop": meta.get("stopReason") or meta.get("stop_reason"), 

209 "tool_calls": [call.get("name") for call in calls], 

210 "arguments": [sorted((call.get("args") or {}).keys()) for call in calls], 

211 "output_tokens": usage.get("output_tokens"), 

212 } 

213 if schema is not None and not calls: 

214 try: 

215 data = safe_json.loads_exact(reply_formats.text_of(reply.content)) 

216 except ValueError: 

217 line.update(json=False, matches_schema=False) 

218 else: 

219 try: 

220 schema.model_validate(data) 

221 matches = True 

222 except ValidationError: 

223 matches = False 

224 line.update(json=True, matches_schema=matches) 

225 return line 

226 

227 

228def failed( 

229 exc: BaseException, *, case: dict[str, Any], seconds: float 

230) -> dict[str, Any]: 

231 """One refused or failed call: the error's code, never its message.""" 

232 from app.services import model_errors 

233 

234 return { 

235 **case, 

236 "seconds": round(seconds, 2), 

237 "accepted": False, 

238 "error": model_errors.describe(exc), 

239 } 

240 

241 

242# ── The calls ──────────────────────────────────────────────────────────────── 

243 

244 

245async def _invoke(llm: Any, messages: list[Any], *, stream: bool) -> Any: 

246 if not stream: 

247 return await llm.ainvoke(messages) 

248 merged = None 

249 async for chunk in llm.astream(messages): 

250 merged = chunk if merged is None else merged + chunk 

251 return merged 

252 

253 

254class Probe: 

255 """The cases on one route, each call one line.""" 

256 

257 def __init__(self, llm: Any, route: str, nonce: str | None = None) -> None: 

258 self.llm = llm 

259 self.route = route 

260 self.nonce = nonce or secrets.token_hex(4) 

261 self.lines: list[dict[str, Any]] = [] 

262 

263 async def _call( 

264 self, 

265 case: str, 

266 call: str, 

267 bound: Any, 

268 messages: list[Any], 

269 *, 

270 stream: bool = False, 

271 schema: type[BaseModel] | None = None, 

272 ) -> Any: 

273 labels = {"route": self.route, "case": case, "call": call, "stream": stream} 

274 started = time.monotonic() 

275 try: 

276 reply = await _invoke(bound, messages, stream=stream) 

277 except Exception as exc: # noqa: BLE001 — one failed call, the rest still run 

278 self.lines.append( 

279 failed(exc, case=labels, seconds=time.monotonic() - started) 

280 ) 

281 return None 

282 self.lines.append( 

283 summarise( 

284 reply, case=labels, seconds=time.monotonic() - started, schema=schema 

285 ) 

286 ) 

287 return reply 

288 

289 def _ask(self) -> list[Any]: 

290 from langchain_core.messages import HumanMessage, SystemMessage 

291 

292 return [ 

293 SystemMessage(content="Use your tools where they help."), 

294 HumanMessage(content=QUESTION), 

295 ] 

296 

297 def _answering(self, schema: type[BaseModel]) -> Any: 

298 from app.services.structured_output import response_format 

299 

300 return self.llm.bind(response_format=response_format(schema)) 

301 

302 def _tools(self, specs: list[dict[str, Any]], **kw: Any) -> Any: 

303 """``specs`` bound as the tool loop binds tools (``bind_tools``), so 

304 the request is the one production sends.""" 

305 return self.llm.bind_tools(specs, **kw) 

306 

307 async def case_a(self) -> None: 

308 schema = reply_schema(self.nonce) 

309 for call in ("new", "again"): 

310 await self._call( 

311 "A", call, self._answering(schema), self._ask(), schema=schema 

312 ) 

313 changed = reply_schema(self.nonce, confidence="How confident you are") 

314 await self._call( 

315 "A'", 

316 "description changed", 

317 self._answering(changed), 

318 self._ask(), 

319 schema=changed, 

320 ) 

321 

322 async def case_b(self) -> None: 

323 schema = reply_schema(f"{self.nonce}b") 

324 await self._call( 

325 "B", "new", self._answering(schema), self._ask(), stream=True, schema=schema 

326 ) 

327 

328 async def case_c(self) -> None: 

329 tool = [calculator(f"{self.nonce}c")] 

330 for call in ("new", "again"): 

331 await self._call("C", call, self._tools(tool), self._ask()) 

332 

333 async def case_d(self) -> None: 

334 nonce = f"{self.nonce}d" 

335 specs = typical_set(nonce) 

336 variants = ( 

337 ("new", specs), 

338 ("again", specs), 

339 ("reordered", list(reversed(specs))), 

340 ("one more", [*specs, one_more(nonce)]), 

341 ("one fewer", specs[1:]), 

342 ) 

343 for call, chosen in variants: 

344 await self._call("D", call, self._tools(chosen), self._ask()) 

345 streamed = self._tools(typical_set(f"{self.nonce}ds")) 

346 await self._call("D-stream", "new", streamed, self._ask(), stream=True) 

347 

348 async def case_e(self, *, stream: bool = False) -> None: 

349 from langchain_core.messages import ToolMessage 

350 

351 from app.services.structured_output import response_format 

352 

353 case = "E-stream" if stream else "E" 

354 nonce = f"{self.nonce}{'es' if stream else 'e'}" 

355 schema = reply_schema(nonce) 

356 bound = self._tools( 

357 [calculator(nonce)], response_format=response_format(schema) 

358 ) 

359 messages = self._ask() 

360 first = await self._call(case, "tool round", bound, messages, stream=stream) 

361 calls = getattr(first, "tool_calls", None) or [] 

362 if not calls: 

363 return 

364 messages += [ 

365 first, 

366 ToolMessage(content=TOOL_RESULT, tool_call_id=calls[0]["id"]), 

367 ] 

368 await self._call( 

369 case, "answer round", bound, messages, stream=stream, schema=schema 

370 ) 

371 

372 async def case_f(self) -> None: 

373 bound = self.llm.bind(toolConfig=forced(calculator(f"{self.nonce}f"))) 

374 await self._call("F", "forced", bound, self._ask()) 

375 

376 async def case_g(self) -> None: 

377 tool = [with_optional_argument(f"{self.nonce}g")] 

378 await self._call("G", "optional left out", self._tools(tool), self._ask()) 

379 

380 async def run(self) -> list[dict[str, Any]]: 

381 await self.case_a() 

382 await self.case_b() 

383 await self.case_c() 

384 await self.case_d() 

385 await self.case_e() 

386 await self.case_e(stream=True) 

387 await self.case_f() 

388 await self.case_g() 

389 return self.lines 

390 

391 

392# ── Which routes ───────────────────────────────────────────────────────────── 

393 

394 

395def bedrock_chat_routes() -> list[tuple[str, str]]: 

396 """Every catalogue chat model with a Bedrock route, as (provider, model).""" 

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

398 

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

400 return [ 

401 (names[seed["provider_id"]], seed["model_name"]) 

402 for seed in BUILTIN_MODELS.values() 

403 if seed.get("bedrock") and seed["is_chat"] 

404 ] 

405 

406 

407def skipped(provider: str, model: str) -> str | None: 

408 """Why this deployment cannot probe ``provider/model``, or None.""" 

409 from app.services import inference_routes 

410 

411 try: 

412 route = inference_routes.resolve(provider, model) 

413 except inference_routes.RouteUnavailable: 

414 return "this account has no access to its maker on Bedrock" 

415 if not route.is_bedrock: 

416 return "this deployment does not reach it through Bedrock" 

417 return None 

418 

419 

420async def main(selected: list[str]) -> None: 

421 from app.models.spec import ModelConfig 

422 from app.services.llm import build_langchain_llm 

423 

424 for provider, model in bedrock_chat_routes(): 

425 label = f"{provider}/{model}" 

426 if selected and label not in selected: 

427 continue 

428 reason = skipped(provider, model) 

429 if reason: 

430 print(json.dumps({"route": label, "skipped": reason})) 

431 continue 

432 llm = build_langchain_llm( 

433 ModelConfig(provider=provider, model=model, max_tokens=MAX_TOKENS) 

434 ) 

435 for line in await Probe(llm, label).run(): 

436 print(json.dumps(line, ensure_ascii=False)) 

437 

438 

439if __name__ == "__main__": 

440 parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 

441 parser.add_argument( 

442 "--route", 

443 action="append", 

444 default=[], 

445 help="provider/model to probe (repeatable); every Bedrock chat route if none", 

446 ) 

447 args = parser.parse_args() 

448 asyncio.run(main(args.route))