okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
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 ): 15pass 16 17 18class _ObjectOnly : 19"""The validator for json_object, and for json_schema without jsonschema: one JSON object.""" 20 21def iter_errors (self ,value ): 22if not isinstance (value ,dict ): 23yield _ObjectError () 24 25 26class _ObjectError : 27absolute_path = () 28message = "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 33are not valid JSON escapes doubled (response_format "repair_latex_escapes": true, #2893).""" 34repair_escapes = True 35 36def __init__ (self ,inner ): 37self .inner = inner 38 39def iter_errors (self ,value ): 40return self .inner .iter_errors (value ) 41 42 43_HEX = "0123456789abcdefABCDEF" 44 45 46def repair_latex_escapes (text :str )-> str : 47r"""Double every backslash that does not start a valid JSON escape, so \alpha and \gamma read as text. 48The valid escapes (\b \f \n \r \t \/ \" and a well-formed \uXXXX) stay as they are: a model cannot be told 49from LaTeX there, so a \beta next to a \alpha comes back with a backspace. Pairs of backslashes are skipped.""" 50out = [] 51i ,n = 0 ,len (text ) 52while i < n : 53ch = text [i ] 54if ch != "\\" : 55out .append (ch ) 56i += 1 57continue 58nxt = text [i + 1 ]if i + 1 < n else "" 59if nxt in ("\\" ,'"' ,"/" ,"b" ,"f" ,"n" ,"r" ,"t" ): 60out .append (ch + nxt ) 61i += 2 62elif nxt == "u" and len (text )>= i + 6 and all (c in _HEX for c in text [i + 2 :i + 6 ]): 63out .append (text [i :i + 6 ]) 64i += 6 65else : 66out .append ("\\\\" ) 67i += 1 68return "" .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).""" 77global _jsonschema 78with _jsonschema_lock : 79if _jsonschema is None : 80try : 81from jsonschema import validators 82from jsonschema .exceptions import SchemaError 83from referencing import Registry 84from referencing .exceptions import NoSuchResource 85_jsonschema = (validators ,SchemaError ,Registry ,NoSuchResource ) 86except ImportError : 87_jsonschema = False 88'[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")' , 90flush = True ) 91return _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 98grammar path accepts and apps send), an allOf with a qualifying member, or a local `$ref` to one of these. 99Anything that can also be an array, string, number, boolean or null (including `type: ["object", "null"]`) is 100not, and a `$ref` cycle never qualifies. 101""" 102if not isinstance (node ,dict ): 103return False 104if node .get ("type" )== "object" : 105return True 106ref = node .get ("$ref" ) 107if isinstance (ref ,str )and ref .startswith ("#" )and ref not in refs : 108target = root 109for part in ref [1 :].split ("/" )[1 :]: 110part = part .replace ("~1" ,"/" ).replace ("~0" ,"~" ) 111if not isinstance (target ,dict )or part not in target : 112return False 113target = target [part ] 114return _only_objects (target ,root ,refs + (ref ,)) 115for key in ("anyOf" ,"oneOf" ): 116branches = node .get (key ) 117if isinstance (branches ,list )and branches and all (_only_objects (b ,root ,refs )for b in branches ): 118return True 119branches = node .get ("allOf" ) 120return 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 ): 124if response_format is None : 125return messages ,None 126if not isinstance (response_format ,dict ): 127raise ValueError ("response_format must be an object" ) 128kind = response_format .get ("type" ) 129if kind == "text" : 130return messages ,None 131if kind == "json_object" : 132schema = {"type" :"object" } 133modules = None # the standard library is enough for "one JSON object" 134elif kind == "json_schema" : 135spec = response_format .get ("json_schema" ) 136if not isinstance (spec ,dict )or not isinstance (spec .get ("schema" ),dict ): 137raise ValueError ("response_format.json_schema needs a schema object" ) 138if not isinstance (spec .get ("name" ),str )or not spec ["name" ]: 139raise ValueError ("response_format.json_schema needs a name" ) 140if "strict" in spec and not isinstance (spec ["strict" ],bool ): 141raise ValueError ("response_format.json_schema.strict must be boolean" ) 142schema = spec ["schema" ] 143if not _only_objects (schema ,schema ): 144raise ValueError ("response_format schema must accept only JSON objects at its root " 145"(type object, or anyOf/oneOf of object schemas)" ) 146modules = jsonschema_modules () 147else : 148raise ValueError ("response_format.type must be text, json_object or json_schema" ) 149 150def check_refs (node ): 151if isinstance (node ,dict ): 152for key ,value in node .items (): 153if key in ("$ref" ,"$dynamicRef" )and isinstance (value ,str )and not value .startswith ("#" ): 154raise ValueError ("response_format supports only local schema references (#...)" ) 155check_refs (value ) 156elif isinstance (node ,list ): 157for value in node : 158check_refs (value ) 159check_refs (schema ) 160if modules is None : 161validator = _ObjectOnly () 162else : 163validators ,SchemaError ,Registry ,NoSuchResource = modules 164 165def no_remote (uri ): 166raise NoSuchResource (ref = uri ) 167 168try : 169cls = validators .validator_for (schema ) 170cls .check_schema (schema ) 171validator = cls (schema ,registry = Registry (retrieve = no_remote )) 172except SchemaError as exc : 173raise ValueError (f"invalid response_format schema: { exc . message } " )from exc 174directive = ("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" + 178json .dumps (schema ,ensure_ascii = False ,allow_nan = False ,separators = ("," ,":" ))) 179if with_tools : 180# /v1/responses (#782): the schema is for the final answer; a turn that calls a tool is not an answer 181directive += ("\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." ) 183if response_format .get ("repair_latex_escapes" )is True : 184validator = _Repairing (validator ) 185messages = [dict (message )for message in messages ] 186if messages and messages [0 ].get ("role" )== "system" : 187content = messages [0 ].get ("content" )or "" 188if isinstance (content ,list ): 189messages [0 ]["content" ]= content + [{"type" :"text" ,"text" :directive }] 190else : 191messages [0 ]["content" ]= content + "\n\n" + directive 192else : 193messages .insert (0 , {"role" :"system" ,"content" :directive }) 194return 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 199from its first `{`. Empty when there is nothing to take. The server's json_schema logprobs 200alignment reads the model's own JSON form with it.""" 201s = (text or "" ).strip () 202if not s : 203return "" 204if s .startswith ("```" ): 205first = s .find ("\n" ) 206if first != - 1 : 207end = s .find ("```" ,first + 1 ) 208if end != - 1 : 209s = s [first + 1 :end ].strip () 210start = s .find ("{" ) 211if start == - 1 : 212return s 213depth = 0 214in_str = False 215esc = False 216for i in range (start ,len (s )): 217ch = s [i ] 218if in_str : 219if esc : 220esc = False 221elif ch == "\\" : 222esc = True 223elif ch == "\"" : 224in_str = False 225else : 226if ch == "\"" : 227in_str = True 228elif ch == "{" : 229depth += 1 230elif ch == "}" : 231depth -= 1 232if depth == 0 : 233return s [start :i + 1 ] 234return s [start :] 235 236 237def validated_json (text ,validator ,finish ): 238def pairs (items ): 239obj = {} 240for key ,value in items : 241if key in obj : 242raise ValueError (f"duplicate JSON key: { key } " ) 243obj [key ]= value 244return obj 245 246def constant (value ): 247raise ValueError (f"invalid JSON constant: { value } " ) 248 249if finish != "stop" : 250raise StructuredOutputError (f"structured output was incomplete (finish_reason= { finish } ); increase the output budget" ) 251try : 252value = json .loads (extract_json (text ),object_pairs_hook = pairs ,parse_constant = constant ) 253canonical = json .dumps (value ,ensure_ascii = False ,allow_nan = False ,separators = ("," ,":" )) 254except (ValueError ,TypeError )as exc : 255value = None 256if getattr (validator ,"repair_escapes" ,False ):# opt-in (#2893); only after the strict parse failed 257try : 258value = json .loads (repair_latex_escapes (extract_json (text )),object_pairs_hook = pairs , 259parse_constant = constant ) 260canonical = json .dumps (value ,ensure_ascii = False ,allow_nan = False ,separators = ("," ,":" )) 261"[strata] structured output: repaired backslashes that were not valid JSON escapes" ,flush = True ) 262except (ValueError ,TypeError ): 263value = None 264if value is None : 265raise StructuredOutputError (f"model did not return valid JSON: { exc } " )from exc 266try : 267error = next (validator .iter_errors (value ),None ) 268except Exception as exc : 269raise StructuredOutputError (f"could not validate structured output: { exc } " )from exc 270if error is not None : 271path = "/" + "/" .join (str (part )for part in error .absolute_path ) 272raise StructuredOutputError (f"model output failed the JSON Schema at { path } : { error . message } " ) 273return canonical