Coverage for app / services / structured_output.py: 98%

304 statements  

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

1"""One way a system step asks a model for structured output. 

2 

3Every system node (gate, recon, planning, evaluator) and the retrieval 

4pipeline's query planner and reranker ask the model to fill a schema. They 

5used to each call ``with_structured_output(Schema, method="function_calling")`` 

6and, on any failure, throw the whole answer away. That is the weakest of the 

7established patterns: forced function calling does not constrain the model, 

8so it can leave out a required field — the planner leaving out an empty list 

9failed every simple question — and nothing tried again. 

10 

11``structured_call`` applies, in order: 

12 

131. **Native constrained decoding** where the model supports it 

14 (``model_capabilities.native_structured_output``): OpenAI Structured 

15 Outputs with ``strict``, Anthropic structured outputs, Bedrock's 

16 structured outputs. The schema sent is ``strict_schema(Schema)`` (shared 

17 with svc-core, ``app.util.model_output``) — every property required, no 

18 extra keys, no keywords a strict mode rejects — so a decoded reply cannot 

19 omit a field or invent an enum value. Bound as an OpenAI-style 

20 ``response_format``, which langchain-openai sends as-is (Chat 

21 Completions) or as ``text.format`` (Responses API), langchain-anthropic 

22 converts to ``output_config.format`` and langchain-aws to Converse's 

23 ``outputConfig``. Function calling is the fallback: for other models 

24 (Claude 5.x on Bedrock among them), for a schema a strict mode cannot 

25 express (a free-form object), and when a provider refuses the native 

26 request — for that call, and from then on when it refused the schema 

27 itself (``provider_refusals``). The schema tool is forced where the 

28 model takes that (``forced_tool_choice``) and otherwise offered with an 

29 instruction to call it: a thinking model refuses to be forced. Every 

30 structured request is sent whole, never streamed (``_unstreamed``). 

312. **Local salvage**: the reply is read leniently (``safe_json.loads_lenient`` 

32 for text; the raw tool-call arguments when the parser gave up) and 

33 validated against the schema, whose ``ModelOutput`` base reads ``null`` as 

34 a default. A reply cut off before it was finished — at the output token 

35 limit, the context window or a content filter (``_cut``) — is not 

36 salvaged: it is read whole (``safe_json.loads_exact``) or not at all, and 

37 accepting one that parsed whole logs a warning. 

383. **One retry that says what was wrong** — the Instructor / Pydantic AI 

39 pattern — unless the model refused or ran out of tokens, where asking 

40 again gets the same answer. 

414. **A typed result, never an exception**, except for failures no step can 

42 work around (``model_errors.ModelUnavailableError``: credentials, model 

43 access, quota), which end the turn once instead of degrading every node. 

44 

45The calls carry ``STRUCTURED_OUTPUT_TAG``: a natively decoded reply is JSON 

46*text*, and the stream must not show it to the person as answer tokens. 

47""" 

48 

49from __future__ import annotations 

50 

51from dataclasses import dataclass 

52from typing import Any, Generic, TypeVar 

53 

54from langchain_core.language_models.chat_models import BaseChatModel 

55from langchain_core.messages import AIMessage, BaseMessage, HumanMessage 

56from pydantic import BaseModel, ValidationError 

57 

58from app.services import ( 

59 cut_replies, 

60 metering, 

61 model_errors, 

62 native_sibling, 

63 provider_refusals, 

64) 

65from app.services.cut_replies import CutShape 

66from app.services.model_capabilities import capabilities_for 

67from app.services.json_shape import JsonShape 

68from app.services.provider_refusals import Feature 

69from app.util import safe_json 

70from app.util.logger import get_logger 

71 

72# The schema rules are shared with svc-core (``app.util.model_output``) and 

73# re-exported here, where every system step has always imported them from. 

74from app.util.model_output import ( # noqa: F401 — re-exported 

75 RESERVED_FIELD_NAMES, 

76 ModelOutput, 

77 SchemaNotStrict, 

78 is_strict_compatible, 

79 strict_schema, 

80) 

81 

82logger = get_logger(__name__) 

83 

84#: Tag on every structured call; ``graph_based._stream_graph`` drops its tokens. 

85STRUCTURED_OUTPUT_TAG = "chainr:structured_output" 

86 

87NATIVE = "json_schema" 

88FUNCTION_CALLING = "function_calling" 

89 

90T = TypeVar("T", bound=BaseModel) 

91 

92 

93# ── What a call fills ──────────────────────────────────────────────────────── 

94 

95 

96@dataclass(frozen=True) 

97class ModelShape: 

98 """A pydantic class to fill — every system step's ``ModelOutput``.""" 

99 

100 cls: type[BaseModel] 

101 

102 @property 

103 def name(self) -> str: 

104 return self.cls.__name__ 

105 

106 @property 

107 def strict_ok(self) -> bool: 

108 return is_strict_compatible(self.cls) 

109 

110 def wire(self) -> dict[str, Any]: 

111 return strict_schema(self.cls) 

112 

113 def tool(self) -> Any: 

114 return self.cls 

115 

116 def validate(self, data: Any) -> Any: 

117 return self.cls.model_validate(data) 

118 

119 def is_value(self, value: Any) -> bool: 

120 return isinstance(value, self.cls) 

121 

122 

123#: What ``structured_call`` fills: a pydantic class (as a ``ModelShape``) or 

124#: a JSON Schema a request declared (``json_shape.JsonShape``). Both name 

125#: themselves, say whether a strict mode takes them, give the schema sent 

126#: natively and the tool bound otherwise, and validate a reply. 

127Shape = ModelShape | JsonShape 

128 

129 

130def as_shape(schema: type[BaseModel] | Shape) -> Shape: 

131 """``schema`` as a shape: a pydantic class wrapped, a shape as it is.""" 

132 if isinstance(schema, (ModelShape, JsonShape)): 

133 return schema 

134 return ModelShape(schema) 

135 

136 

137def response_format(schema: type[BaseModel] | Shape) -> dict[str, Any]: 

138 """The OpenAI-style ``response_format`` the clients accept for it.""" 

139 shape = as_shape(schema) 

140 return { 

141 "type": "json_schema", 

142 "json_schema": {"name": shape.name, "schema": shape.wire(), "strict": True}, 

143 } 

144 

145 

146# ── Which path a call takes ────────────────────────────────────────────────── 

147 

148 

149def provider_model(llm: Any) -> tuple[str, str]: 

150 """The provider and model ``llm`` was built for, from its usage meter. 

151 

152 Every model ``build_langchain_llm`` builds carries a ``MeterCallback`` 

153 naming them; anything else (a test double) is unknown. 

154 """ 

155 from app.services.metering import MeterCallback 

156 

157 callbacks = getattr(llm, "callbacks", None) 

158 if isinstance(callbacks, list): 

159 for callback in callbacks: 

160 if isinstance(callback, MeterCallback): 

161 return callback.provider, callback.model 

162 return "", "" 

163 

164 

165def method_for(llm: Any, schema: type[BaseModel] | Shape) -> str: 

166 """``NATIVE`` when the model and the schema both allow it.""" 

167 shape = as_shape(schema) 

168 provider, model = provider_model(llm) 

169 if not provider or not capabilities_for(provider, model).native_structured_output: 

170 return FUNCTION_CALLING 

171 if provider_refusals.refused(provider, model, Feature.NATIVE_SCHEMA, shape.name): 

172 return FUNCTION_CALLING 

173 return NATIVE if shape.strict_ok else FUNCTION_CALLING 

174 

175 

176def forces_tool_choice(llm: Any) -> bool: 

177 """Whether function calling may force the schema tool on ``llm``. 

178 

179 Not where the route says the model refuses it — Claude 5.x on Bedrock 

180 thinks by default, and a thinking model will not be forced to call a 

181 tool — nor once the provider has refused it. A client that names no 

182 model (a test double) keeps the client's own behaviour. 

183 """ 

184 provider, model = provider_model(llm) 

185 if not provider: 

186 return True 

187 return capabilities_for( 

188 provider, model 

189 ).forced_tool_choice and not provider_refusals.refused( 

190 provider, model, Feature.FORCED_TOOL_CHOICE 

191 ) 

192 

193 

194def _unstreamed(llm: Any) -> Any: 

195 """``llm`` answering in one response, never a stream. 

196 

197 Under ``astream_events`` a chat model streams whatever it is asked, so a 

198 structured call on a chat path went out as ConverseStream: its tokens 

199 were thrown away (``STRUCTURED_OUTPUT_TAG``), some routes decode natively 

200 only on a whole response, and a streamed tool call's arguments are parsed 

201 as partial JSON. The copy is shallow, so it keeps the client's meter. 

202 """ 

203 if isinstance(llm, BaseChatModel) and llm.disable_streaming is not True: 

204 return llm.model_copy(update={"disable_streaming": True}) 

205 return llm 

206 

207 

208# ── The call ───────────────────────────────────────────────────────────────── 

209 

210 

211@dataclass 

212class StructuredResult(Generic[T]): 

213 """What a structured call produced. ``value`` is None when it failed; 

214 ``failure`` then says why in one line, for the trace and the log.""" 

215 

216 value: T | None 

217 method: str = "" 

218 attempts: int = 0 

219 failure: str = "" 

220 #: What a reply cut off at its token cap was doing when it stopped 

221 #: (``cut_replies``), when that is why it failed. 

222 cut: CutShape | None = None 

223 #: How a cut-off reply was read after all, when it was: "closed" — it ran 

224 #: on in whitespace after a finished value, and only its closers were 

225 #: missing (``cut_replies.closed``). 

226 recovered: str = "" 

227 

228 def failure_record(self) -> dict[str, Any]: 

229 """Why it failed, for the trace: the one line, and a cut-off reply's 

230 shape. Keys and counts only, never the reply's words.""" 

231 return { 

232 "reason": self.failure or "no structured output", 

233 **({"cut": self.cut.wire()} if self.cut is not None else {}), 

234 } 

235 

236 @property 

237 def ok(self) -> bool: 

238 return self.value is not None 

239 

240 def unwrap(self) -> T: 

241 """The value, or ``model_errors.StepFailed`` carrying ``failure`` — 

242 for a step whose ``except`` already degrades and records the reason.""" 

243 if self.value is None: 

244 raise model_errors.StepFailed(self.failure or "no structured output") 

245 return self.value 

246 

247 

248@dataclass(frozen=True) 

249class _Cut: 

250 """What ended a reply before it was finished: what the reply hit, for 

251 the warning when it parsed whole anyway, and the problem it is reported 

252 with when it did not.""" 

253 

254 hit: str 

255 problem: str 

256 

257 

258#: The problem a reply cut off at the output token limit is reported with. 

259_CUT_OFF = "the reply was cut off at the output token limit" 

260_TOKEN_LIMIT = _Cut("the output cap", _CUT_OFF) 

261_CONTENT_FILTER = _Cut( 

262 "a content filter", "the reply was cut off by the provider's content filter" 

263) 

264#: The other stop reasons on which a reply ends unfinished, as a provider 

265#: names them. Its text stops where the model was stopped, so a lenient read 

266#: finds a balanced span inside it as surely as inside one cut at the token 

267#: limit. None is resumed (``base._is_truncated`` does not count them): a 

268#: full context window or a filter cuts the continuation the same way. 

269_CUT_SHORT: dict[str, _Cut] = { 

270 # Bedrock Converse's stopReason and the Anthropic Messages API's 

271 # stop_reason: the request filled the model's context window. 

272 "model_context_window_exceeded": _Cut( 

273 "the context window", "the reply was cut off at the model's context window" 

274 ), 

275 # Chat Completions' finish_reason: the output was cut where it was flagged. 

276 "content_filter": _CONTENT_FILTER, 

277 # Bedrock Converse's stopReason for the same. 

278 "content_filtered": _CONTENT_FILTER, 

279} 

280 

281 

282def _cut(message: Any) -> _Cut | None: 

283 """What ended ``message`` before it was finished, or None when nothing 

284 did: the output token limit (``base._is_truncated``) or a stop reason in 

285 ``_CUT_SHORT``.""" 

286 from app.agents.base import _is_truncated 

287 

288 if _is_truncated(message): 

289 return _TOKEN_LIMIT 

290 meta = getattr(message, "response_metadata", None) or {} 

291 for key in ("finish_reason", "stop_reason", "stopReason"): 

292 cut = _CUT_SHORT.get(str(meta.get(key) or "")) 

293 if cut is not None: 

294 return cut 

295 return None 

296 

297 

298@dataclass 

299class _Attempt: 

300 value: Any = None 

301 #: The reply as text, shown back to the model on a retry. 

302 text: str = "" 

303 problem: str = "" 

304 #: True when asking again would get the same answer (refusal, token cap). 

305 final: bool = False 

306 #: What cut the reply off before it was finished (``_cut``), when 

307 #: something did; it was read whole, if at all. 

308 cut: _Cut | None = None 

309 #: "closed" when a cut-off reply was read by closing what it left open. 

310 recovered: str = "" 

311 

312 

313def _tagged(config: Any) -> dict[str, Any]: 

314 """``config`` plus ``STRUCTURED_OUTPUT_TAG``, which every child run — 

315 the chat model's included — inherits, so its stream events carry it.""" 

316 merged: dict[str, Any] = dict(config or {}) 

317 merged["tags"] = [*(merged.get("tags") or []), STRUCTURED_OUTPUT_TAG] 

318 return merged 

319 

320 

321def _reply_text(message: Any) -> str: 

322 """The reply's text, without reasoning blocks or commentary-phase text 

323 (``reply_formats.text_of``); reasoning written as text before the JSON is 

324 left for ``safe_json`` to read past.""" 

325 from app.services import reply_formats 

326 

327 return reply_formats.text_of(getattr(message, "content", "")) 

328 

329 

330def _stop_reason(message: Any) -> str | None: 

331 """``"refusal"``, ``"truncated"`` (``_cut``: the reply ended unfinished) 

332 or None, for any provider's reply.""" 

333 if message is None: 

334 return None 

335 meta = getattr(message, "response_metadata", None) or {} 

336 extra = getattr(message, "additional_kwargs", None) or {} 

337 content = getattr(message, "content", None) 

338 blocks = content if isinstance(content, list) else [] 

339 if ( 

340 meta.get("stop_reason") == "refusal" 

341 or meta.get("stopReason") == "refusal" 

342 or extra.get("refusal") 

343 or any(isinstance(b, dict) and b.get("type") == "refusal" for b in blocks) 

344 ): 

345 return "refusal" 

346 return "truncated" if _cut(message) is not None else None 

347 

348 

349def _validated(shape: Shape, data: Any, text: str, stop: str | None) -> _Attempt: 

350 try: 

351 return _Attempt(value=shape.validate(data), text=text) 

352 except (ValidationError, model_errors.StepFailed) as exc: 

353 return _Attempt( 

354 text=text, problem=model_errors.describe(exc), final=stop is not None 

355 ) 

356 

357 

358async def _native( 

359 llm: Any, 

360 shape: Shape, 

361 messages: list[BaseMessage], 

362 config: Any, 

363 options: dict[str, Any] | None = None, 

364) -> _Attempt: 

365 bound = _unstreamed(llm).bind( 

366 response_format=response_format(shape), **(options or {}) 

367 ) 

368 reply = await bound.ainvoke(messages, config=_tagged(config)) 

369 stop = _stop_reason(reply) 

370 text = _reply_text(reply) 

371 if stop == "refusal": 

372 return _Attempt(text=text, problem="the model refused", final=True) 

373 if stop == "truncated": 

374 # Read whole or not at all. The lenient reader finds a balanced span 

375 # inside a cut-off value — one complete score of a cut list — and 

376 # that validated as the whole answer: a judge that rated nothing. 

377 cut = _cut(reply) 

378 try: 

379 data = safe_json.loads_exact(text) 

380 except ValueError: 

381 attempt = _closed_up(shape, text, stop) 

382 if attempt is not None: 

383 attempt.cut = cut 

384 return attempt 

385 return _Attempt( 

386 text=text, 

387 problem=cut.problem if cut else _CUT_OFF, 

388 final=True, 

389 cut=cut, 

390 ) 

391 attempt = _validated(shape, data, text, stop) 

392 attempt.cut = cut 

393 return attempt 

394 try: 

395 data = safe_json.loads_lenient(text) 

396 except ValueError: 

397 return _Attempt(text=text, problem="the reply held no JSON") 

398 return _validated(shape, data, text, stop) 

399 

400 

401def _tool_arguments(reply: Any, *, whole_only: bool = False) -> Any: 

402 """The arguments of the reply's first tool call, however they arrived. 

403 

404 ``whole_only``, for a reply cut off at the output token limit, reads only 

405 the raw argument text the provider sent, and only when all of it parses. 

406 The client's own parse is not taken: a streamed reply's arguments are 

407 parsed with ``parse_partial_json``, which closes a cut-off value and 

408 reports what was written so far as the arguments. 

409 """ 

410 if not whole_only: 

411 for call in getattr(reply, "tool_calls", None) or []: 

412 args = call.get("args") if isinstance(call, dict) else None 

413 if args is not None: 

414 return args 

415 read = safe_json.loads_exact if whole_only else safe_json.loads_lenient 

416 for call in getattr(reply, "invalid_tool_calls", None) or []: 

417 raw = call.get("args") if isinstance(call, dict) else None 

418 if isinstance(raw, str): 

419 try: 

420 return read(raw) 

421 except ValueError: 

422 continue 

423 return None 

424 

425 

426def _closed_up(shape: Shape, text: str, stop: str | None) -> _Attempt | None: 

427 """A cut-off reply read by closing what it left open, when it ran on in 

428 whitespace after a finished value (``cut_replies.closed``) and the 

429 result parses whole and fits the schema; else None.""" 

430 completed = cut_replies.closed(text) 

431 if completed is None: 

432 return None 

433 try: 

434 data = safe_json.loads_exact(completed) 

435 except ValueError: 

436 return None 

437 attempt = _validated(shape, data, completed, stop) 

438 if attempt.value is None: 

439 return None 

440 attempt.recovered = "closed" 

441 return attempt 

442 

443 

444def _raw_arguments(reply: Any) -> str: 

445 """The raw argument text of the reply's first tool call that did not 

446 parse, as the provider sent it; "" when there is none.""" 

447 for call in getattr(reply, "invalid_tool_calls", None) or []: 

448 raw = call.get("args") if isinstance(call, dict) else None 

449 if isinstance(raw, str): 

450 return raw 

451 return "" 

452 

453 

454def _call_the_tool(shape: Shape) -> HumanMessage: 

455 """What a model that cannot be forced to call the schema tool is told.""" 

456 name = shape.name 

457 return HumanMessage( 

458 content=( 

459 f"Answer by calling the {name} tool with your complete {name}, " 

460 "and write nothing else." 

461 ) 

462 ) 

463 

464 

465async def _function_calling( 

466 llm: Any, 

467 shape: Shape, 

468 messages: list[BaseMessage], 

469 config: Any, 

470 *, 

471 forced: bool = True, 

472) -> _Attempt: 

473 """The schema bound as a tool. ``forced`` lets the client force the call 

474 (``with_structured_output``); otherwise the tool is offered, the model is 

475 asked to call it, and its arguments are read from the reply.""" 

476 llm = _unstreamed(llm) 

477 if forced or not isinstance(llm, BaseChatModel): 

478 structured = llm.with_structured_output( 

479 shape.tool(), method="function_calling", include_raw=True 

480 ) 

481 out = await structured.ainvoke(messages, config=_tagged(config)) 

482 if shape.is_value(out): # a client (or test double) without raw 

483 return _Attempt(value=out) 

484 if not isinstance(out, dict): 

485 return _Attempt(problem=f"unexpected {type(out).__name__} from the model") 

486 parsed, reply = out.get("parsed"), out.get("raw") 

487 else: 

488 reply = await llm.bind_tools([shape.tool()]).ainvoke( 

489 [*messages, _call_the_tool(shape)], config=_tagged(config) 

490 ) 

491 parsed = None 

492 stop = _stop_reason(reply) 

493 truncated = stop == "truncated" 

494 cut = _cut(reply) if truncated else None 

495 # A cut-off reply's parsed call may be the cut-off value closed up (see 

496 # ``_tool_arguments``), so it is read from the raw arguments instead. 

497 if shape.is_value(parsed) and not truncated: 

498 return _Attempt(value=parsed) 

499 if stop == "refusal": 

500 return _Attempt( 

501 text=_reply_text(reply), problem="the model refused", final=True 

502 ) 

503 args = _tool_arguments(reply, whole_only=truncated) 

504 if args is None and truncated: 

505 attempt = _closed_up(shape, _raw_arguments(reply), stop) 

506 if attempt is not None: 

507 attempt.cut = cut 

508 return attempt 

509 if args is None and not forced and not truncated: 

510 # Offered the tool, a model may write the object as text instead. 

511 try: 

512 args = safe_json.loads_lenient(_reply_text(reply)) 

513 except ValueError: 

514 args = None 

515 if args is None: 

516 return _Attempt( 

517 # A cut-off call's arguments are the reply: what ``cut_replies`` 

518 # reads for where it stopped. 

519 text=(_raw_arguments(reply) if truncated else "") or _reply_text(reply), 

520 problem=cut.problem if cut else "the reply did not call the schema tool", 

521 final=stop is not None, 

522 cut=cut, 

523 ) 

524 attempt = _validated(shape, args, safe_json.dumps(args, ensure_ascii=False), stop) 

525 attempt.cut = cut 

526 return attempt 

527 

528 

529def _retry_thread( 

530 messages: list[BaseMessage], attempt: _Attempt, shape: Shape 

531) -> list[BaseMessage]: 

532 name = shape.name 

533 return [ 

534 *messages, 

535 AIMessage(content=attempt.text or "(no output)"), 

536 HumanMessage( 

537 content=( 

538 f"That reply did not match the {name} schema: {attempt.problem}. " 

539 f"Reply again with the complete, corrected {name} and nothing else." 

540 ) 

541 ), 

542 ] 

543 

544 

545def _bad_request(exc: BaseException) -> bool: 

546 """A 400 from any provider SDK — Bedrock's ``ValidationException`` too.""" 

547 return model_errors.status_of(exc) == 400 

548 

549 

550async def structured_call( 

551 llm: Any, 

552 schema_cls: type[T] | Shape, 

553 messages: list[BaseMessage], 

554 *, 

555 purpose: str, 

556 config: Any = None, 

557 retries: int = 1, 

558 cache_system: bool = False, 

559 stand_in: bool = True, 

560) -> StructuredResult[T]: 

561 """Ask ``llm`` to fill ``schema_cls`` — a pydantic class, or a JSON 

562 Schema a request declared (``json_shape.JsonShape``, whose value is the 

563 reply's object). See the module docstring. 

564 

565 Never raises for a reply that does not parse or a request a provider 

566 refuses — the result says what failed — except 

567 ``ModelUnavailableError``, which no later step could work around either. 

568 ``purpose`` names the step in logs and on every call it makes 

569 (``metering.step``), so a turn's spend can be read step by step. 

570 

571 ``cache_system`` marks the system message for the provider's prompt 

572 cache (``prompt_cache.cached_system``) — for a call whose system prompt 

573 is the same turn after turn, as triage's and the quality check's are. 

574 

575 ``stand_in``: whether the run's native sibling may make the call when 

576 ``llm`` would not decode the schema natively (``native_sibling``) — a 

577 system step's call. False for a node's own work (a typed worker's 

578 output), which stays on the node's model. 

579 """ 

580 if llm is None: 

581 return StructuredResult(None, failure="no model configured") 

582 shape = as_shape(schema_cls) 

583 sibling = native_sibling.current(config) if stand_in else None 

584 with metering.step(purpose): 

585 sibling_llm = sibling.stand_in(llm, shape) if sibling is not None else None 

586 if sibling_llm is not None: 

587 try: 

588 return await _call_on( 

589 sibling_llm, shape, messages, purpose, config, retries, cache_system 

590 ) 

591 except model_errors.ModelUnavailableError as exc: 

592 if not sibling.refused(exc): 

593 raise 

594 return await _call_on( 

595 llm, shape, messages, purpose, config, retries, cache_system 

596 ) 

597 

598 

599async def _call_on( 

600 llm: Any, 

601 shape: Shape, 

602 messages: list[BaseMessage], 

603 purpose: str, 

604 config: Any, 

605 retries: int, 

606 cache_system: bool, 

607) -> StructuredResult[Any]: 

608 """The structured call on ``llm``, its system message marked for that 

609 model's prompt cache when asked.""" 

610 options: dict[str, Any] = {} 

611 if cache_system: 

612 # Imported here: prompt_cache reads this module's provider_model. 

613 from app.services import prompt_cache 

614 

615 messages, options = prompt_cache.cached_system(llm, messages, [shape.name]) 

616 return await _structured_call( 

617 llm, shape, messages, purpose, config, retries, options 

618 ) 

619 

620 

621async def _structured_call( 

622 llm: Any, 

623 shape: Shape, 

624 messages: list[BaseMessage], 

625 purpose: str, 

626 config: Any, 

627 retries: int, 

628 options: dict[str, Any] | None = None, 

629) -> StructuredResult[T]: 

630 """``structured_call``'s body, inside its step. ``options`` go on the 

631 native request (``prompt_cache_key``); function calling binds the schema 

632 as a tool, which carries its own prefix.""" 

633 method = method_for(llm, shape) 

634 forced = forces_tool_choice(llm) 

635 thread = list(messages) 

636 attempt = _Attempt() 

637 calls = 0 

638 # Replies the model gave, against the budget ``retries`` sets. A request 

639 # the provider refused before answering is a call but not a reply: the 

640 # path that replaces it gets the whole budget, its corrective retry 

641 # included — it used to get one try and no correction. 

642 replies = 0 

643 while replies <= retries: 

644 calls += 1 

645 try: 

646 if method == NATIVE: 

647 attempt = await _native(llm, shape, thread, config, options) 

648 else: 

649 attempt = await _function_calling( 

650 llm, shape, thread, config, forced=forced 

651 ) 

652 except Exception as exc: # noqa: BLE001 — classified below 

653 model_errors.raise_if_fatal(exc) 

654 if method == NATIVE and _bad_request(exc): 

655 # A refusal of the schema is remembered for it; any other 

656 # 400 (a prompt too long for the window) is this call's. 

657 provider, model = provider_model(llm) 

658 lasting = model_errors.refused_schema(exc) 

659 if lasting: 

660 provider_refusals.remember( 

661 provider, model, Feature.NATIVE_SCHEMA, shape.name 

662 ) 

663 logger.warning( 

664 "[structured:%s] %s/%s refused native %s (%s) — using " 

665 "function calling %s", 

666 purpose, 

667 provider, 

668 model, 

669 shape.name, 

670 model_errors.describe(exc), 

671 "from now on" if lasting else "for this call", 

672 ) 

673 method = FUNCTION_CALLING 

674 continue 

675 if ( 

676 forced 

677 and method == FUNCTION_CALLING 

678 and (model_errors.refused_tool_choice(exc)) 

679 ): 

680 provider, model = provider_model(llm) 

681 provider_refusals.remember(provider, model, Feature.FORCED_TOOL_CHOICE) 

682 logger.warning( 

683 "[structured:%s] %s/%s refused a forced %s call (%s) — " 

684 "offering the tool instead from now on", 

685 purpose, 

686 provider, 

687 model, 

688 shape.name, 

689 model_errors.describe(exc), 

690 ) 

691 forced = False 

692 continue 

693 return StructuredResult( 

694 None, method, calls, failure=model_errors.describe(exc) 

695 ) 

696 replies += 1 

697 if attempt.value is not None: 

698 if attempt.recovered: 

699 logger.warning( 

700 "[structured:%s] %s reply ran on in whitespace to %s; read " 

701 "by closing what it left open", 

702 purpose, 

703 shape.name, 

704 attempt.cut.hit if attempt.cut else "its end", 

705 ) 

706 elif attempt.cut is not None: 

707 logger.warning( 

708 "[structured:%s] %s reply hit %s; accepted only because it " 

709 "parsed whole", 

710 purpose, 

711 shape.name, 

712 attempt.cut.hit, 

713 ) 

714 if calls > 1: 

715 logger.info( 

716 "[structured:%s] %s valid on attempt %d", 

717 purpose, 

718 shape.name, 

719 calls, 

720 ) 

721 return StructuredResult( 

722 attempt.value, method, calls, recovered=attempt.recovered 

723 ) 

724 logger.warning( 

725 "[structured:%s] %s attempt %d failed (%s): %s", 

726 purpose, 

727 shape.name, 

728 calls, 

729 method, 

730 attempt.problem, 

731 ) 

732 if attempt.final: 

733 break 

734 thread = _retry_thread(messages, attempt, shape) 

735 cut = None 

736 if attempt.cut is _TOKEN_LIMIT: 

737 cut = cut_replies.shape_of(attempt.text) 

738 logger.warning( 

739 "[structured:%s] %s cut off: %s", purpose, shape.name, cut.describe() 

740 ) 

741 return StructuredResult(None, method, calls, failure=attempt.problem, cut=cut)