Chapter 05 / 18 min read
Pydantic: Define, Document and Enforce Tool Input Contracts
BaseModel, ConfigDict, Field, strict validation, JSON Schema, runtime validation and the execution boundary.
Pydantic: define, document and enforce tool input contracts
This chapter deserves special attention. Pydantic was not added merely to generate JSON for the model. It became the validation boundary between untrusted model output and the Python functions that perform work.
1. What problem are we solving?
Imagine the model asks the application to run:
multiply_numbers(a=250, b=40)
That is valid. But what if it returns:
multiply_numbers(a="two hundred", b=40)
Or sends an unexpected argument:
multiply_numbers(a=250, b=40, admin=True)
Or omits the denominator for division?
A Python type annotation such as a: float communicates the expected type to a reader and static tooling. Python does not automatically enforce that annotation every time the function is called. The function can be called directly, bypassing a validation step that happens elsewhere.
That was exactly the concern raised during the original implementation: someone could invoke the function directly and bypass Pydantic validation. The conclusion was correct: validation must happen inside the execution path immediately before the function call.
2. What is Pydantic?
Pydantic is a Python library for parsing and validating data using Python type annotations. We define a model class describing the shape of the data we expect. Pydantic validates incoming values against that model and gives us a typed model instance when validation succeeds.
For example:
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
person = Person(name="Asha", age=32)
print(person.name)
print(person.age)
The class declares the contract. Creating Person(...) asks Pydantic to validate the supplied values. If required data is missing or invalid, Pydantic raises a ValidationError.
A Pydantic model is therefore more than a convenient container. It describes what valid input looks like and performs runtime validation when data is parsed.
3. Create a strict base model
The project introduced a common base class so every tool schema could share the same validation policy:
from pydantic import BaseModel, ConfigDict, Field
class StrictInput(BaseModel):
model_config = ConfigDict(
extra="forbid",
strict=True,
)
Let's understand each line.
BaseModelis the Pydantic base class. Our schema classes inherit its validation and serialization behavior.ConfigDictdefines model-level configuration.extra="forbid"rejects fields that were not declared in the model.strict=Truerequests strict validation rather than silently coercing incompatible input values.
Why forbid extra fields? A model should not be able to smuggle an undeclared argument into a tool call. If the schema only declares a and b, a third field named admin should not be accepted.
4. Build a SearchInput schema
An early schema experiment used a search-tool definition:
class SearchInput(StrictInput):
query: str = Field(
min_length=3,
max_length=300,
description="The search query string.",
)
max_results: int = Field(
default=5,
ge=1,
le=10,
)
The model has two fields:
| Field | Type | Rule | Meaning |
|---|---|---|---|
query | str | 3–300 characters | Search phrase |
max_results | int | 1–10, default 5 | Maximum results requested |
The original draft used required=True and maximum=10 in Field. In Pydantic v2, a field is required when it has no default; numeric bounds are expressed with ge and le. The code above shows the corrected Pydantic v2 form, preserving the intended rules.
The description is particularly useful when we later generate JSON Schema. It tells a human and a model what the field means, rather than only stating that it is a string.
5. Build a SaveReportInput schema
The same early prototype had a report-saving input:
class SaveReportInput(StrictInput):
filename: str = Field(
min_length=1,
max_length=100,
)
report_markdown: str = Field(
min_length=50,
max_length=20000,
)
This constrains the filename and report content. These are input-shape limits, not a complete file-system security policy. A production file-writing tool would also need to constrain the output directory, reject path traversal, control overwrite behavior and apply authorization.
6. Define calculator-specific input models
Once we selected the calculator as the main learning domain, we created separate schemas for each operation:
class MultiplyInput(StrictInput):
a: float = Field(
description="The first number to multiply."
)
b: float = Field(
description="The second number to multiply."
)
class AdditionInput(StrictInput):
a: float = Field(
description="The first number to add."
)
b: float = Field(
description="The second number to add."
)
class DivideInput(StrictInput):
a: float = Field(
description="The numerator."
)
b: float = Field(
description="The denominator."
)
Why keep three models instead of one generic NumbersInput?
Because each tool has a different semantic contract. The two fields may have the same primitive type, but their meanings are different. The descriptions help the model understand the intended operation. Separate schemas also allow the tools to evolve independently—for example, division could later add a policy field or a denominator constraint without changing addition.
7. Validate real input at runtime
The following tests were run:
from pydantic import ValidationError
valid_input = SearchInput(
query="python 3.14.7 features"
)
print("Valid input:")
print(valid_input)
try:
SearchInput(query=12345)
except ValidationError as exc:
print("Invalid input:")
print(exc)
try:
SearchInput(
query="python version",
admin=True,
)
except ValidationError as exc:
print("Unexpected argument:")
print(exc)
The observed output included:
Valid input:
query='python 3.14.7 features'
Invalid input:
1 validation error for SearchInput
query
Input should be a valid string
[type=string_type, input_value=12345, input_type=int]
Unexpected argument:
1 validation error for SearchInput
admin
Extra inputs are not permitted
[type=extra_forbidden, input_value=True, input_type=bool]
This demonstrates two separate protections:
- Type validation rejects an integer where a strict string is required.
- Extra-field validation rejects an undeclared field.
The tests confirmed that the model configuration behaved as expected.
8. Generate JSON Schema from the same model
One of the most useful features is that the Pydantic model can generate JSON Schema:
schema = MultiplyInput.model_json_schema()
print(schema)
The output from the project had this general structure:
{
"additionalProperties": false,
"properties": {
"a": {
"description": "The first number to multiply.",
"title": "A",
"type": "number"
},
"b": {
"description": "The second number to multiply.",
"title": "B",
"type": "number"
}
},
"required": ["a", "b"],
"title": "MultiplyInput",
"type": "object"
}
This schema is a machine-readable description of the contract. It tells the LLM that it should provide an object, that the object must contain a and b, that both are numbers, and that extra properties are not allowed.
The important design principle is to avoid maintaining two independent definitions. We define the contract once in Pydantic and generate the JSON Schema from it.
9. Where validation belongs in the call path
The correct sequence is:
Model returns tool name + argument dictionary
|
v
Check tool name in registry
|
v
Find the Pydantic model for tool
|
v
Validate arguments with model_validate()
|
valid?
/ \
yes no
| |
v v
Call Python Return validation
function error; do not call
|
v
Return result
A validation model that is never called by the executor does not protect the function. The executor must invoke it at the boundary.
10. A reusable validation mapping
A natural extension of the separate schemas is a mapping from tool name to schema class:
TOOL_SCHEMAS = {
"calculate_addition": AdditionInput,
"multiply_numbers": MultiplyInput,
"divide_numbers": DivideInput,
}
Then the executor can validate dynamically:
schema_model = TOOL_SCHEMAS.get(tool_name)
if schema_model is None:
return {
"success": False,
"error": f"No schema registered for {tool_name}",
}
validated = schema_model.model_validate(tool_arguments)
validated_arguments = validated.model_dump()
This snippet illustrates the validation boundary; the full executor is developed in the tool-execution chapter. A production executor should catch ValidationError and return a structured failure rather than letting untrusted model output crash the orchestration loop.
What we learned
Pydantic performs runtime validation. JSON Schema describes the same contract to the model. The registry decides which function is callable. These are complementary responsibilities—not interchangeable alternatives.