Why Validate Tool Inputs
Without validation, LLMs may provide:- Malformed data (e.g., text in numeric fields)
- Out-of-range values (e.g., negative ages, future dates in the past)
- Invalid formats (e.g., malformed emails, incorrect URLs)
- Inconsistent field combinations (e.g., mismatched passwords)
Field Validators
Field validators check individual fields independently. Use@field_validator to validate a single field’s value.
Basic Field Validation
Multiple Field Validation
Validate multiple fields with a single validator:Format Validation
Validate specific formats like URLs or emails:Model Validators
Model validators validate the entire model, enabling checks across multiple fields. Use@model_validator when field validation depends on other fields.
Cross-Field Validation
Date Range Validation
Conditional Validation
Best Practices
Specific Error Messages
Provide clear, actionable error messages that guide the LLM to correct inputs.
Fail Fast
Validate at the schema level before expensive operations or external API calls.
Normalize Input
Use validators to clean and normalize data (e.g., strip whitespace, lowercase emails).
Test Validators
Write unit tests for validators to ensure they catch invalid cases and allow valid ones.