A support assistant asks a language model for a ticket as JSON, and the code after it needs that JSON to match a schema exactly. Write the validator for a small JSON Schema subset, with an error message per problem that names its JSON path, and the loop that sends those errors back to the model until the reply is valid or the attempts run out.
Implement two functions.
validate(value, schema, path="$") returns the list of error strings for value (a parsed JSON value) against schema. Every error is "<path>: <message>". The root path is $; an object property adds .<key> and an array element adds [<index>], so a path looks like $.items[2].qty.
The JSON type of a value: None is null, bool is boolean, int is integer, float is number, str is string, list is array, dict is object. A schema may hold these keywords, checked in this order:
type (one of "object", "array", "string", "number", "integer", "boolean"): if the value does not have it, report expected <type>, got <json type of value> and check nothing else at this path or below. "number" accepts integers and numbers; "integer" accepts only int (not bool, not 3.0).enum: the value must equal (==) an entry with the same JSON type, else must be one of <json.dumps(enum)>.minimum, then maximum (inclusive), only when the value is an integer or number: must be >= <json.dumps(minimum)>, must be <= <json.dumps(maximum)>.missing required property '<name>' for each name in required, in list order; then, only if additionalProperties is False, unexpected property '<key>' for each key not in properties, in the value's key order; then the errors of each key that is in properties, in the value's key order, validated against its subschema.items: the errors of each element against items, in index order.structured_call(model, prompt, schema, max_attempts). model is a callable model(prompt: str) -> str (scripted in the tests). For each attempt, call it and get the JSON out of the reply:
```[A-Za-z]*[ \t]*\n(.*?)``` (with re.DOTALL), the text is the first block's inside; otherwise the text is the whole reply.{ or [ of the text, whichever comes first, with json.JSONDecoder().raw_decode. Whatever follows the value is ignored.{ or [ gives the single error $: no JSON found in reply; a decode failure gives $: reply is not valid JSON. Otherwise the errors are validate(value, schema).If there are no errors, stop. Otherwise the next prompt is the original prompt followed by the errors of this attempt only:
prompt + "\n\nYour previous reply was invalid:\n" + "- <error>\n" for each error, in order, + "Reply with corrected JSON only."
Never make more than max_attempts (at least 1) calls. Return {"ok": bool, "value": parsed value or None, "attempts": number of calls made, "errors": [the error list of each attempt, in order]}.