Coverage for app / services / json_shape.py: 95%
92 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A reply shape someone else declared, as a JSON Schema.
3``structured_call`` fills a pydantic class — every system step's schema is
4one (``ModelOutput``). A request can instead carry its shape as text: an agent
5or skill asked for ``output_format="json"`` with an ``output_schema`` (a
6chat's chosen format, the schema a dashboard tile reads its reply against).
7:class:`JsonShape` lets ``structured_call`` fill that too: decoded to natively
8where the route can, offered as a tool otherwise, and checked here.
10The schema is first reduced to Bedrock's subset (``bedrock_json_schema``),
11which is what a route decodes to and so what a reply is held to; the caller
12still validates the reply against everything its schema said (svc-core does,
13with the pydantic class it was written from). The check below covers that
14subset — types, required and extra keys, ``enum`` / ``const``, ``anyOf`` /
15``allOf``, internal ``$ref`` and ``minItems`` — and names a path, never a
16value: a reply's text never reaches a log or a trace through it.
17"""
19from __future__ import annotations
21import hashlib
22from dataclasses import dataclass, field
23from typing import Any
25from app.services.model_errors import StepFailed
26from app.util import safe_json
27from app.util.model_output import bedrock_json_schema, is_strict_shaped
30class ShapeMismatch(StepFailed):
31 """A reply that is not what its JSON Schema says, in one line."""
34_TYPES: dict[str, Any] = {
35 "string": lambda v: isinstance(v, str),
36 "integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
37 "number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
38 "boolean": lambda v: isinstance(v, bool),
39 "null": lambda v: v is None,
40 "object": lambda v: isinstance(v, dict),
41 "array": lambda v: isinstance(v, list),
42}
45def mismatch(schema: dict[str, Any], value: Any) -> str | None:
46 """Where ``value`` departs from ``schema`` (Bedrock's subset), or None."""
47 defs = {**(schema.get("definitions") or {}), **(schema.get("$defs") or {})}
48 return _check(schema, value, defs, "(root)")
51def _check(node: Any, value: Any, defs: dict[str, Any], path: str) -> str | None:
52 if not isinstance(node, dict):
53 return None
54 ref = node.get("$ref")
55 if isinstance(ref, str):
56 return _check(defs.get(ref.rsplit("/", 1)[-1], {}), value, defs, path)
57 options = node.get("anyOf")
58 if (
59 isinstance(options, list)
60 and options
61 and all(_check(option, value, defs, path) for option in options)
62 ):
63 return f"{path}: matches none of its options"
64 for part in node.get("allOf") or []:
65 found = _check(part, value, defs, path)
66 if found:
67 return found
68 if "enum" in node and value not in node["enum"]:
69 return f"{path}: not one of its values"
70 if "const" in node and value != node["const"]:
71 return f"{path}: not its value"
72 kind = node.get("type")
73 kinds = kind if isinstance(kind, list) else [kind] if kind else []
74 if kinds and not any(_TYPES.get(k, lambda v: True)(value) for k in kinds):
75 return f"{path}: not {' or '.join(kinds)}"
76 if isinstance(value, dict):
77 properties = node.get("properties") or {}
78 for name in node.get("required") or []:
79 if name not in value:
80 return f"{path}.{name}: missing"
81 if node.get("additionalProperties") is False:
82 extra = sorted(set(value) - set(properties))
83 if extra:
84 return f"{path}.{extra[0]}: not a field"
85 for name, child in value.items():
86 if name in properties:
87 found = _check(properties[name], child, defs, f"{path}.{name}")
88 if found:
89 return found
90 if isinstance(value, list):
91 if len(value) < int(node.get("minItems") or 0):
92 return f"{path}: too few items"
93 items = node.get("items")
94 for index, item in enumerate(value):
95 found = _check(items, item, defs, f"{path}[{index}]")
96 if found:
97 return found
98 return None
101@dataclass(frozen=True, eq=False)
102class JsonShape:
103 """A reply shape a request declared as a JSON Schema, for
104 ``structured_call``. Its value is the reply's object, checked against
105 the reduced schema."""
107 #: The declared schema, as it arrived.
108 schema: dict[str, Any]
109 #: What the tool is called and the shape known as in logs; a hash of the
110 #: schema keeps two shapes' refusals apart (``provider_refusals``).
111 label: str = "Answer"
112 _wire: dict[str, Any] = field(init=False, repr=False)
114 def __post_init__(self) -> None:
115 object.__setattr__(self, "_wire", bedrock_json_schema(self.schema))
117 @classmethod
118 def of(cls, output_schema: str | None, label: str = "Answer") -> JsonShape | None:
119 """The shape ``output_schema`` declares, or None when it is not a
120 JSON Schema object (a prose description of a shape)."""
121 if not output_schema or not output_schema.strip():
122 return None
123 try:
124 schema = safe_json.loads_exact(output_schema)
125 except ValueError:
126 return None
127 if not isinstance(schema, dict) or schema.get("type") != "object":
128 return None
129 return cls(schema, label)
131 @property
132 def name(self) -> str:
133 digest = hashlib.sha256(safe_json.dumps(self._wire, sort_keys=True).encode())
134 return f"{self.label}_{digest.hexdigest()[:8]}"
136 @property
137 def strict_ok(self) -> bool:
138 """Whether a strict mode takes it as it stands (native decoding)."""
139 return is_strict_shaped(self._wire)
141 def wire(self) -> dict[str, Any]:
142 return self._wire
144 def tool(self) -> dict[str, Any]:
145 return {
146 "type": "function",
147 "function": {
148 "name": self.name,
149 "description": "The reply, in the shape it was asked for.",
150 "parameters": self._wire,
151 },
152 }
154 def validate(self, data: Any) -> dict[str, Any]:
155 found = mismatch(self._wire, data)
156 if found:
157 raise ShapeMismatch(f"{self.name} did not match: {found}")
158 return data
160 def is_value(self, value: Any) -> bool:
161 # A tool's parsed arguments are never taken unchecked.
162 return False