How to Validate Structured LLM Output
Summary
Configure JSON response validation from LLMs using JSON Schema to ensure data structure correctness before application use.
Problem
LLMs often return JSON with errors: missing fields, incorrect types, extra keys, and invalid values. Passing such a response to code without validation can cause the application to crash or receive garbage data. Validation at the response stage solves this problem.
Step 1. Define the Response Schema
Create a JSON Schema for the expected output:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"title": {"type": "string", "minLength": 1},
"price": {"type": "number", "minimum": 0},
"category": {"type": "string", "enum": ["electronics", "books", "clothing"]},
"in_stock": {"type": "boolean"},
"tags": {"type": "array", "items": {"type": "string"}, "maxItems": 10}
},
"required": ["title", "price", "category", "in_stock"],
"additionalProperties": false
}
Step 2. Use a Validation Library
In Python, use jsonschema:
pip install jsonschema
import json
import jsonschema
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"title": {"type": "string"},
"price": {"type": "number"}
},
"required": ["title", "price"]
}
def validate_llm_response(response_text: str) -> dict:
try:
data = json.loads(response_text)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON: {e}")
try:
validate(instance=data, schema=schema)
except jsonschema.ValidationError as e:
raise ValueError(f"Schema validation failed: {e.message}")
return data
Step 3. Integrate Validation with LLM Call
import requests
def get_structured_response(prompt: str) -> dict:
response = requests.post(
"https://api.openrouter.ai/api/v1/chat/completions",
headers={"Authorization": "Bearer YOUR_KEY"},
json={
"model": "openai/gpt-4o-mini",
"messages": [
{"role": "system", "content": "Return JSON with fields: title, price, category, in_stock"},
{"role": "user", "content": prompt}
],
"response_format": {"type": "json_object"}
}
)
content = response.json()["choices"][0]["message"]["content"]
return validate_llm_response(content)
Step 4. Handle Validation Errors
On schema mismatch, send a retry request with the error indication:
def get_validated_response(prompt: str, max_retries: int = 3) -> dict:
for attempt in range(max_retries):
try:
return get_structured_response(prompt)
except ValueError as e:
if attempt == max_retries - 1:
raise
prompt = f"{prompt}\n\nPrevious response was invalid: {e}. Please fix and return valid JSON."
raise RuntimeError("Failed to get valid response")
Step 5. Use Pydantic for Typing
For complex structures, Pydantic is more convenient:
from pydantic import BaseModel, Field
class Product(BaseModel):
title: str = Field(min_length=1)
price: float = Field(ge=0)
category: str
in_stock: bool
def validate_with_pydantic(data: dict) -> Product:
return Product(**data)
Step 6. Test Validation
```python import unittest
class TestValidation(unittest.TestCase): def test_valid_response(self): data = validate_llm_response('{