okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
11.3 KiB273 linesraw
1"""JSON response formats at the HTTP boundary: prompt once, validate before delivery.
2
3The native engine has no grammar decoder. Failed generations are errors, never
4silently retried or returned as successful structured output.
5
6`jsonschema` is optional (no new hard dependency of the server): json_object needs only the standard library, and
7json_schema is checked against its schema when the package is installed - without it, only that the answer is one
8JSON object, and the server says so once.
9"""
10import json
11import threading
12
13
14class StructuredOutputError(RuntimeError):
15    pass
16
17
18class _ObjectOnly:
19    """The validator for json_object, and for json_schema without jsonschema: one JSON object."""
20
21    def iter_errors(self, value):
22        if not isinstance(value, dict):
23            yield _ObjectError()
24
25
26class _ObjectError:
27    absolute_path = ()
28    message = "the answer is not a JSON object"
29
30
31class _Repairing:
32    """A validator that also tells validated_json to retry once, after a strict parse failed, with the backslashes that
33    are not valid JSON escapes doubled (response_format "repair_latex_escapes": true, #2893)."""
34    repair_escapes = True
35
36    def __init__(self, inner):
37        self.inner = inner
38
39    def iter_errors(self, value):
40        return self.inner.iter_errors(value)
41
42
43_HEX = "0123456789abcdefABCDEF"
44
45
46def repair_latex_escapes(text: str) -> str:
47    r"""Double every backslash that does not start a valid JSON escape, so \alpha and \gamma read as text.
48    The valid escapes (\b \f \n \r \t \/ \" and a well-formed \uXXXX) stay as they are: a model cannot be told
49    from LaTeX there, so a \beta next to a \alpha comes back with a backspace. Pairs of backslashes are skipped."""
50    out = []
51    i, n = 0, len(text)
52    while i < n:
53        ch = text[i]
54        if ch != "\\":
55            out.append(ch)
56            i += 1
57            continue
58        nxt = text[i + 1] if i + 1 < n else ""
59        if nxt in ("\\", '"', "/", "b", "f", "n", "r", "t"):
60            out.append(ch + nxt)
61            i += 2
62        elif nxt == "u" and len(text) >= i + 6 and all(c in _HEX for c in text[i + 2:i + 6]):
63            out.append(text[i:i + 6])
64            i += 6
65        else:
66            out.append("\\\\")
67            i += 1
68    return "".join(out)
69
70
71_jsonschema = None                     # (validators, SchemaError, Registry, NoSuchResource), False when not installed
72_jsonschema_lock = threading.Lock()
73
74
75def jsonschema_modules():
76    """jsonschema, imported on first use; None when it is not installed (said once, in the server window)."""
77    global _jsonschema
78    with _jsonschema_lock:
79        if _jsonschema is None:
80            try:
81                from jsonschema import validators
82                from jsonschema.exceptions import SchemaError
83                from referencing import Registry
84                from referencing.exceptions import NoSuchResource
85                _jsonschema = (validators, SchemaError, Registry, NoSuchResource)
86            except ImportError:
87                _jsonschema = False
88                print('[strata] response_format json_schema: the Python package jsonschema is not installed, so '
89                      'answers are only checked to be one JSON object (python -m pip install "jsonschema>=4.23,<5")',
90                      flush=True)
91        return _jsonschema or None
92
93
94def _only_objects(node, root, refs=()):
95    """True when every value `node` accepts is a JSON object, so "return one JSON object" stays true.
96
97    `type: object`, an anyOf/oneOf whose branches all qualify (e.g. a root union of object shapes, which llama.cpp's
98    grammar path accepts and apps send), an allOf with a qualifying member, or a local `$ref` to one of these.
99    Anything that can also be an array, string, number, boolean or null (including `type: ["object", "null"]`) is
100    not, and a `$ref` cycle never qualifies.
101    """
102    if not isinstance(node, dict):
103        return False
104    if node.get("type") == "object":
105        return True
106    ref = node.get("$ref")
107    if isinstance(ref, str) and ref.startswith("#") and ref not in refs:
108        target = root
109        for part in ref[1:].split("/")[1:]:
110            part = part.replace("~1", "/").replace("~0", "~")
111            if not isinstance(target, dict) or part not in target:
112                return False
113            target = target[part]
114        return _only_objects(target, root, refs + (ref,))
115    for key in ("anyOf", "oneOf"):
116        branches = node.get(key)
117        if isinstance(branches, list) and branches and all(_only_objects(b, root, refs) for b in branches):
118            return True
119    branches = node.get("allOf")
120    return isinstance(branches, list) and any(_only_objects(b, root, refs) for b in branches)
121
122
123def prepare_format(response_format, messages, with_tools=False):
124    if response_format is None:
125        return messages, None
126    if not isinstance(response_format, dict):
127        raise ValueError("response_format must be an object")
128    kind = response_format.get("type")
129    if kind == "text":
130        return messages, None
131    if kind == "json_object":
132        schema = {"type": "object"}
133        modules = None                 # the standard library is enough for "one JSON object"
134    elif kind == "json_schema":
135        spec = response_format.get("json_schema")
136        if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict):
137            raise ValueError("response_format.json_schema needs a schema object")
138        if not isinstance(spec.get("name"), str) or not spec["name"]:
139            raise ValueError("response_format.json_schema needs a name")
140        if "strict" in spec and not isinstance(spec["strict"], bool):
141            raise ValueError("response_format.json_schema.strict must be boolean")
142        schema = spec["schema"]
143        if not _only_objects(schema, schema):
144            raise ValueError("response_format schema must accept only JSON objects at its root "
145                             "(type object, or anyOf/oneOf of object schemas)")
146        modules = jsonschema_modules()
147    else:
148        raise ValueError("response_format.type must be text, json_object or json_schema")
149
150    def check_refs(node):
151        if isinstance(node, dict):
152            for key, value in node.items():
153                if key in ("$ref", "$dynamicRef") and isinstance(value, str) and not value.startswith("#"):
154                    raise ValueError("response_format supports only local schema references (#...)")
155                check_refs(value)
156        elif isinstance(node, list):
157            for value in node:
158                check_refs(value)
159    check_refs(schema)
160    if modules is None:
161        validator = _ObjectOnly()
162    else:
163        validators, SchemaError, Registry, NoSuchResource = modules
164
165        def no_remote(uri):
166            raise NoSuchResource(ref=uri)
167
168        try:
169            cls = validators.validator_for(schema)
170            cls.check_schema(schema)
171            validator = cls(schema, registry=Registry(retrieve=no_remote))
172        except SchemaError as exc:
173            raise ValueError(f"invalid response_format schema: {exc.message}") from exc
174    directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. "
175                 "No Markdown, headings, code fences, commentary, or text outside the JSON. "
176                 "Use every required field, correct types, and only allowed fields. "
177                 "Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" +
178                 json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":")))
179    if with_tools:
180        # /v1/responses (#782): the schema is for the final answer; a turn that calls a tool is not an answer
181        directive += ("\nThis applies only to your final answer. To use a tool, call it as usual; the JSON object is "
182                      "what you write once you are done with the tools.")
183    if response_format.get("repair_latex_escapes") is True:
184        validator = _Repairing(validator)
185    messages = [dict(message) for message in messages]
186    if messages and messages[0].get("role") == "system":
187        content = messages[0].get("content") or ""
188        if isinstance(content, list):
189            messages[0]["content"] = content + [{"type": "text", "text": directive}]
190        else:
191            messages[0]["content"] = content + "\n\n" + directive
192    else:
193        messages.insert(0, {"role": "system", "content": directive})
194    return messages, validator
195
196
197def extract_json(text: str) -> str:
198    """The first JSON object in `text`: a ```-fenced block's inside when there is one, else the text
199    from its first `{`.  Empty when there is nothing to take.  The server's json_schema logprobs
200    alignment reads the model's own JSON form with it."""
201    s = (text or "").strip()
202    if not s:
203        return ""
204    if s.startswith("```"):
205        first = s.find("\n")
206        if first != -1:
207            end = s.find("```", first + 1)
208            if end != -1:
209                s = s[first + 1:end].strip()
210    start = s.find("{")
211    if start == -1:
212        return s
213    depth = 0
214    in_str = False
215    esc = False
216    for i in range(start, len(s)):
217        ch = s[i]
218        if in_str:
219            if esc:
220                esc = False
221            elif ch == "\\":
222                esc = True
223            elif ch == "\"":
224                in_str = False
225        else:
226            if ch == "\"":
227                in_str = True
228            elif ch == "{":
229                depth += 1
230            elif ch == "}":
231                depth -= 1
232                if depth == 0:
233                    return s[start:i + 1]
234    return s[start:]
235
236
237def validated_json(text, validator, finish):
238    def pairs(items):
239        obj = {}
240        for key, value in items:
241            if key in obj:
242                raise ValueError(f"duplicate JSON key: {key}")
243            obj[key] = value
244        return obj
245
246    def constant(value):
247        raise ValueError(f"invalid JSON constant: {value}")
248
249    if finish != "stop":
250        raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget")
251    try:
252        value = json.loads(extract_json(text), object_pairs_hook=pairs, parse_constant=constant)
253        canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
254    except (ValueError, TypeError) as exc:
255        value = None
256        if getattr(validator, "repair_escapes", False):      # opt-in (#2893); only after the strict parse failed
257            try:
258                value = json.loads(repair_latex_escapes(extract_json(text)), object_pairs_hook=pairs,
259                                   parse_constant=constant)
260                canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
261                print("[strata] structured output: repaired backslashes that were not valid JSON escapes", flush=True)
262            except (ValueError, TypeError):
263                value = None
264        if value is None:
265            raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc
266    try:
267        error = next(validator.iter_errors(value), None)
268    except Exception as exc:
269        raise StructuredOutputError(f"could not validate structured output: {exc}") from exc
270    if error is not None:
271        path = "/" + "/".join(str(part) for part in error.absolute_path)
272        raise StructuredOutputError(f"model output failed the JSON Schema at {path}: {error.message}")
273    return canonical