Pydantic BaseModels as Tool Arguments: Enforcing Complex Validations
Passing Pydantic models into ADK tool signatures: how nested schemas reach the model, field constraints and validators, error messages the model can repair from, and separating the wire schema from your domain model.
Published on • November 27, 2026
AI Assistant

Flat parameters work until the data stops being flat. order_id: str is fine; a booking with dates, line items, contact details, and an address is not — and squeezing it into eight scalar arguments produces a schema the model fills in badly.
Pydantic models are ADK’s answer: annotate a parameter with a BaseModel subclass and the framework nests the model’s schema inside the tool declaration, then constructs a real instance of your class before your function runs. This post covers how that pipeline works, how to use constraints and validators so problems are caught before they hit your API, and how to keep the schema the model sees from leaking into the rest of your codebase.
The pattern
import pydantic
from google.adk import Agent
class Address(pydantic.BaseModel):
line1: str
city: str
postal_code: str = pydantic.Field(pattern=r'^\d{5}$')
class BookingRequest(pydantic.BaseModel):
"""A request to create a hotel booking."""
guest_name: str
check_in: pydantic.date
check_out: pydantic.date
rooms: int = pydantic.Field(default=1, ge=1, le=6)
address: Address
def create_booking(request: BookingRequest) -> dict:
"""Create a hotel booking for a guest.
Args:
request (BookingRequest): The booking details to confirm.
"""
...
What happens under the hood:
- ADK converts
BookingRequestinto a JSON schema and nests it under therequestparameter in the tool declaration. - The model produces JSON matching that schema.
- ADK constructs a
BookingRequestinstance (validating as it goes) and passes the object to your function —request.roomsis anint, not a string you have to coerce.
You get the best of both: a schema the model understands and a type your function can trust.
Constraints do the model’s arguing for you
Field constraints are the cheapest form of validation, because they show up in the schema the model reads:
class TicketInput(pydantic.BaseModel):
urgency: int = pydantic.Field(ge=1, le=5)
category: str = pydantic.Literal['refund', 'shipping', 'defect', 'question']
priority_note: str | None = None
ge/le/gt/ltbound numeric ranges.Literal[...]andEnumfields give the model an explicit choice list — dramatically better than “urgency 1-5” written in prose somewhere in the docstring.patternconstrains formats (IDs, codes, postcodes).min_length/max_lengthbound sizes before your API ever sees them.
Custom validators extend the same idea:
class Window(pydantic.BaseModel):
start: pydantic.datetime
end: pydantic.datetime
@pydantic.model_validator(mode='after')
def _ordered(self):
if self.end <= self.start:
raise ValueError('end must be after start')
return self
Because validation errors are raised before your function body runs, a bad window never reaches the booking system — and, crucially, the error text that flows back to the model describes the violated rule, which is exactly the information it needs to correct itself.
Error messages are repair instructions
When validation fails, the model gets a second attempt. Make that attempt likely to succeed:
- Name the field in the constraint:
pattern=r'^A-\d{5}$'with a field description “format ‘A-12345’” tells the model both what’s wrong and what’s right. - Write
Field(description=...)for anything non-obvious. This is the per-field documentation that flat parameters lack — say where the value comes from (“fromget_orders, never guessed”). - Avoid opaque error text. A bare
ValueError('invalid')produces a blind retry;ValueError('urgency must be 1-5; got 9')produces a correct one.
Two or three failed repairs in a row usually means the description is wrong rather than the model — re-read the schema as if you’d never seen the domain.
Choosing: nested model vs flattened parameters
| Shape | Use when |
|---|---|
One BaseModel parameter | Coherent object; fields that belong together; created/submitted as a unit |
| Flat scalar params | Independent options, few of them, model must choose between them |
| Model + a couple of scalars | Mixed: a payload plus per-call switches (dry_run: bool = False) |
list[Model] | Batch operations — the model supplies several validated rows |
Watch the tool’s call semantics: a tool that receives one BookingRequest is atomic; a tool receiving list[BookingRequest] implies partial failure handling (all-or-nothing vs per-row status) that you must document in the docstring.
Keeping the wire schema separate from your domain model
The tempting shortcut — reusing your ORM/entity classes as tool arguments — couples your prompt surface to your database schema:
- Every entity change silently rewrites the tool declaration (and breaks your prompt cache prefix).
- Fields the model should never set become settable.
- Fields grow weird names for users of the API (
created_at_v2, internal enums) and leak into descriptions.
The cleaner separation:
# api_models.py — what the model may send
class BookingInput(pydantic.BaseModel):
"""Payload the assistant may submit for a booking."""
guest_name: str = pydantic.Field(description='Full name as given by the guest.')
check_in: pydantic.date
check_out: pydantic.date
# service layer maps it onto your domain objects
def create_booking(payload: BookingInput) -> dict:
booking = BookingMapper.to_domain(payload) # validation, defaults, IDs
...
If you need both views, use Pydantic’s model-sharing (model_config = ConfigDict(extra='forbid') on the input side, model_validate from the domain side) — but keep the declaration class explicitly small and stable.
extra='forbid' deserves a mention: it stops the model from inventing fields, turning a silently-ignored typo into a visible error. Strongly recommended for tool arguments.
Testing
Assert on the declaration, not just the function:
def test_booking_tool_schema():
tool = FunctionTool(func=create_booking)
decl = tool.get_declaration()
req = decl.parameters['required']
assert 'request' in req
# nested schema reached the model
props = decl.parameters['properties']['request']['properties']
assert 'urgency' in props or 'rooms' in props
def test_validator_rejects_bad_window():
with pytest.raises(pydantic.ValidationError):
Window(start=datetime(2026, 11, 27, 15), end=datetime(2026, 11, 27, 9))
The first test is the one people skip: schema regressions (a field renamed, a constraint dropped) don’t crash anything — they just make the model worse at calling you.
Takeaways
- Annotate a parameter with a
BaseModeland ADK nests the schema for the model while handing your function a validated instance. - Put constraints and
Literal/enum choices on fields — they appear in the schema the model reads, so errors become self-explanatory. - Treat validation errors as repair instructions: name fields, show formats, never raise
invalid. - Keep a small, dedicated input model separate from domain/ORM entities;
extra='forbid'prevents invented fields. - Assert the generated declaration in CI — a silent schema change is a silent quality regression.