Introduction
In our last lesson, we built a system to detect when an agent's output is unfaithful to its source context, tackling the critical problem of hallucinations. This detection capability is the "sensor" in our safety system. Now, we will build the "actuator": the output guardrails that enforce corrective action based on validation results. This lesson is about moving from simply identifying problems to systematically preventing them from reaching the user or triggering downstream actions.
Our objective is to implement a multi-layered guardrail system to enforce structural, format, and content policy constraints on our agent's final output. For the production-grade systems you aim to engineer, this is a non-negotiable component. It ensures that every piece of data leaving the agent is not only factually grounded (as we checked previously) but also well-formed, compliant, and safe. We will build these guardrails from first principles, focusing on the underlying mechanisms that guarantee reliability.
The Three Levels of Output Validation
A robust output guardrail system operates at multiple levels, much like network security or data validation pipelines in traditional software engineering. Each layer addresses a different class of potential errors.

This flowchart illustrates a sequential validation process. We will implement each of these three levels, starting with basic parsing and moving to complex business logic, to ensure our agent's output is production-ready.
- Level 1: Parse JSON (Structural Constraint): Can the output be parsed at all? This catches basic syntax errors and ensures the output is a valid JSON object.
- Level 2: Check Schema (Format Constraint): Does the parsed object have the right fields, data types, and formats? Are strings within length limits? Are numbers in the correct range? Is an email field actually a valid email?
- Level 3: Validate Business Logic (Content Constraint): Does the content of the fields make sense in the context of our application? Does it violate any content policies (e.g., mentioning a competitor, giving medical advice)?
While many systems stop at Level 1, a production-grade agent must enforce all three.
Levels 1 & 2: Enforcing Structure and Format with Schema-Constrained Generation
Relying on an LLM to "please return a JSON object" and then parsing the resulting string is brittle and prone to failure. Given your background in distributed systems, you're familiar with the necessity of well-defined schemas (like Protobuf or Avro) for reliable communication. We apply the same principle here.
The most robust method for enforcing structural and format constraints is schema-constrained generation. This isn't a post-processing step; it's a fundamental change to how the LLM generates tokens.
LLM Structured Output in 2026: Stop Parsing JSON with Regex and ...
This article provides an excellent first-principles explanation of why structured output is crucial and how it works under the hood.
Please read the first three sections: Start with the introduction to understand the six dangerous assumptions we make when parsing raw LLM responses. Continue through The Three Levels of Output Control, which contrasts basic prompting with the guarantees of native structured output. Finally, read How it Works. Pay close attention to the explanation of constrained decoding and the Finite State Machine (FSM). This is the core mechanism that allows the model to guarantee a schema-valid output by masking invalid tokens at each generation step.
As the article explains, modern LLM APIs (from OpenAI, Anthropic, etc.) can accept a schema and use constrained decoding to force the output to conform to it. For defining these schemas in Python, the industry standard is Pydantic. It allows us to define data structures as Python classes, which can then be used to both generate and validate data.
The following video provides a practical overview of implementing structured output with OpenAI's API and Pydantic, which is the pattern we will adopt.
OpenAI Structured Output - All You Need to Know
This video from Dave Ebbelaar demonstrates the recommended Pydantic-based approach to structured output.
Watch the segment on you're good to go to see how a complex JSON schema can be represented concisely and readably as a set of Pydantic classes. Note how extending the model with a new confidence field is trivial. Then, review the system design for key tips, reinforcing the value of using Pydantic models and descriptive fields.
Level 3: Enforcing Content and Business Logic
A valid schema is necessary but not sufficient. An agent could produce a perfectly-formed output that still violates critical business rules. For example:
- An agent might be prohibited from mentioning competitor names.
- A financial agent should not generate investment advice.
- A customer service agent should not leak internal-only pricing information.
These content-based rules require a higher level of validation. We can implement this in two main ways.
1. Schema-Based Content Enforcement
For simple content policies, we can use clever schema definitions. For instance, to prevent the model from mentioning competitors, we can define a field for it and constrain it to be empty.
LLM Guardrails That Actually Work in Production | Kalvium Labs
This article from Kalvium Labs details production-tested guardrail techniques.
Read the subsection Structured Output Enforcement. Pay attention to the code example that uses maxItems: 0 on the mentioned_competitors field. This is a powerful technique that forces a validation failure at the generation stage if the model attempts to fill that field, acting as a "canary" for a policy breach.
2. Post-Generation Validation: The "Validation Sandwich"
For more complex policies, we need to analyze the generated content after the fact. This brings us to a robust production pattern called the Validation Sandwich.

The process is:
- Top Slice (Generation): Call the LLM with schema-constrained generation to produce a structurally and formally valid object.
- Filling (Validation): Re-validate the generated object using more powerful tools that can express complex business logic.
- Bottom Slice (Usage): Only use the object if it passes the second validation step.
Pydantic is perfect for this second step. In addition to basic type hints, it provides powerful decorators like @field_validator and @model_validator that allow you to implement arbitrary validation logic.
LLM Structured Output in 2026: Stop Parsing JSON with Regex and ...
Let's revisit the article on structured output to see this pattern in action.
Read the section titled Pattern 1: The Validation Sandwich. The key insight here is that you call ProductReview.model_validate() on the parsed result. This second validation pass is where you can catch business logic violations (like a generic title) that the initial JSON Schema compliance check cannot.
To learn more about implementing these advanced Pydantic validators, the official documentation and tutorials are excellent resources. This video provides a comprehensive guide.
Python Pydantic Tutorial: Complete Data Validation Course (Used by FastAPI)
This comprehensive Pydantic tutorial by Corey Schafer is a great reference for mastering data validation.
For this lesson, focus on two key concepts: that we're using here: This section introduces Annotated and Field for adding constraints like value ranges (gt, le) and regex patterns. This is key for Level 2 (Format) validation. fields during validation: This segment explains how to create custom logic with @field_validator for single fields and @model_validator for cross-field validation (e.g., ensuring password and confirm_password match). This is the mechanism for our Level 3 (Content/Business Logic) validation.
Implementation: A Multi-Layered Output Guardrail
Let's synthesize these concepts into a reusable OutputGuardrail class. This component will take a Pydantic model and a list of custom content policies. Its job is to ensure that an LLM's output satisfies all three levels of validation.
We'll define custom exception types to clearly signal what kind of validation failed, which is crucial for the agent loop to decide on a recovery strategy (e.g., retry, escalate to human).
import openai
import re
from pydantic import BaseModel, Field, field_validator, ValidationError, EmailStr
from enum import Enum
from typing import Type, TypeVar, Generic, List
# --- Custom Exceptions for Clear Error Handling ---
class GuardrailViolationError(Exception):
"""Base exception for all guardrail violations."""
pass
class StructuralError(GuardrailViolationError):
"""Failed to parse the LLM output as JSON."""
pass
class FormatError(GuardrailViolationError):
"""The parsed JSON does not conform to the Pydantic model's format constraints."""
pass
class ContentError(GuardrailViolationError):
"""The validated content violates a custom business rule or policy."""
pass
# --- Define a Pydantic Schema for a Customer Service Agent's Response ---
# This schema enforces Level 1 (JSON) and Level 2 (Format) constraints.
class Sentiment(str, Enum):
POSITIVE = "positive"
NEUTRAL = "neutral"
NEGATIVE = "negative"
class CustomerServiceResponse(BaseModel):
response_text: str = Field(
...,
max_length=500,
description="The final response to send to the customer."
)
sentiment: Sentiment = Field(
...,
description="The sentiment of the generated response."
)
escalate_to_human: bool = Field(
...,
description="True if the query requires human intervention."
)
# Level 3 (Business Logic) constraint implemented via Pydantic validator
@field_validator('response_text')
@classmethod
def no_competitor_mentions(cls, v: str) -> str:
competitors = ["compete_corp", "rival_inc"]
if any(competitor in v.lower() for competitor in competitors):
raise ValueError("Response mentions a competitor.")
return v
# --- A Generic Guardrail Class ---
T = TypeVar('T', bound=BaseModel)
class OutputGuardrail(Generic[T]):
def __init__(self, model: Type[T], content_policies: List[callable] = None):
"""
Initializes the guardrail with a Pydantic model and optional content policies.
:param model: The Pydantic model for schema validation.
:param content_policies: A list of functions, each taking the validated data
and raising a ContentError if a policy is violated.
"""
self.model = model
self.content_policies = content_policies or []
self.client = openai.OpenAI()
def validate(self, llm_output_str: str) -> T:
"""
Applies the full validation pipeline to a raw LLM output string.
"""
# Level 1: Parse JSON (Implicitly handled by Pydantic's JSON parsing)
# Level 2 & 3 (Pydantic): Validate schema, format, and Pydantic-based business logic
try:
# model_validate_json handles both parsing and validation
validated_data = self.model.model_validate_json(llm_output_str)
except ValueError as e: # Catches both JSON parsing and Pydantic validation errors
if "JSON" in str(e):
raise StructuralError(f"Failed to parse LLM output as JSON: {e}") from e
raise FormatError(f"Schema validation failed: {e}") from e
# Level 3 (Custom Policies): Run additional, complex content policies
for policy in self.content_policies:
try:
policy(validated_data)
except ValueError as e:
raise ContentError(f"Content policy violation: {e}") from e
return validated_data
# --- Example Usage ---
# A custom content policy function not expressible in Pydantic alone
def prevent_financial_advice(data: CustomerServiceResponse):
financial_keywords = ["invest", "stock", "portfolio", "return"]
if any(keyword in data.response_text.lower() for keyword in financial_keywords):
raise ValueError("Response appears to give financial advice.")
# Instantiate the guardrail
guardrail = OutputGuardrail(
model=CustomerServiceResponse,
content_policies=[prevent_financial_advice]
)
# --- Simulate LLM Outputs ---
# 1. Valid output
valid_output = """
{
"response_text": "We're sorry for the trouble with your order. We have processed your refund.",
"sentiment": "neutral",
"escalate_to_human": false
}
"""
# 2. Format violation (sentiment is not a valid enum member)
format_violation_output = """
{
"response_text": "Thanks for your feedback!",
"sentiment": "grateful",
"escalate_to_human": false
}
"""
# 3. Pydantic validator violation (mentions competitor)
pydantic_content_violation_output = """
{
"response_text": "Our product is much better than Rival_Inc's offering.",
"sentiment": "positive",
"escalate_to_human": false
}
"""
# 4. Custom content policy violation (gives financial advice)
custom_content_violation_output = """
{
"response_text": "To get a good return, you should invest in our new stock options.",
"sentiment": "positive",
"escalate_to_human": false
}
"""
# --- Run Validations ---
print("--- Testing Guardrails ---")
try:
print("\n1. Testing valid output:")
validated = guardrail.validate(valid_output)
print(f" ✅ Success! Validated data: {validated.model_dump_json(indent=2)}")
print("\n2. Testing format violation:")
guardrail.validate(format_violation_output)
except GuardrailViolationError as e:
print(f" ❌ Caught expected error: {type(e).__name__} - {e}")
try:
print("\n3. Testing Pydantic content violation:")
guardrail.validate(pydantic_content_violation_output)
except GuardrailViolationError as e:
print(f" ❌ Caught expected error: {type(e).__name__} - {e}")
try:
print("\n4. Testing custom content policy violation:")
guardrail.validate(custom_content_violation_output)
except GuardrailViolationError as e:
print(f" ❌ Caught expected error: {type(e).__name__} - {e}")
This implementation creates a clean separation of concerns. The Pydantic model handles all schema-level validation, while the OutputGuardrail class orchestrates the process and applies additional, more dynamic content policies. The custom exceptions provide clear signals to the calling agent loop about why an output failed, enabling more intelligent recovery logic.
Conclusion
In this lesson, we have constructed a multi-layered defense for our agent's output. By moving beyond simple string parsing and embracing schema-constrained generation, we have built a foundation of reliability. We've seen how to enforce rules at every level, from basic syntax to complex business logic, creating a comprehensive safety net.
Key Takeaways:
- Output guardrails operate on three levels: structural (valid JSON), format (schema compliance), and content (business rules).
- Schema-constrained generation is the most robust method for enforcing structural and format constraints, using tools like Pydantic to define schemas.
- The "Validation Sandwich" is a key production pattern: generate with schema constraints, then re-validate the parsed object with more advanced business logic before use.
- Pydantic offers powerful tools for all levels of validation: from basic type hints and
Fieldconstraints to custom@field_validatordecorators for expressing complex rules. - A well-designed guardrail system uses custom exceptions to signal specific failure modes, enabling intelligent error handling and recovery in the agent loop.
Preview of the Next Lesson:
Our guardrails can now block or flag invalid or unsafe outputs. But what about actions that are valid and safe, but have high stakes? For example, an agent might correctly formulate a request to delete a customer's account. This action is well-formed and doesn't violate a content policy, but we might not want it to happen autonomously. In our next lesson, we will design and implement human-in-the-loop approval gates, which pause the agent's execution for high-stakes actions and await explicit confirmation from a human operator.