Overview
The Schema Validator module provides JSON Schema Draft 2020-12 validation utilities for validating payloads and schemas, and integrating validation failures into the Guardrails re-ask pipeline.
Description
This module provides multiple layers of JSON Schema validation:
SchemaValidationError is a custom exception class that carries a fields dictionary mapping JSON Paths to lists of error messages, enabling detailed per-field error reporting.
validate_against_schema iterates over validation errors produced by a Draft202012Validator, collecting them by JSON Path. When validate_subschema is enabled, "required property" errors are skipped to allow partial payloads.
validate_json_schema validates a JSON Schema itself against the JSON Schema Draft 2020-12 meta-schema, ensuring that user-provided schemas are structurally correct.
validate_payload validates a data payload against a provided JSON Schema by constructing a Draft202012Validator with a referencing.Registry for proper $ref resolution.
schema_validation is the integration point for the Guardrails pipeline: it validates LLM output against an output schema and, on failure, returns a SkeletonReAsk object containing a FailResult with the formatted error details, triggering the re-ask mechanism.
Usage
Use this module to validate LLM output against JSON Schemas within the Guardrails validation pipeline. The schema_validation function is called automatically during guard execution. Use validate_payload or validate_json_schema directly when you need standalone schema validation outside the guard pipeline.
Code Reference
Source Location
- Repository: Guardrails
- File:
guardrails/schema/validator.py
Signature
class SchemaValidationError(Exception):
fields: Dict[str, List[str]]
def __init__(self, *args: object, fields: Dict[str, List[str]])
def validate_against_schema(
payload: Any,
validator: Draft202012Validator,
*,
validate_subschema: Optional[bool] = False,
)
def validate_json_schema(json_schema: Dict[str, Any])
def validate_payload(
payload: Any,
json_schema: Dict[str, Any],
*,
validate_subschema: Optional[bool] = False,
)
def schema_validation(
llm_output: Any,
output_schema: Dict[str, Any],
**kwargs,
) -> Optional[SkeletonReAsk]
Import
from guardrails.schema.validator import (
SchemaValidationError,
validate_against_schema,
validate_json_schema,
validate_payload,
schema_validation,
)
I/O Contract
validate_against_schema
| Parameter |
Type |
Description
|
payload |
Any |
The data payload to validate
|
validator |
Draft202012Validator |
A configured JSON Schema validator instance
|
validate_subschema |
Optional[bool] |
If True, skips "required property" errors to allow partial payloads
|
| Raises |
Description
|
SchemaValidationError |
Raised with fields dict mapping JSON Paths to error messages when validation fails
|
validate_json_schema
| Parameter |
Type |
Description
|
json_schema |
Dict[str, Any] |
The JSON Schema to validate against the Draft 2020-12 meta-schema
|
| Raises |
Description
|
SchemaValidationError |
Raised when the schema does not conform to JSON Schema Draft 2020-12
|
validate_payload
| Parameter |
Type |
Description
|
payload |
Any |
The data payload to validate
|
json_schema |
Dict[str, Any] |
The JSON Schema to validate against
|
validate_subschema |
Optional[bool] |
If True, skips "required property" errors
|
| Raises |
Description
|
SchemaValidationError |
Raised with per-field error messages when validation fails
|
schema_validation
| Parameter |
Type |
Description
|
llm_output |
Any |
The LLM output to validate
|
output_schema |
Dict[str, Any] |
The JSON Schema defining the expected output structure
|
**kwargs |
Any |
Additional options; supports validate_subschema: bool
|
| Returns |
Type |
Description
|
| Re-ask object |
Optional[SkeletonReAsk] |
A SkeletonReAsk with a FailResult if validation fails, or None if validation passes
|
Usage Examples
from guardrails.schema.validator import validate_payload, schema_validation, SchemaValidationError
# Validate a payload against a schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
}
try:
validate_payload({"name": "Alice", "age": 30}, schema)
print("Payload is valid!")
except SchemaValidationError as e:
for path, errors in e.fields.items():
print(f"{path}: {errors}")
# Integration with the Guardrails re-ask pipeline
llm_output = {"name": "Alice", "age": "not a number"}
result = schema_validation(llm_output, schema)
if result is not None:
# result is a SkeletonReAsk with FailResult details
print(result.fail_results[0].error_message)
Related Pages