Custom Validators for Domain-Specific Rules
What you'll learn: How to create custom validation logic that enforces business rules like content filters, user permissions, and quota limits in your LLM API.
Why Standard Validation Isn't Enough
Pydantic validates data types and basic constraints (like string length), but your LLM application has unique business rules that go beyond "is this an integer?" You might need to verify that a user hasn't exceeded their monthly token quota, that content doesn't violate policies, or that a request is authorized for specific features.
Creating Custom Validators
Think of custom validators as security guards at different checkpoints. Each guard checks for specific rules before letting a request through.
You implement these by extending your existing Pydantic validation with domain-specific logic:
from pydantic import BaseModel, field_validator, model_validator
class LLMRequest(BaseModel):
prompt: str
user_id: str
max_tokens: int
@field_validator('prompt')
@classmethod
def check_content_policy(cls, v):
banned_words = ['spam', 'malicious']
if any(word in v.lower() for word in banned_words):
raise ValueError('Content violates policy')
return v
@model_validator(mode='after')
def check_user_quota(self):
# Check if user has tokens remaining
if not has_quota(self.user_id, self.max_tokens):
raise ValueError('User quota exceeded')
return self
Common Business Rules to Validate
- Content filtering: Block prohibited terms, detect sensitive data
- Permission checks: Verify user access to specific models or features
- Quota enforcement: Limit tokens, requests per minute, or cost thresholds
- Rate limiting validation: Check if user is within allowed request frequency
- Context window limits: Ensure prompt + history fits model constraints
Key Takeaway: Custom validators let you enforce business logic and domain rules at the request validation layer, preventing invalid or unauthorized LLM requests before they reach your models or incur costs.