Recipe: validate JSON output against a schema
Recipe — validate JSON outputs against a strict schema using a custom judge or pre-evaluation validation.
Pattern A — pre-evaluation validation (cheapest)
import json, jsonschema
from layerlens import Stratix
schema = {
"type": "object",
"properties": {
"answer": {"type": "string"},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
},
"required": ["answer", "confidence"],
"additionalProperties": False,
}
client = Stratix()
def trace_with_schema_check(model_output: dict, **trace_kwargs):
try:
jsonschema.validate(instance=model_output, schema=schema)
except jsonschema.ValidationError as e:
# Tag failed traces explicitly so you can filter them downstream
trace_kwargs.setdefault("tags", {})["schema_valid"] = False
trace_kwargs["tags"]["schema_error"] = str(e)
else:
trace_kwargs.setdefault("tags", {})["schema_valid"] = True
return client.traces.upload(...) # your trace upload pathPattern B — custom judge that scores schema conformance
See also
Last updated
Was this helpful?