Coverage for app / services / structured_reply.py: 100%
47 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"""A reply a model fills to a schema svc-core declares.
3svc-core asks models for structured data in four places — the evaluation
4judge, the prompt optimiser's proposer, the dashboard generator and the
5comparison tile — and calls no model itself: each goes through svc-ai's
6governed paths (``ai_client.invoke_model``, an agent request), which carry
7the schema as ``output_format="json"`` and ``output_schema``. svc-ai decodes
8to it natively where the route can (Bedrock's ``outputConfig``, strict
9``json_schema`` on OpenAI and Anthropic) and states it in the instruction it
10adds where it cannot. They used to ask for JSON in prose and dig it out of
11whatever came back.
13The schema sent is ``strict_schema`` of a ``ModelOutput``
14(``app/util/model_output.py``, carried byte for byte by svc-ai), so these
15schemas meet the rules svc-ai's own system steps do, and decode natively
16wherever theirs do. ``tests/test_structured_replies.py`` holds every one to
17them.
19A reply is read whole, as the one fenced block it is, or as the object it
20ends with after a model's preamble — never as a span salvaged from inside
21it, so a reply cut off mid-object is not read at all — and is then validated
22by the class, which still enforces the bounds and lengths the wire schema
23leaves out. ``targets.invoke_structured`` makes the call, and one correction
24after a reply that does not match.
25"""
27from __future__ import annotations
29import json
30import re
31from typing import Any
33from pydantic import BaseModel, ValidationError
35from app.util.model_output import strict_schema
37#: What every structured request asks svc-ai for.
38OUTPUT_FORMAT = "json"
40#: A reply that is one fenced block and nothing else.
41_FENCED = re.compile(r"```(?:json)?\s*(.*?)\s*```", re.DOTALL)
44def output_schema(schema_cls: type[BaseModel]) -> str:
45 """The JSON Schema svc-ai is sent for ``schema_cls``: its strict form,
46 as svc-ai's own steps send theirs."""
47 return json.dumps(strict_schema(schema_cls), separators=(",", ":"))
50def _candidates(text: str) -> list[str]:
51 candidates = [text]
52 fences = _FENCED.findall(text)
53 if len(fences) == 1:
54 candidates.append(fences[0])
55 # A preamble before the object (a model's working written as text): the
56 # object is read only when it ends the reply, so one cut off is not.
57 start = text.find("{")
58 if start > 0 and text.endswith("}"):
59 candidates.append(text[start:])
60 return candidates
63def _problem(exc: ValidationError) -> str:
64 """One line naming what did not validate — never the reply itself."""
65 fields = sorted(
66 {
67 f"{'.'.join(str(p) for p in err.get('loc', ())) or '(root)'} "
68 f"({err.get('type', 'invalid')})"
69 for err in exc.errors()
70 }
71 )
72 return f"{exc.title} did not validate: {', '.join(fields)}"[:300]
75def read[T: BaseModel](text: str | None, schema_cls: type[T]) -> tuple[T | None, str]:
76 """``(value, "")`` when ``text`` is a reply filled to ``schema_cls``,
77 else ``(None, problem)`` with the problem in one line."""
78 stripped = (text or "").strip()
79 if not stripped:
80 return None, "the reply was empty"
81 data: Any = None
82 for candidate in _candidates(stripped):
83 try:
84 data = json.loads(candidate)
85 except ValueError:
86 continue
87 break
88 else:
89 return None, "the reply held no JSON object"
90 try:
91 return schema_cls.model_validate(data), ""
92 except ValidationError as exc:
93 return None, _problem(exc)
96def json_object(text: str | None) -> dict[str, Any] | None:
97 """A JSON object a schema carries as text (``ProposedWidget.config_json``:
98 a value strict decoding cannot type, a widget's free-form config), read
99 exactly; None when it is not one."""
100 try:
101 value = json.loads(text or "")
102 except ValueError:
103 return None
104 return value if isinstance(value, dict) else None
107def correction(schema_cls: type[BaseModel], problem: str) -> str:
108 """What a model is told after a reply that did not match: what was
109 wrong, and to reply again with the whole object."""
110 name = schema_cls.__name__
111 return (
112 f"That reply did not match the {name} schema: {problem}. Reply again "
113 f"with the complete, corrected {name} and nothing else."
114 )