Coverage for app / inference / output_shape.py: 100%
65 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"""The shape a run's answer is asked in, held to where it can be.
3An agent chat, a skill run or a dashboard tile can ask for its answer as
4JSON — ``output_format="json"``, with an ``output_schema`` the caller reads
5it against (svc-core's comparison tile, a chat's chosen format). The
6answering node is told so (``llm.build_format_instruction``, in its
7``<request_context>``), but a graph's answer is a worker's tool loop, a
8revision or a synthesis, none of them decoded to the schema. So the finished
9answer is checked here, before the run's audit rules:
11* an answer that already is the shape — JSON that parses whole, or the one
12 fenced block it is, and with a schema, matches it (``json_shape``) —
13 passes as it is and costs nothing;
14* otherwise one structured call (``structured_call``, purpose
15 ``reply.format``) rewrites it into the shape, decoded natively where the
16 route can, on the run's own model;
17* failing that, the answer goes as it was, with the problem in one line
18 (``output_format_error`` on the response), for the caller's own check.
20Only JSON is checked: YAML, CSV and XML stay as the instruction asked.
21"""
23from __future__ import annotations
25import re
26from dataclasses import dataclass
27from typing import Any
29from langchain_core.messages import HumanMessage, SystemMessage
31from app.models.spec import ModelConfig
32from app.services.json_shape import JsonShape, ShapeMismatch
33from app.util import safe_json
34from app.util.logger import get_logger
36logger = get_logger(__name__)
38#: The step a rewrite is metered as (``metering.step``).
39REPLY_FORMAT = "reply.format"
41#: What the rewriting model is told; the reply is the data it rewrites.
42REWRITE_PROMPT = (
43 "Rewrite the reply you are given as the object its schema describes. Keep "
44 "every fact and figure it states, add none, and leave out what fits no "
45 "field."
46)
48#: An answer that is one fenced block and nothing else.
49_FENCED = re.compile(r"```(?:json)?\s*(.*?)\s*```", re.DOTALL)
51#: Where the problem rides on the response and the stream's done frame.
52ERROR_KEY = "output_format_error"
55@dataclass(frozen=True)
56class AnswerShape:
57 """What a run's answer is asked to be: JSON, to ``shape`` when the
58 request declared one, rewritten on ``model`` when it is not."""
60 shape: JsonShape | None
61 model: ModelConfig | None
63 @classmethod
64 def of(
65 cls,
66 output_format: str | None,
67 output_schema: str | None,
68 model: ModelConfig | None,
69 ) -> AnswerShape | None:
70 """The shape a request asks for, or None when it asks for none this
71 checks (prose, YAML, CSV, XML)."""
72 if output_format != "json":
73 return None
74 return cls(JsonShape.of(output_schema), model)
77def of_builder(builder: Any) -> AnswerShape | None:
78 """The shape the engine that built ``builder`` asked its answer in.
80 Type-guarded, like the engine's other builder hooks: a test double's
81 builder answers any attribute."""
82 shape = getattr(builder, "answer_shape", None)
83 return shape if isinstance(shape, AnswerShape) else None
86def _json_text(answer: str) -> str | None:
87 """The answer's JSON, when the whole of it is JSON or the one fenced
88 block it is; None otherwise."""
89 stripped = answer.strip()
90 fenced = _FENCED.fullmatch(stripped)
91 for text in (stripped, fenced.group(1) if fenced else None):
92 if text is None:
93 continue
94 try:
95 safe_json.loads_exact(text)
96 except ValueError:
97 continue
98 return text
99 return None
102def _problem(shape: AnswerShape, text: str | None) -> str | None:
103 if text is None:
104 return "the answer is not JSON"
105 if shape.shape is None:
106 return None
107 try:
108 shape.shape.validate(safe_json.loads_exact(text))
109 except ShapeMismatch as exc:
110 return str(exc)
111 return None
114async def shape_answer(
115 shape: AnswerShape | None, answer: str, *, config: Any = None
116) -> tuple[str, str | None]:
117 """``(answer, problem)``: the answer in the shape asked for, and None —
118 or the answer as it was and why it is not in it."""
119 if shape is None or not answer:
120 return answer, None
121 text = _json_text(answer)
122 problem = _problem(shape, text)
123 if problem is None:
124 return (text if text is not None else answer), None
125 if shape.shape is None or shape.model is None:
126 return answer, problem
128 from app.services.llm import build_langchain_llm
129 from app.services.structured_output import structured_call
131 llm = build_langchain_llm(
132 shape.model.model_copy(update={"output_format": None, "output_schema": None})
133 )
134 result = await structured_call(
135 llm,
136 shape.shape,
137 [SystemMessage(content=REWRITE_PROMPT), HumanMessage(content=answer)],
138 purpose=REPLY_FORMAT,
139 config=config,
140 )
141 if result.value is None:
142 logger.warning("[output] the answer could not be shaped: %s", result.failure)
143 return answer, result.failure
144 return safe_json.dumps(result.value, ensure_ascii=False), None