Reference · Snippet · python

Validate JSON from LLM

Last updated

pythonjsonstructured-output

import json
from jsonschema import validate, ValidationError

SCHEMA = {
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "tags": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["title", "tags"],
}

def parse_model_json(raw: str) -> dict:
    data = json.loads(raw)  # raises JSONDecodeError if invalid
    validate(instance=data, schema=SCHEMA)
    return data

try:
    obj = parse_model_json(model_text)
except (json.JSONDecodeError, ValidationError) as e:
    # retry with repair prompt or return 422 to client
    raise