How to validate agent tool inputs in python
Quick answer
Use Python's type hints combined with runtime checks or schema validation libraries like
pydantic to validate agent tool inputs. This ensures inputs meet expected formats and types before processing, preventing runtime errors and improving reliability.PREREQUISITES
Python 3.8+pip install pydantic
Setup
Install pydantic for schema validation and ensure you have Python 3.8 or higher.
pip install pydantic Step by step
Define a pydantic.BaseModel schema for your agent tool inputs, then validate inputs by instantiating the model. Catch validation errors to handle invalid inputs gracefully.
from pydantic import BaseModel, ValidationError
class ToolInput(BaseModel):
query: str
max_results: int = 5
def validate_tool_input(data: dict) -> ToolInput:
try:
validated = ToolInput(**data)
print("Validation successful:", validated)
return validated
except ValidationError as e:
print("Validation error:", e)
raise
# Example usage
input_data = {"query": "Find AI tutorials", "max_results": 3}
validate_tool_input(input_data)
# Invalid input example
invalid_data = {"query": 123, "max_results": "many"}
try:
validate_tool_input(invalid_data)
except ValidationError:
pass output
Validation successful: query='Find AI tutorials' max_results=3 Validation error: 2 validation errors for ToolInput query str type expected (type=type_error.str) max_results value is not a valid integer (type=type_error.integer)
Common variations
You can use Python's built-in typing module for simple type checks or integrate validation in async agents. For streaming inputs, validate chunks incrementally. Different models or frameworks may require adapting validation schemas accordingly.
from typing import Optional
from pydantic import BaseModel
class AsyncToolInput(BaseModel):
query: str
max_results: Optional[int] = 5
# Async validation example (simplified)
import asyncio
async def async_validate(data: dict):
return AsyncToolInput(**data)
async def main():
data = {"query": "Async example"}
validated = await async_validate(data)
print(validated)
asyncio.run(main()) output
query='Async example' max_results=5
Troubleshooting
If you see ValidationError, check that input keys match schema fields and types exactly. Use detailed error messages from pydantic to pinpoint issues. For missing fields, provide defaults or mark them optional.
Key Takeaways
- Use
pydanticmodels to enforce input types and constraints for agent tools. - Catch and handle validation errors to prevent runtime failures in your agent workflows.
- Adapt validation schemas for async or streaming input scenarios to maintain robustness.