Validating Tool Outputs (Pydantic)
Parse every tool output through a Pydantic model — fail loud on a malformed response.
Validating Tool Outputs (Pydantic) is a free AI Agents lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Trust But Verify
Tool outputs come from the outside world — APIs, web pages, models. A malformed or unexpected response can crash your agent or, worse, silently feed bad data into the LLM.
Validate every tool output against a schema.
Pydantic Models
Define expected shapes:
from pydantic import BaseModel, HttpUrl
class SearchResult(BaseModel):
title: str
url: HttpUrl
snippet: str
score: float = 0.0Validate at the Boundary
from pydantic import ValidationError
def search(query):
raw = requests.post('https://api.tavily.com/search', json={'query': query}).json()
results = []
for r in raw.get('results', []):
try:
results.append(SearchResult.model_validate(r))
except ValidationError as e:
log.warning('Bad search result skipped: %s', e)
return resultsLists with Model Validation
Validate the entire response:
from pydantic import BaseModel
class SearchResponse(BaseModel):
results: list[SearchResult]
response = SearchResponse.model_validate(raw)Field Validators
Custom checks inside fields:
from pydantic import field_validator
class SearchResult(BaseModel):
score: float
@field_validator('score')
@classmethod
def score_in_range(cls, v):
if not 0 <= v <= 1:
raise ValueError('score out of [0,1]')
return vStrict vs Lenient
By default Pydantic coerces types (string -> int when possible). For strict checks:
from pydantic import StrictInt
class User(BaseModel):
age: StrictInt # rejects '25' (string)Default Values for Missing Fields
class Tool(BaseModel):
name: str
description: str = 'No description provided' # fallbackValidate LLM Structured Output
Force the model to return JSON that fits a Pydantic schema — see the Structured Outputs lesson. Validate again at the boundary as defense in depth.
Validate Tool Arguments
Validate the model's tool_call.arguments before executing:
class SearchArgs(BaseModel):
query: str
k: int = 5
args = SearchArgs.model_validate_json(tool_call.function.arguments)
results = search(args.query, args.k)Validation Errors as Tool Results
If validation fails, return the error to the model so it can retry with corrected arguments:
try:
args = SearchArgs.model_validate_json(...)
except ValidationError as e:
return {'error': f'Invalid arguments: {e}'}Schema Versioning
When a tool's output schema changes, version it:
class SearchResultV2(BaseModel):
title: str
url: HttpUrl
relevance: float # was 'score' in v1Generate JSON Schema From Pydantic
For tool schema definitions, derive from your Pydantic class:
schema = SearchArgs.model_json_schema()
# Use directly as the 'parameters' for an OpenAI tool definition.Validation Goal
Why use Pydantic on every tool output?
Recap
Pydantic at every boundary: tool arguments going in, tool outputs coming out, LLM structured outputs. Loud failures beat silent corruption.
Frequently asked questions
Is the “Validating Tool Outputs (Pydantic)” lesson free?
Yes — the full text of “Validating Tool Outputs (Pydantic)” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Validating Tool Outputs (Pydantic)”?
Parse every tool output through a Pydantic model — fail loud on a malformed response. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Validating Tool Outputs (Pydantic)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Idempotent Tools and Side Effects
- Retries with Exponential Backoff
- Timeouts and Circuit Breakers
- Validating Tool Outputs (Pydantic)