AI AgentsLangChain
How do you validate tool arguments with Pydantic schemas?
Question 293 of 324 · Updated
On this page
- Direct answer
- 1. Why use an explicit schema rather than inferred annotations?
- 2. Design the schema and enforcement layers
- 3. Define a Pydantic v2 model
- Required, optional and nullable are different
- 4. Strict validation versus type coercion
- 5. Attach args_schema to a LangChain tool
- 6. Understand field constraints and validators
- 7. Tested implementation: validate valid and invalid arguments
- 8. Keep business authorization separate: tested domain function
- 9. Inspect generated JSON Schema and provider compatibility
- 10. Validation errors and bounded recovery
- 11. Production testing and versioning
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
Define a Pydantic BaseModel describing the tool's accepted arguments, then attach it to the LangChain tool using @tool(args_schema=YourModel). Pydantic validates supplied values, applies supported defaults and constraints, and can enforce relationships among fields through validators. LangChain can use the declared schema to describe the tool to a model and validate inputs at invocation time. Always validate actual tool requests on the application side: provider-side tool schemas are useful guidance and may constrain generation, but not all providers implement every JSON Schema feature.
A valid Pydantic object means the input meets the configured schema and validators. It does not prove that a user is authorized, a resource exists, an amount is affordable, an approval is valid or an external action has succeeded.
This lesson builds on AI Agents #86 (generic tool schemas), #291 (the LangChain tool decorator) and #292 (model-facing metadata). It concentrates on explicit Pydantic v2 input schemas and the boundary between structural validation and executable domain rules. Response schemas, structured-output strategies and runtime dependency injection are covered in separate lessons.
1. Why use an explicit schema rather than inferred annotations?#
The tool decorator can infer a basic argument schema from a Python function signature. That is useful for straightforward tools. A signature such as estimate_delivery(postcode: str, parcels: int = 1) communicates basic types and a default but not necessarily the complete postal-code format, permitted parcel count, allowed service levels, cross-field constraints or strictness policy.
An explicit Pydantic model makes these rules a named, reviewable artifact. It can be tested independently of LangChain and reused at the tool boundary.
| Concern | Inferred schema | Explicit Pydantic schema |
|---|---|---|
| Basic names and types | Usually inferred from annotations | Declared on the model |
| Required fields and defaults | Derived from the signature | Explicit model fields |
| Numeric ranges and string patterns | May be represented through supported annotated constraints | Field constraints |
| Unknown fields and strictness | Depends on inferred model configuration | ConfigDict and explicit settings |
| Nested structures | Possible through typed arguments | Explicit nested BaseModel classes |
| Cross-field constraints | Not inferred from ordinary function logic | model_validator |
| Reuse and independent testing | May require access to the generated schema | Direct model_validate and model_json_schema calls |
Do not maintain two conflicting sources of truth. When you supply args_schema, keep the tool's callable signature aligned with that model. The tool wrapper may pass parsed values, nested models or dictionaries according to the installed implementation. Verify the actual invocation contract rather than assume that every adapter forwards a raw JSON object unchanged.
2. Design the schema and enforcement layers#
Suppose an agent offers a read-only fictional parcel quotation tool. Its business contract accepts a nested destination, a parcel count from one to ten, standard or express service, and an optional reference. Express accepts at most three parcels.
The model might propose parcels="2" (a string), parcels=true (a Boolean), a missing postcode, an unsupported service, or four express parcels. Different validation layers address these cases.
The provider schema and local validator serve different purposes. The model-facing schema can guide or constrain argument generation. Local Pydantic validation is an executable contract. Trusted application policy decides whether a structurally valid request is permitted. Do not move authenticated tenant IDs, approval credentials or broad service dependencies into the model-generated argument schema just because they are required by the backend.
3. Define a Pydantic v2 model#
The following complete schema is used throughout this lesson. It was tested locally with Python 3.13.5 and Pydantic 2.13.5. The postal-code and service constraints are fictional and intentionally narrow, not a universal shipping-address standard.
PYTHONfrom typing import Literal, Self from pydantic import ( BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator, ) class Address(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') postcode: str = Field(pattern=r'^[0-9]{5}$') country: Literal['US'] class QuoteArgs(BaseModel): model_config = ConfigDict( strict=True, extra='forbid', validate_default=True ) destination: Address parcels: int = Field( default=1, ge=1, le=10, description='Number of parcels' ) service: Literal['standard', 'express'] = 'standard' reference: str | None = Field(default=None, max_length=30) @field_validator('reference') @classmethod def nonblank(cls, value: str | None) -> str | None: if value is not None and not value.strip(): raise ValueError('reference must not be blank') return value @model_validator(mode='after') def express_limit(self) -> Self: if self.service == 'express' and self.parcels > 3: raise ValueError('express accepts at most three parcels') return self
This is Pydantic v2 syntax. BaseModel defines the validation and serialization interface. ConfigDict configures the model, Field supplies metadata and constraints, field_validator handles a field-specific rule, and model_validator evaluates a relationship among fields.
For this example, the model has four top-level fields and one nested model. The nested Address model explicitly defines its own strictness and extra-field policy. Do not assume an outer model's configuration automatically imposes every desired rule on an independently defined nested model.
Required, optional and nullable are different#
A field is required when a caller must provide it. Nullable means the field may contain None or JSON null. A default specifies what happens when the caller omits it.
| Declaration | May omit? | May supply None? |
|---|---|---|
| name: str | No | No |
| name: str = 'standard' | Yes | No |
| name: str or None, without default | No | Yes |
| name: str or None, default None | Yes | Yes |
In Python syntax, the nullable union in the last two examples is written as str | None. In Pydantic v2, annotating a field with Optional or a union containing None does not automatically give it a default.
In QuoteArgs, destination is required, parcels defaults to one, service defaults to standard and reference defaults to None. validate_default=True requests validation of defaults for that model. Test defaults explicitly, including whether the tool wrapper passes them or relies on matching function defaults.
4. Strict validation versus type coercion#
Pydantic commonly supports coercion in lax mode. Depending on the target type and input, a string such as "2" may be converted to an integer. That can be convenient for ordinary form input, but in an agent tool it may hide an upstream argument-generation error.
The explicit strict configuration in this example rejects a string or Boolean for parcels. It also preserves a postal code as a string, including a leading zero. Treat postal codes and opaque resource identifiers as identifiers rather than quantities.
PYTHONclass Lax(BaseModel): parcels: int assert Lax.model_validate({'parcels': '2'}).parcels == 2
The assertion was executed successfully. Contrast it with the strict QuoteArgs test in section 7, which rejects the same string.
Strictness can be configured at model, field or validation-call level where supported. The exact conversion rules depend on the input type and validation method. Strict JSON validation and strict Python-object validation are not identical for every data type; some JSON-compatible representations are necessarily different from native Python objects, such as dates represented as strings. Test the actual payload path that the tool uses.
Strict mode does not automatically reject every unwanted field: extra='forbid' is a separate setting. Nor does strictness prevent a syntactically valid but incorrect identifier, a wrong unit, or a value inconsistent with trusted records.
5. Attach args_schema to a LangChain tool#
Use the Pydantic class itself as the explicit argument schema in a compatible LangChain release. The following SDK illustration reuses QuoteArgs and a separately validated domain function, quote, defined in section 8.
PYTHONfrom langchain.tools import tool @tool(args_schema=QuoteArgs) def estimate_delivery( destination: Address, parcels: int = 1, service: Literal['standard', 'express'] = 'standard', reference: str | None = None, ) -> dict: """Return a fictional read-only delivery estimate in USD cents.""" # Fictional scope for this demonstration only. In production, # obtain a scoped dependency from authenticated runtime context. payload = { 'destination': destination, 'parcels': parcels, 'service': service, 'reference': reference, } return quote(payload, frozenset({'01234'})) # Direct invocation in a compatible environment: result = estimate_delivery.invoke({ 'destination': {'postcode': '01234', 'country': 'US'}, 'parcels': 3, 'service': 'express', }) print(result)
The expected logical result is currency USD and cost_cents 1150. That value was tested through the standalone domain function, not through the LangChain wrapper. The domain function validates the assembled payload again so that a dictionary or an already parsed Address object can be handled by the Pydantic model in the intended example. In production, consider whether explicit validation at the domain boundary is necessary to protect other callers; avoid redundant work only when the trusted invocation contract is demonstrably sufficient.
SDK verification limitation: LangChain, langchain_core and langgraph were not installed in the local environment. The decorator and agent integration snippets are illustrative and unexecuted. Verify the exact installed API, the nested argument representation and default forwarding behavior before use. The Pydantic examples themselves were executed using the actual installed library.
To register the tool, use the previously established agent builder pattern:
PYTHONfrom langchain.agents import create_agent agent = create_agent( model='openai:gpt-4o-mini', tools=[estimate_delivery], system_prompt=( 'Return fictional delivery estimates. Use the provided tool; ' 'ask for missing information rather than inventing a destination.' ), )
The model identifier is illustrative, not a live availability claim. The example does not access real shipping systems. Installing compatible packages, selecting approved provider credentials and verifying model tool-call capabilities are separate deployment steps.
6. Understand field constraints and validators#
Field constraints are declarative rules. Numeric bounds, string lengths and patterns, collection lengths and descriptions can often be represented in generated JSON Schema. The model provider may support only a subset of those schema features.
| Rule | Example | Meaning |
|---|---|---|
| ge and le | parcels from 1 through 10 | Inclusive numeric bounds |
| pattern | postcode matches five ASCII digits | String-format constraint |
| max_length | reference at most 30 characters | Length constraint |
| Literal | standard or express | Closed set of accepted values |
| extra='forbid' | Reject unexpected properties | No unrecognized fields |
| field_validator | Reject whitespace-only reference | Field-specific executable validation |
| model_validator | Express service permits at most 3 parcels | Cross-field executable validation |
A field validator can normalize a value or reject it. Prefer explicit normalization when the application genuinely accepts multiple equivalent representations. Do not silently change a model-generated amount, identity or unit in a way that could alter the user's intended action.
A model validator in after mode receives a validated model instance and can compare multiple fields. This is the right place for pure, deterministic relationships such as a minimum value being no greater than a maximum, an end date not preceding a start date, or a service level having a different parcel limit. A validator should normally avoid network calls and irreversible side effects. Validation can be retried, repeated, invoked during tests or called by other application entry points.
A before-mode validator can inspect or transform raw input before ordinary validation. Use it with care; transformations can accidentally weaken strictness or hide errors. For business rules involving current balances, permissions, inventory or external service state, validate at the domain boundary rather than embedding a potentially stale external lookup in a schema.
7. Tested implementation: validate valid and invalid arguments#
Run the following code after the schema definitions in section 3. It was executed locally against Pydantic 2.13.5 rather than an imitation of its API.
PYTHONbase = { 'destination': {'postcode': '01234', 'country': 'US'} } a = QuoteArgs.model_validate(base) assert a.parcels == 1 and a.reference is None assert QuoteArgs.model_validate({ **base, 'parcels': 3, 'service': 'express' }).parcels == 3 assert a.destination.postcode == '01234' for bad in [ {}, {**base, 'parcels': '2'}, {**base, 'parcels': True}, {**base, 'parcels': 0}, {**base, 'parcels': 11}, {**base, 'service': 'express', 'parcels': 4}, {**base, 'reference': ' '}, {**base, 'unexpected': 1}, {'destination': {'postcode': '1234', 'country': 'US'}}, {'destination': { 'postcode': '01234', 'country': 'US', 'extra': True }}, {**base, 'service': 'priority'}, ]: try: QuoteArgs.model_validate(bad) except ValidationError: pass else: raise AssertionError('invalid payload accepted') assert QuoteArgs.model_json_schema()['required'] == ['destination'] class Lax(BaseModel): parcels: int assert Lax.model_validate({'parcels': '2'}).parcels == 2 print('16 checks passed')
Actual local output:
16 checks passedThe test verifies three valid/default/preservation cases, eleven rejected inputs, a generated-schema required-field check, and a lax conversion check.
| Invalid case | Why it must fail |
|---|---|
| Empty payload | Missing destination |
| parcels is the string "2" | Strict integer rule |
| parcels is true | Strict integer rule |
| parcels is zero or eleven | Outside allowed numeric range |
| Express with four parcels | Cross-field validator |
| Blank reference | Field validator |
| Unexpected root property | Root extra-field policy |
| Four-digit postcode | Pattern constraint |
| Unexpected destination property | Nested extra-field policy |
| Unsupported service priority | Literal constraint |
The checks assert rejection through ValidationError without relying on exact error wording, which can vary by version. A production suite should also assert appropriate error locations and normalized categories, test boundaries such as one and ten parcels, and include representative raw JSON and provider-adapter inputs.
8. Keep business authorization separate: tested domain function#
A valid destination may still be outside a caller's approved service scope. The following function receives a trusted scope from its caller, validates the arguments and calculates a fictional price only when the destination is allowed.
PYTHONdef quote(payload: dict, allowed_postcodes: frozenset[str]) -> dict: args = QuoteArgs.model_validate(payload) if args.destination.postcode not in allowed_postcodes: raise PermissionError('destination not available') surcharge = 300 if args.service == 'express' else 0 return { 'currency': 'USD', 'cost_cents': 400 + 150 * args.parcels + surcharge, } assert quote(base, frozenset({'01234'})) == { 'currency': 'USD', 'cost_cents': 550 } assert quote({ **base, 'service': 'express', 'parcels': 3 }, frozenset({'01234'}))['cost_cents'] == 1150 try: quote(base, frozenset({'99999'})) except PermissionError: pass else: raise AssertionError('unauthorized destination') print('3 business-boundary checks passed')
Actual local output:
3 business-boundary checks passedThe first quote costs 400 + 150 = 550 cents. The three-parcel express quote costs 400 + 450 + 300 = 1150 cents. All values are fictional. Integer cents avoid floating-point ambiguity for this simple currency calculation.
The third test is particularly important: the payload is structurally valid, but the application rejects it because the caller's allowed scope does not include the destination. The example assumes the scope has already been authenticated and authorized by the host. It does not implement identity verification, a real shipping policy or a live resource service.
For a write-capable tool, further checks are necessary: current authorization, any required approval bound to the exact operation, transactional business invariants, idempotency and authoritative outcome verification. Validation must happen before execution; if circumstances can change, recheck the relevant business constraints at commit time.
This is an application-level sequence diagram. It does not claim that every LangChain version automatically converts each error into exactly these model-visible observations.
9. Inspect generated JSON Schema and provider compatibility#
Pydantic v2 exposes model_json_schema for inspecting the schema. For QuoteArgs, the generated object can include a reference to the nested Address definition, required-field information, numeric bounds, enum values and additionalProperties restrictions. The locally executed test verifies that destination is the sole required top-level field.
Do not assume that every executable validator is reflected in the generated JSON Schema. For example, the express parcel-count rule is implemented in Python by model_validator; the model provider cannot be assumed to enforce it through ordinary schema conversion. Likewise, the reference nonblank check is not necessarily encoded as a declarative constraint.
A provider may support only certain JSON Schema keywords or require additional restrictions for constrained tool generation. Differences can include nested references, nullable unions, defaults, additional properties, numeric constraints and required-field conventions. The integration may adapt, simplify or reject the schema.
Use this checklist:
| Compatibility question | Verification |
|---|---|
| Are nested objects accepted? | Send the actual converted tool definition in a controlled test |
| Are nullable fields and defaults represented correctly? | Test omitted fields and explicit null |
| Does constrained generation support the field constraints? | Observe actual model proposals and locally validate them |
| Are unknown properties rejected? | Test the adapter and local validator independently |
| Are cross-field rules preserved? | Enforce them locally even if not expressible in the provider schema |
| Are injected dependencies omitted from model arguments? | Inspect the model-facing contract |
| Are tool calls correlated with their results? | Verify complete runtime message sequences |
An unsupported schema feature is not a reason to remove essential local validation. Where feasible, simplify the model-facing description while preserving the stronger domain contract. If a provider cannot support a critical capability, reject the incompatible profile or use a reviewed adapter.
For sensitive tools, do not execute partial streamed arguments. Wait for a complete, valid tool request, then check the parsed payload and authorization. Even if a provider advertises strict structured tool calls, use local validation before external actions.
10. Validation errors and bounded recovery#
Pydantic ValidationError provides structured error details, including the field location and error category. In a nested payload, a location can identify destination.postcode; a cross-field error may apply to the whole model. Use these categories to guide debugging and safe correction.
Avoid sending raw exception strings directly to a user or model. Validation errors can include the original input, and custom errors may reveal internal data. Return only approved, minimal correction information, such as "parcel count must be an integer from 1 through 10" or "destination is required." Do not reveal whether another tenant's private record exists when authorization fails.
Separate failure classes:
| Failure class | Appropriate handling |
|---|---|
| Missing required argument | Ask for the missing input or request a corrected call |
| Wrong type or range | Return bounded validation guidance |
| Unsupported field | Reject unexpected input; review schema mismatch |
| Cross-field conflict | Explain the relevant accepted relationship |
| Permission denied | Stop or return a controlled denial; do not try unrelated identities |
| Provider schema rejection | Diagnose adapter compatibility before invoking tools |
| Temporary external read failure | Retry only under an explicit bounded policy |
| Uncertain write result | Reconcile with the external system before retrying |
Some LangChain versions offer tool-validation error handling configuration or middleware mechanisms. Exact behavior differs by tool class and runtime; check the installed API rather than assume validation failures always reach the model as recoverable observations. The dedicated error-handling lesson covers those interfaces in detail.
The loop should have explicit call, time and correction budgets. A model that repeatedly generates the same invalid arguments must not retry indefinitely. Never weaken a validator merely to make the retry succeed.
11. Production testing and versioning#
Start with independent Pydantic tests, then test the actual LangChain tool and provider integration when approved. Keep all experiments on synthetic records or isolated environments.
- Test valid boundary values, missing fields, explicit null, wrong types, coercion behavior, unknown properties and nested errors.
- Verify cross-field validators and deterministic normalization. Avoid external side effects inside validation code.
- Inspect the generated and actual provider-facing schema, including defaults and required fields.
- Verify direct tool invocation and confirm that malformed arguments do not reach an external operation.
- Test valid but unauthorized inputs separately from schema-invalid ones.
- Test model proposals with incomplete JSON, unknown tool names, invalid arguments and repeated failures.
- Verify that error reporting does not disclose raw input, secrets or private records.
- Record the Pydantic version, LangChain integration version, schema revision, provider model and regression dataset.
Schema evolution is a behavioral change. Adding a required field can break existing clients or suspended workflows; renaming a field can break recorded tool requests; increasing permissiveness can expose unsafe behavior. Treat schema revisions as versioned contracts and preserve migration or compatibility paths where necessary.
Measure local validation overhead separately from model and external-tool latency. For an illustrative run containing 50 calls, a hypothetical 0.5 ms validation cost per call adds 25 ms of aggregate validation work before any concurrency effects. This is not a measured benchmark. Real validation cost depends on schema size, parsing, nested data and custom validators. Correctness and authorization are release requirements, not optimizations to discard.
Interview-ready answer#
I define a Pydantic v2 BaseModel for the tool's model-generated arguments and attach it with LangChain's args_schema option. I use Field and Literal for declarative constraints, explicit defaults for optional fields, strict configuration where coercion is undesirable, and field or model validators for deterministic additional rules. I inspect the generated schema and test actual provider compatibility because not every provider supports every JSON Schema keyword or Python validator. I validate the request locally before execution, keep identity and business authorization outside model-generated arguments, sanitize validation errors and bound correction attempts. A schema-valid input is necessary but does not prove permission or successful execution.
Official documentation research leads and verification status#
- LangChain tools
- LangChain agents
- LangChain API reference
- Pydantic models
- Pydantic fields
- Pydantic strict mode
- Pydantic validators
- Pydantic JSON Schema
- Pydantic errors
Authorized offline research exception applied. These official documentation URLs are reference leads and were not live-accessed. Actual local tests ran on Python 3.13.5 with Pydantic 2.13.5: 16 validation checks and 3 business-boundary checks passed. LangChain, langchain_core and langgraph were absent, so SDK integration examples were not executed and provider compatibility remains unverified. Mermaid blocks use standard triple-backtick fences; live rendering and public website display were not verified. All prices, service constraints and authorization fixtures are synthetic.
References
- 1.LangChain toolsdocs.langchain.com
- 2.LangChain agentsdocs.langchain.com
- 3.LangChain API referencereference.langchain.com
- 4.Pydantic modelsdocs.pydantic.dev
- 5.Pydantic fieldsdocs.pydantic.dev
- 6.Pydantic strict modedocs.pydantic.dev
- 7.Pydantic validatorsdocs.pydantic.dev
- 8.Pydantic JSON Schemadocs.pydantic.dev
- 9.Pydantic errorsdocs.pydantic.dev
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps