Coverage for app / util / model_output.py: 94%
172 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""What a model is asked to fill, and the schema it is held to.
3Both backend services ask models for structured output: svc-ai's system steps
4through ``structured_call``, svc-core's evaluation judge, prompt optimiser and
5dashboard flows through svc-ai's governed model path. The rules for such a
6schema are the same on either side, so this module is a file in each service,
7held byte-identical by ``tools/test_shared_modules.py``. It depends on
8pydantic and the standard library only.
10* :class:`ModelOutput` is the base of every schema a model fills: a field
11 with a default reads ``null`` as that default; required fields stay
12 required.
13* :func:`strict_schema` is the schema a model is *constrained* to when a
14 provider decodes natively: every property required, no extra keys, only the
15 keywords a strict mode accepts. Bounds, lengths and defaults are dropped
16 from the wire and stay enforced by the pydantic class the reply is
17 validated against. :func:`strict_tool_schema` is its counterpart for a
18 strict tool's arguments, where optional arguments stay optional.
19* Amazon Bedrock's structured outputs accept a subset of JSON Schema Draft
20 2020-12 and refuse a schema outside it with a 400
21 (``bedrock/latest/userguide/structured-output.html``, checked 2026-10-19):
22 every basic type, ``enum`` of primitives, ``const``, ``anyOf``, ``allOf``,
23 internal ``$ref`` / ``$defs`` / ``definitions``, a fixed list of string
24 ``format`` values and ``minItems`` of 0 or 1 — never recursion, an external
25 ``$ref``, ``minimum`` / ``maximum`` / ``multipleOf``, ``minLength`` /
26 ``maxLength``, or ``additionalProperties`` other than ``false``.
27 :func:`bedrock_problems` says where a schema steps outside it;
28 :func:`bedrock_json_schema` reduces one to it.
29"""
31from __future__ import annotations
33import copy
34from functools import lru_cache
35from typing import Any
37from pydantic import BaseModel, model_validator
39#: Field names a model-facing schema may not use. Claude 5.x models can
40#: refuse — billed, as ``reasoning_extraction`` — when output asks them to
41#: write out their reasoning; ask for a short basis or evidence instead.
42RESERVED_FIELD_NAMES = frozenset(
43 {"reasoning", "rationale", "thinking", "trace", "chain_of_thought"}
44)
47class ModelOutput(BaseModel):
48 """Base for every schema a model is asked to fill.
50 Model output is read leniently where leniency loses nothing: a field that
51 has a default reads ``null`` as that default. Function-calling models
52 routinely send ``null`` — or leave the key out — for a field that is
53 empty in the normal case (no node plans for a lookup, no critique on a
54 pass). Before, one such value failed the whole object and the step fell
55 back to a degraded path.
57 Required fields stay required: a decision the model did not make is still
58 a failure. Every subclass must pass ``strict_schema`` unless it is never
59 sent to a model natively; each service's tests hold its own to that.
60 """
62 @model_validator(mode="before")
63 @classmethod
64 def _null_means_default(cls, data: Any) -> Any:
65 if not isinstance(data, dict):
66 return data
67 cleaned = dict(data)
68 for name, info in cls.model_fields.items():
69 if name in cleaned and cleaned[name] is None and not info.is_required():
70 default = info.get_default(call_default_factory=True)
71 if default is not None:
72 cleaned[name] = default
73 return cleaned
76# ── The strict schema ────────────────────────────────────────────────────────
79class SchemaNotStrict(ValueError):
80 """A schema strict decoding cannot express: a free-form object (``dict``),
81 an untyped value (``Any``), or a recursive model."""
84def _counted(n: Any, noun: str) -> str:
85 return f"{n} {noun}" if n == 1 else f"{n} {noun}s"
88#: Constraints a strict mode refuses, and the words that state them in a
89#: tool argument's description instead (``strict_tool_schema``).
90_BOUND_WORDS: tuple[tuple[str, Any], ...] = (
91 ("minimum", lambda n: f"at least {n}"),
92 ("exclusiveMinimum", lambda n: f"more than {n}"),
93 ("maximum", lambda n: f"at most {n}"),
94 ("exclusiveMaximum", lambda n: f"less than {n}"),
95 ("minLength", lambda n: f"at least {_counted(n, 'character')}"),
96 ("maxLength", lambda n: f"at most {_counted(n, 'character')}"),
97 ("minItems", lambda n: f"at least {_counted(n, 'item')}"),
98 ("maxItems", lambda n: f"at most {_counted(n, 'item')}"),
99)
102def _bounds(node: dict[str, Any]) -> str:
103 return ", ".join(words(node[key]) for key, words in _BOUND_WORDS if key in node)
106def _described(description: str | None, notes: str | None) -> str:
107 if description and notes:
108 return f"{description} ({notes})"
109 return description or notes or ""
112def _without_null(node: dict[str, Any]) -> dict[str, Any]:
113 """An optional tool argument's schema without its ``null`` alternative:
114 the model leaves the argument out rather than sending null."""
115 options = node.get("anyOf")
116 if not isinstance(options, list):
117 return node
118 kept = [option for option in options if option.get("type") != "null"]
119 if len(kept) != 1:
120 return {**node, "anyOf": kept} if kept else node
121 merged = dict(kept[0])
122 description = _described(node.get("description"), merged.get("description"))
123 if description:
124 merged["description"] = description
125 return merged
128def _strict_node(
129 node: dict[str, Any],
130 defs: dict[str, Any],
131 stack: tuple[str, ...],
132 path: str,
133 tool: bool = False,
134) -> dict[str, Any]:
135 ref = node.get("$ref")
136 if ref is None and isinstance(node.get("allOf"), list) and len(node["allOf"]) == 1:
137 ref = node["allOf"][0].get("$ref")
138 if ref is not None:
139 name = ref.rsplit("/", 1)[-1]
140 if name in stack:
141 raise SchemaNotStrict(f"{path or '(root)'}: recursive model {name}")
142 resolved = _strict_node(defs[name], defs, (*stack, name), path, tool)
143 if node.get("description"):
144 resolved = {**resolved, "description": node["description"]}
145 return resolved
147 out: dict[str, Any] = {}
148 description = node.get("description")
149 if tool:
150 description = _described(description, _bounds(node))
151 if description:
152 out["description"] = description
153 if "type" in node:
154 out["type"] = node["type"]
155 if "const" in node:
156 out["enum"] = [node["const"]]
157 if "enum" in node:
158 out["enum"] = list(node["enum"])
159 if "anyOf" in node:
160 out["anyOf"] = [
161 _strict_node(option, defs, stack, f"{path}|", tool)
162 for option in node["anyOf"]
163 ]
165 kind = node.get("type")
166 if kind == "array":
167 items = node.get("items")
168 if not isinstance(items, dict) or not items:
169 raise SchemaNotStrict(f"{path or '(root)'}: array of untyped items")
170 out["items"] = _strict_node(items, defs, stack, f"{path}[]", tool)
171 elif kind == "object":
172 properties = node.get("properties")
173 # A tool that takes no arguments declares an empty object, which a
174 # free-form one (a ``dict``) never does: it has no ``properties``.
175 empty = tool and properties == {} and not node.get("additionalProperties")
176 if not properties and not empty:
177 raise SchemaNotStrict(f"{path or '(root)'}: free-form object")
178 declared = set(node.get("required") or ())
179 required = [key for key in properties if not tool or key in declared]
180 out["properties"] = {}
181 for key, value in properties.items():
182 prop = _strict_node(value, defs, stack, f"{path}.{key}", tool)
183 out["properties"][key] = prop if key in required else _without_null(prop)
184 out["required"] = required
185 out["additionalProperties"] = False
186 elif kind is None and "anyOf" not in out and "enum" not in out:
187 raise SchemaNotStrict(f"{path or '(root)'}: untyped value")
188 return out
191@lru_cache(maxsize=256)
192def _strict_schema_cached(schema_cls: type[BaseModel]) -> dict[str, Any]:
193 raw = schema_cls.model_json_schema()
194 return _strict_node(raw, raw.get("$defs", {}), (), "")
197def strict_schema(schema_cls: type[BaseModel]) -> dict[str, Any]:
198 """The schema a model is constrained to when filling ``schema_cls``.
200 Every object lists all its properties as required and forbids others;
201 ``$defs`` are inlined; only ``type``, ``properties``, ``required``,
202 ``additionalProperties``, ``items``, ``enum``, ``anyOf`` and
203 ``description`` survive. Bounds, lengths and defaults are dropped — a
204 strict mode rejects some of them (OpenAI refuses ``default``, Bedrock
205 ``maximum``) — and stay enforced where they always were, by the pydantic
206 class the reply is validated against. Raises ``SchemaNotStrict`` for what
207 strict decoding cannot express.
208 """
209 return copy.deepcopy(_strict_schema_cached(schema_cls))
212#: The keywords :func:`strict_schema` builds a schema from — the only ones
213#: OpenAI's strict mode takes, and within Bedrock's subset.
214STRICT_KEYWORDS = frozenset(
215 {
216 "type",
217 "properties",
218 "required",
219 "additionalProperties",
220 "items",
221 "enum",
222 "anyOf",
223 "description",
224 }
225)
228def is_strict_shaped(node: Any) -> bool:
229 """Whether a JSON Schema someone else wrote is one a strict mode takes as
230 it stands: what :func:`strict_schema` builds — every object listing all
231 its properties as required and forbidding others, and only
232 ``STRICT_KEYWORDS``. A schema sent as text (``output_schema``) is
233 decoded to natively only when it is."""
234 if not isinstance(node, dict) or set(node) - STRICT_KEYWORDS:
235 return False
236 if node.get("type") == "object":
237 properties = node.get("properties")
238 if (
239 not isinstance(properties, dict)
240 or node.get("additionalProperties") is not False
241 or list(node.get("required") or []) != list(properties)
242 ):
243 return False
244 if not all(is_strict_shaped(child) for child in properties.values()):
245 return False
246 if "items" in node and not is_strict_shaped(node["items"]):
247 return False
248 return all(is_strict_shaped(option) for option in node.get("anyOf") or [])
251def is_strict_compatible(schema_cls: type[BaseModel]) -> bool:
252 try:
253 _strict_schema_cached(schema_cls)
254 except SchemaNotStrict:
255 return False
256 return True
259@lru_cache(maxsize=256)
260def _strict_tool_schema_cached(schema_cls: type[BaseModel]) -> dict[str, Any]:
261 raw = schema_cls.model_json_schema()
262 return _strict_node(raw, raw.get("$defs", {}), (), "", tool=True)
265def strict_tool_schema(schema_cls: type[BaseModel]) -> dict[str, Any]:
266 """The input schema a strict tool is held to (Bedrock ``toolSpec.strict``)
267 when its arguments are ``schema_cls``.
269 As :func:`strict_schema`, with two differences that come from a tool's
270 arguments being a request rather than a reply. An argument the class
271 declares optional stays optional: it is left out of ``required`` and its
272 ``null`` alternative dropped, so the model omits it and the tool takes
273 its default. And a bound or length a strict mode refuses is stated in
274 the argument's description ("at most 20"), since the model can no longer
275 read it from the schema; the class still enforces it when the tool runs.
276 Raises ``SchemaNotStrict`` for what strict decoding cannot express.
277 """
278 return copy.deepcopy(_strict_tool_schema_cached(schema_cls))
281# ── Bedrock's subset ─────────────────────────────────────────────────────────
283#: The keywords Bedrock's structured outputs accept. Annotations
284#: (``description``, ``title``) are kept: they steer the model and are not
285#: constraints.
286BEDROCK_KEYWORDS = frozenset(
287 {
288 "type",
289 "properties",
290 "required",
291 "additionalProperties",
292 "items",
293 "enum",
294 "const",
295 "anyOf",
296 "allOf",
297 "$ref",
298 "$defs",
299 "definitions",
300 "format",
301 "minItems",
302 "description",
303 "title",
304 }
305)
307#: The string formats Bedrock accepts.
308BEDROCK_FORMATS = frozenset(
309 {
310 "date-time",
311 "time",
312 "date",
313 "duration",
314 "email",
315 "hostname",
316 "uri",
317 "ipv4",
318 "ipv6",
319 "uuid",
320 }
321)
323#: Keywords whose value is a map of schemas, or a list of them.
324_SCHEMA_MAPS = ("properties", "$defs", "definitions")
325_SCHEMA_LISTS = ("anyOf", "allOf")
328def _primitive_enum(values: Any) -> bool:
329 return all(
330 v is None or isinstance(v, (str, int, float, bool)) for v in values or ()
331 )
334def bedrock_problems(schema: Any, path: str = "#") -> list[str]:
335 """Where ``schema`` steps outside what Bedrock decodes to; empty when it
336 fits. Every object must forbid additional properties."""
337 found: list[str] = []
338 if not isinstance(schema, dict):
339 return [f"{path}: not a schema object"]
340 for key, value in schema.items():
341 where = f"{path}/{key}"
342 if key not in BEDROCK_KEYWORDS:
343 found.append(f"{where}: unsupported keyword")
344 elif key == "format" and value not in BEDROCK_FORMATS:
345 found.append(f"{where}: unsupported format {value!r}")
346 elif key == "minItems" and value not in (0, 1):
347 found.append(f"{where}: minItems may only be 0 or 1")
348 elif key == "enum" and not _primitive_enum(value):
349 found.append(f"{where}: enum values must be primitives")
350 elif key == "additionalProperties" and value is not False:
351 found.append(f"{where}: additionalProperties must be false")
352 elif key == "$ref" and not str(value).startswith("#"):
353 found.append(f"{where}: only internal references")
354 elif key in _SCHEMA_MAPS and isinstance(value, dict):
355 for name, sub in value.items():
356 found.extend(bedrock_problems(sub, f"{where}/{name}"))
357 elif key in _SCHEMA_LISTS and isinstance(value, list):
358 for index, sub in enumerate(value):
359 found.extend(bedrock_problems(sub, f"{where}/{index}"))
360 elif key == "items" and isinstance(value, dict):
361 found.extend(bedrock_problems(value, where))
362 if (
363 schema.get("type") == "object"
364 and schema.get("additionalProperties") is not False
365 ):
366 found.append(f"{path}: an object must set additionalProperties to false")
367 return found
370def bedrock_json_schema(schema: dict[str, Any]) -> dict[str, Any]:
371 """``schema`` reduced to what Bedrock decodes to: unsupported keywords
372 dropped, every object closed to additional properties, an unsupported
373 ``format``, ``minItems`` or ``enum`` left out rather than refused."""
374 out: dict[str, Any] = {}
375 for key, value in schema.items():
376 if key not in BEDROCK_KEYWORDS:
377 continue
378 if key in _SCHEMA_MAPS and isinstance(value, dict):
379 out[key] = {
380 name: bedrock_json_schema(sub) if isinstance(sub, dict) else sub
381 for name, sub in value.items()
382 }
383 elif key in _SCHEMA_LISTS and isinstance(value, list):
384 out[key] = [
385 bedrock_json_schema(sub) if isinstance(sub, dict) else sub
386 for sub in value
387 ]
388 elif key == "items" and isinstance(value, dict):
389 out[key] = bedrock_json_schema(value)
390 elif (
391 (key == "format" and value not in BEDROCK_FORMATS)
392 or (key == "minItems" and value not in (0, 1))
393 or (key == "enum" and not _primitive_enum(value))
394 or (key == "$ref" and not str(value).startswith("#"))
395 ):
396 continue
397 else:
398 out[key] = value
399 if out.get("type") == "object" or "properties" in out:
400 out["additionalProperties"] = False
401 return out