Skip to main content
Tool validation ensures data integrity by enforcing schemas before tools execute. Pydantic validators catch invalid input from LLMs, preventing errors and hallucinations from reaching your tool logic.

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)
Validators enforce constraints at the schema level, giving the LLM immediate feedback to retry with correct inputs.

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.

See Also

Tool Best Practices

General best practices for tool design

Pydantic Validators

Official Pydantic validators documentation

Agent Guardrails

Validate agent inputs and outputs with guardrails

Tool Configuration

Configure tool behavior and parameters