LLM Output Validation Pipeline: From Schema to Business Rules
When LLMs are used in production, it's not enough to simply get a response. You need to ensure that the response conforms to the expected structure and business rules. In this article, I describe a multi-level validation pipeline that I use in my projects.
Why Multi-Level Validation Is Needed
LLMs are probabilistic systems. Even when using structured output or function calling, the model may return data that formally conforms to the schema but fails business checks. For example, a date in the past, a negative price, or a link to a non-existent product. Single-level validation does not cover all cases. Therefore, I build a pipeline with several stages.
Level 1: Structural Validation
The first stage is JSON Schema validation. This is the fastest and cheapest way to catch obvious errors.
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"product_id": {"type": "integer"},
"price": {"type": "number", "minimum": 0},
"in_stock": {"type": "boolean"}
},
"required": ["product_id", "price", "in_stock"]
}
try:
validate(instance=llm_output, schema=schema)
except ValidationError as e:
handle_error(e)
Level 2: Semantic Validation
The structure is correct, but values may be meaningless. At this stage, I check: - date and time formats; - number ranges; - email and URL formats; - presence of required fields based on context.
def validate_semantics(data):
errors = []
if data["price"] > 1000000:
errors.append("Price exceeds maximum allowed value")
if not is_valid_date(data["release_date"]):
errors.append("Invalid release date format")
return errors
Level 3: Business Rules
The most important level. Here, rules specific to your domain are checked. For example: - the product with the specified ID exists in the database; - the discount amount does not exceed the cost; - the order status corresponds to a valid transition. To check for the existence of data, I make requests to the database or API. This stage is the slowest, so it should only be executed after successfully passing the first two levels.
Level 4: LLM-as-a-Judge
For complex cases where rules are hard to formalize, I use LLM-as-a-Judge. For example, checking the tone of the response or compliance with brand style.
def judge_response(response):
judge_prompt = f"""Evaluate if the response meets the requirements:
Requirements: {requirements}
Response: {response}
Return JSON: {"is_valid": bool, "reason": str}"""
# call LLM
Error Handling and Retries
Upon detecting an error, it's not always necessary to immediately fail. The strategy depends on the type of error. | Error Type | Action | |---|---| | Schema Error | Retry with clarification | | Semantic Error | Retry with error indication | | Business Rule Violation | Reject or manual handling | | Judge Error | Manual verification | Upon retry, I pass the model an error message. This often helps correct the output without changing the prompt.
Tools and Libraries
To implement the pipeline, I use: - Pydantic for validation and parsing; - JSON Schema for describing structures; - custom functions for business rules; - observability system for logging errors.
Conclusion
Multi-level validation is an essential part of LLM production systems. It allows you to catch most errors before they reach the user. Start with the first two levels, then add business rules and judges. This pays off in reduced incidents and increased trust in the system.