AI AgentsLangChain

How do you define Pydantic schemas for agent responses?

Question 303 of 324 · Updated

On this page

Direct answer#

Define an agent response as an explicit Pydantic v2 BaseModel with typed fields, descriptive Field metadata, nested models, bounded values, and validators for relationships that cannot be expressed by individual field types. Register the response model through LangChain's create_agent(response_format=YourModel), then accept the completed structured_response only after independent application checks. The model is a versioned consumer contract, not merely a convenient way to parse JSON.

A good final response schema distinguishes meaningful business outcomes rather than forcing the model to fabricate a success record. Use a discriminated union for alternatives such as a verified report and a report requiring review. Use model_json_schema to inspect the generated JSON Schema, test the actual provider's supported subset, and serialize only accepted results.

Earlier LangChain lessons #13 (#293), #21 (#301) and #22 (#302) cover tool argument schemas, the final structured-response interface and response strategy selection. This lesson focuses on designing the response contract itself, with nested records, explicit variants, required-nullable fields, validator scope, JSON serialization, semantic acceptance and versioning. The next question addresses recovery from invalid structured output.

1. Design for the downstream consumer first#

Suppose a fictional fulfillment-support agent inspects an order-related task. The dashboard needs to know whether stock availability and address verification passed or failed. It also needs references to trusted observations. If evidence is missing or contradictory, the agent must produce a needs_review result rather than fabricate two findings.

A weak schema might expose a free-form summary, a confidence number and an optional list of findings. That representation allows an ambiguous object: a status of verified, no evidence and a high model-generated confidence value. A stronger contract uses a dedicated outcome variant for a verified report and a separate variant for a review request.

Design decisionConsumer requirement
Task identifierAssociate the result with the authorized requested task
Outcome discriminatorSelect the correct rendering or processing branch
Nested findingsRepresent individually typed observations
Evidence referenceIdentify trusted observations for independent verification
Explicit review reasonDistinguish missing evidence from conflicting evidence
Nullable noteAllow an optional explanatory value without hiding field omission
Schema versionMaintain compatibility across producer and consumer releases

The report is read-only. A verified finding does not approve shipment, change an address or reserve stock. Any external commitment must occur through a separately authorized domain service. A consumer must never treat a model-generated response as proof of authorization.

Loading diagram…

2. BaseModel and Field: make each property meaningful#

Pydantic BaseModel supplies a runtime validation and serialization interface. Define a model for the final output, independent of the models used for intermediate tools. A field name and type express shape; Field metadata expresses additional constraints and communicates intent when converted to a schema.

For example, a finding has a check identifier, a result state and an evidence reference. The check identifier should come from a small stable vocabulary. The evidence reference should identify an observation collected through an authorized tool or service. A pattern can restrict the identifier's shape but cannot prove that the reference exists.

DeclarationMeaning
task_id: strA required string
status: Literal["pass", "fail"]A required member of a fixed vocabulary
Field(pattern=r"^E-[0-9]+$")An evidence identifier matching a local pattern
Field(min_length=1, max_length=2)Bounds the length of a list in this example
Field(description="Reference from an authorized tool observation")Documents the intended value for schema consumers and model guidance
ConfigDict(extra="forbid")Rejects undeclared fields at local validation
ConfigDict(strict=True)Enables stricter type handling
ConfigDict(frozen=True)Prevents ordinary field reassignment; not deep immutability

Field descriptions should identify units, reference formats, semantics and important exclusions. For example, "integer amount in minor currency units" is more useful than "amount." A description saying "must be an authorized resource" helps communicate intent, but only trusted application code can actually establish authorization.

Avoid placing sensitive internal policy details, credentials or private examples in schema descriptions: metadata can be transmitted to the model provider. Keep descriptions concise and relevant. Schema size affects context use, and redundant metadata may make the model's task harder.

Required versus nullable versus defaulted#

Pydantic v2 distinguishes nullability from whether a key is required. The annotation str | None permits null but does not itself supply a default. That distinction matters for machine-readable final results.

Field declarationKey required?Accepts None?
note: strYesNo
note: str or None, without defaultYesYes
note: str or None = NoneNoYes
note: str = "No note"NoNo

Use Python's union notation str | None (or Optional[str]) in actual code for the nullable declarations. The table's plain-English "or" is descriptive.

In the fulfillment report, the note key is required but nullable: explicit null communicates that there is no note. An omitted key indicates that the producer has not satisfied the contract. Some provider structured-output APIs prefer or require every property to be listed as required; explicit nullable fields can be useful when supported. Verify actual compatibility rather than assuming all APIs enforce the same rules.

3. Nested models, Literal and Enum#

Nested response models organize repeated facts and preserve relationships. Instead of multiple parallel lists containing checks, states and evidence references, represent each finding as one object. Parallel arrays are easy to misalign, especially when a result is partial.

A list of findings also needs size and uniqueness constraints. A maximum length limits the local accepted result, although it does not by itself guarantee a hard provider token budget. A model-level validator can ensure that the same check appears only once.

Literal is convenient for model-facing string vocabularies. An Enum is useful when application code also needs named members and shared semantics. For example, State.PASS can be an application constant, while its JSON representation is the string "pass".

With strict Pydantic models, JSON parsing and Python-object validation can behave differently. Some types have no direct JSON representation and can be accepted from their JSON representation in strict JSON mode, while strict validation of a Python dict requires the actual Python type. The tested enum example in section 6 demonstrates strict JSON parsing of a string into an Enum member and JSON-mode serialization back to its value. When the framework returns a Python dict rather than raw JSON, test the exact input representation you will validate. A Literal string field is often simpler for a wire-facing enum.

4. Use discriminated unions for meaningful outcome branches#

A discriminated union selects a variant through a shared tag field. Each branch has a distinct Literal tag. This avoids asking the model to fill unrelated fields with arbitrary null values.

For the fictional report:

  • Verified has kind="verified" and a bounded list of findings.
  • Review has kind="needs_review" and a reason.
  • The containing Report has a task ID, outcome and nullable note.

The variant is part of the consumer's contract. The consumer may render verified findings only from the verified branch, and a review request only from the review branch.

Loading diagram…

This diagram describes the data contract, not Python inheritance. Both variants can inherit common configuration from a base model. A verified branch may contain an observation whose state is fail; verified means that the finding is supported by evidence, not that every business check passed.

Discriminated unions are helpful for local validation and deterministic downstream branching. They can generate JSON Schema using oneOf, $defs, references and discriminator metadata. Some provider APIs reject or transform these features. If the exact generated schema is unsupported, a reviewed simpler wire model or separately routed response schema may be required. Preserve the stronger local domain model and verify the mapping; do not flatten all meaningful branches into unchecked prose.

5. Validators: structural rules and semantic rules belong at different boundaries#

A field_validator can reject whitespace-only notes. A model_validator can compare fields or examine a collection and reject duplicated checks. These validations should be deterministic, local and inexpensive.

Do not place network calls, database writes, authentication decisions or external side effects inside response-model validators. A validation routine may execute more than once, and the model provider cannot enforce arbitrary Python validators in constrained generation. Keep the schema and domain acceptance test separate.

ValidationExampleAppropriate boundary
Field type and patternTask ID begins with T-Pydantic field
Field-specific ruleNote cannot be blank when presentfield_validator
Collection invariantEach check appears at most oncemodel_validator
Task completenessBoth required checks are presentApplication acceptance
Claim correctnessEvidence matches task, check and stateTrusted evidence acceptance
Resource authorizationCaller may access that evidenceDomain service and application policy
Current validityObservation is fresh enough for this taskApplication policy

The consumer's required checks may depend on the actual task, so a production acceptance function should receive the requirements from trusted task configuration. This lesson's fictional task always requires stock and address, allowing the example to use a fixed set.

6. Tested Python implementation: nested tagged reports and local acceptance#

The complete example below was executed locally on Python 3.13.5 with Pydantic 2.13.5. It models a synthetic fulfillment report and checks both structural correctness and claims against independently supplied evidence. No external tool, model provider or live order system was used.

PYTHON
from typing import Annotated, Literal, Self from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator from enum import Enum import json class Contract(BaseModel): model_config = ConfigDict(strict=True, extra='forbid', frozen=True) class Finding(Contract): check: Literal['stock', 'address'] state: Literal['pass', 'fail'] evidence_ref: str = Field(pattern=r'^E-[0-9]+$', description='Reference from an authorized tool observation') class Verified(Contract): kind: Literal['verified'] findings: list[Finding] = Field(min_length=1, max_length=2) @model_validator(mode='after') def distinct_checks(self) -> Self: if len({f.check for f in self.findings}) != len(self.findings): raise ValueError('duplicate check') return self class Review(Contract): kind: Literal['needs_review'] reason: Literal['missing_evidence', 'conflicting_evidence'] class Report(Contract): task_id: str = Field(pattern=r'^T-[0-9]+$') outcome: Annotated[Verified | Review, Field(discriminator='kind')] note: str | None = Field(max_length=120, description='Optional meaning; required key; null when absent') @field_validator('note') @classmethod def not_blank(cls, value): if value is not None and not value.strip(): raise ValueError('blank note') return value class State(str, Enum): PASS = 'pass' FAIL = 'fail' class LocalEnum(Contract): state: State def accept(raw, task_id, evidence): report = Report.model_validate(raw.model_dump() if isinstance(raw, Report) else raw) if report.task_id != task_id: raise ValueError('wrong task') if isinstance(report.outcome, Verified): if {f.check for f in report.outcome.findings} != {'stock','address'}: raise ValueError('incomplete checks') for f in report.outcome.findings: if evidence.get(f.evidence_ref) != (task_id, f.check, f.state): raise ValueError('unsupported finding') return report evidence = {'E-1': ('T-7','stock','pass'), 'E-2': ('T-7','address','fail')} f1 = {'check':'stock','state':'pass','evidence_ref':'E-1'} f2 = {'check':'address','state':'fail','evidence_ref':'E-2'} base = {'task_id':'T-7','outcome':{'kind':'verified','findings':[f1,f2]},'note':None} report = accept(base,'T-7',evidence) assert isinstance(report.outcome, Verified) assert Report.model_validate_json(report.model_dump_json()) == report assert accept(report,'T-7',evidence) == report assert isinstance(accept({'task_id':'T-7','outcome':{'kind':'needs_review','reason':'missing_evidence'},'note':None},'T-7',evidence).outcome, Review) assert Report.model_json_schema()['properties']['outcome']['discriminator']['propertyName']=='kind' assert set(Report.model_json_schema()['required'])=={'task_id','outcome','note'} assert LocalEnum.model_validate_json('{"state":"pass"}').state is State.PASS assert LocalEnum(state=State.PASS).model_dump(mode='json')=={'state':'pass'} for raw, err in [ ({**base,'task_id':7}, ValidationError), ({k:v for k,v in base.items() if k!='note'}, ValidationError), ({**base,'note':' '}, ValidationError), ({**base,'note':'x'*121}, ValidationError), ({**base,'outcome':{'kind':'other'}}, ValidationError), ({**base,'outcome':{'kind':'needs_review','reason':'missing_evidence','findings':[f1]}}, ValidationError), ({**base,'outcome':{'kind':'verified','findings':[]}}, ValidationError), ({**base,'outcome':{'kind':'verified','findings':[f1,f1]}}, ValidationError), ({**base,'outcome':{'kind':'verified','findings':[f1]}}, ValueError), ({**base,'outcome':{'kind':'verified','findings':[f1,{**f2,'state':'pass'}]}}, ValueError), ({**base,'outcome':{'kind':'verified','findings':[f1,{**f2,'evidence_ref':'E-9'}]}}, ValueError), ({**base,'task_id':'T-8'}, ValueError), ({**base,'outcome':{'kind':'verified','findings':[f1,{**f2,'private':'x'}]}}, ValidationError), ]: try: accept(raw,'T-7',evidence) except err: pass else: raise AssertionError('invalid payload accepted') print('21 checks passed') print(report.model_dump_json())

Actual local output:

21 checks passed
{"task_id":"T-7","outcome":{"kind":"verified","findings":[{"check":"stock","state":"pass","evidence_ref":"E-1"},{"check":"address","state":"fail","evidence_ref":"E-2"}]},"note":null}

The eight positive checks cover verified and review variants, revalidation, JSON round-trip, generated discriminator, required keys and enum conversion. The thirteen negative fixtures cover invalid types, omission, invalid notes, unknown tags, extra fields across variants and nested objects, empty or duplicate findings, incomplete checks, unsupported claims, fabricated evidence and wrong task identity.

The final four acceptance-related negative fixtures use ValueError where a semantic rejection is expected. Pydantic ValidationError itself subclasses ValueError, so catching ValueError alone does not prove an error originated exclusively at the semantic boundary. The fixtures are structurally intended to pass in those cases, but a stronger production test should independently assert that schema validation succeeds, then assert a dedicated domain exception or normalized error code from the acceptance layer. This is a limitation of the compact test harness, not a guarantee about every failure classification.

The frozen configuration prevents ordinary reassignment of model fields. The findings list remains mutable, so the model is not deeply immutable. Revalidate or produce an independent approved projection before sharing across trust boundaries. If deep immutability is required, design suitable immutable containers and test how their JSON and Python representations interact with strictness.

The fixture evidence map represents trusted observations that are already authorized for the task. The code does not authenticate a principal, query a service, check evidence freshness or prove that a real tool executed. The review branch makes no positive finding claim. The example accepts its structurally valid reason without proving that the reason is accurate; production consumers should verify the review reason if decisions depend on it. Unnecessary abstention should be measured separately from unsafe acceptance.

A free-text note is also untrusted even when length and blank checks pass. The note can contain unsupported claims or sensitive information; a production system may omit it from the consumer projection or separately validate its content and disclosure. Never assume a valid field type guarantees safe text.

7. Inspect JSON Schema and integrate with LangChain#

After defining the Pydantic model, inspect Report.model_json_schema(). For this tested model, the outcome property contains a discriminator with propertyName equal to kind, and the root required keys are task_id, outcome and note.

The generated schema can contain definitions for the nested Finding, Verified and Review models, a reference-based union, constraints, descriptions and additionalProperties restrictions. The exact emitted schema is determined by the installed Pydantic version and its configuration. Not all executable Python validators are encoded as JSON Schema. In particular, the duplicate-check validator and application evidence comparison need local enforcement.

Pydantic can generate schemas for validation or serialization mode. Inspect the representation that actually crosses the provider or consumer boundary. If aliases, computed fields or custom serializers are introduced, schema and serialization representations may differ. Test both rather than infer one from the other.

A compatible LangChain agent can use Report directly as the response schema.

PYTHON
# Illustrative SDK integration; requires a verified LangChain installation. from langchain.agents import create_agent from langchain.tools import tool @tool def inspect_demo(task_id: str) -> dict: """Return fictional authorized inspection observations; no writes.""" if task_id != "T-7": return {"status": "unavailable"} return { "task_id": "T-7", "findings": [ {"check": "stock", "state": "pass", "evidence_ref": "E-1"}, {"check": "address", "state": "fail", "evidence_ref": "E-2"}, ], } agent = create_agent( model="openai:gpt-4o-mini", tools=[inspect_demo], response_format=Report, system_prompt=( "Produce a report for the fictional task using verified evidence. " "Use needs_review if required evidence is unavailable. " "Never invent references or perform mutations." ), ) state = agent.invoke({ "messages": [{"role": "user", "content": "Inspect fictional task T-7."}] }) candidate = state.get("structured_response") if candidate is None: raise ValueError("No completed structured response") # In production this mapping comes from trusted authorized observations, # not from candidate fields. This is a synthetic fixture. trusted_evidence = {"E-1": ("T-7", "stock", "pass"), "E-2": ("T-7", "address", "fail")} approved = accept(candidate, "T-7", trusted_evidence) print(approved.model_dump_json())

SDK verification limitation: LangChain, langchain_core and langgraph were absent locally. This integration is illustrative and unexecuted. The model identifier is an example, not a claim of current availability or support for this particular union schema. Confirm the selected response strategy accepts the generated schema and that the actual invocation completes with the expected result. If the provider rejects discriminators or references, use an approved compatible representation with the same local acceptance requirements. The standalone Pydantic program in section 6 was executed; the actual SDK path was not.

As established in #302, choose ProviderStrategy or ToolStrategy based on verified provider and schema compatibility. Do not make a provider-specific strategy choice part of the domain response model. Keep the consumer contract stable across supported generation mechanisms.

8. Serialization, explicit nulls and consumer contracts#

Pydantic offers several different serialization operations:

OperationResult
model_dump()Python data representation
model_dump(mode="json")JSON-compatible Python values
model_dump_json()Serialized JSON string
model_validate(raw)Validates a Python input representation
model_validate_json(raw_json)Parses and validates JSON input

Do not double-encode JSON when a web framework expects a dictionary or object. Preserve explicit null values when required by the consumer contract. For the Report schema, model_dump(exclude_none=True) would omit note when it is null, violating the required-key contract if used as the final payload. The same concern applies to exclude_unset and exclude_defaults when consumers require specific keys.

Keep representation decisions explicit for Enum, date/time, Decimal and UUID fields. A strict validator's treatment of raw JSON and already decoded Python values may differ for these types. Use reviewed serialization rules for money, time zones, identifiers and precision.

A downstream consumer should branch on the approved kind tag, not attempt to infer the result from prose. For example, render a needs_review report as a review item instead of displaying an empty successful verification table. If the verified outcome contains an address failure, display that verified failure without changing the task's external state.

Loading diagram…

9. Schema versioning and evolution#

A structured response schema is an API contract. Changes can break persisted records, dashboards, typed clients and workflow routing even if the new model is able to produce valid JSON.

ChangeCompatibility concern
Add optional field with defaultNew consumers must handle absent older values; old strict consumers may reject extra fields
Add required fieldOld producers cannot supply it
Rename a keyExisting parsers and stored records may fail
Remove enum valueHistorical records may become invalid
Add union variantExhaustive consumers may not know how to route it
Change nullabilityPreviously accepted results may fail
Change meaning or unitsType-compatible data may be interpreted incorrectly

Do not assume that adding a field is always backward-compatible. In this lesson, extra="forbid" means an older validator may reject the newer field. Coordinate compatibility in both directions.

A practical production contract includes an application-owned schema version in a response envelope. For example, the host can serialize a trusted schema revision and a request correlation ID around the accepted Report rather than have the model choose a version or invent identifiers. The envelope should itself be validated for the consumer interface.

For a breaking change, maintain explicit versioned readers or an audited migration function. Validate old records against the old schema, transform only well-understood fields, and validate against the new schema. Never infer missing evidence or convert an unknown status into success during migration. Pin the schema revision for each active or resumable workflow.

A release manifest can include the schema revision, generated schema digest, Pydantic and LangChain versions, strategy and provider profile. A digest helps detect unexpected changes in a schema representation; it does not establish semantic equivalence or consumer compatibility. Use fixture-based contract tests alongside the digest.

10. Production contract testing and evaluation#

Begin with pure schema unit tests before involving the model. Construct valid fixtures for every variant and invalid fixtures for every important field and invariant. For each semantic failure, first show that the candidate satisfies the schema, then verify that an independent acceptance policy rejects it. A production system should use distinct normalized outcome categories to keep parsing failures separate from unsupported claims.

Loading diagram…
Test areaAcceptance condition
Required-nullable contractMissing note rejected; explicit null accepted
Nested strictnessWrong types and unexpected nested fields rejected
Discriminated unionUnknown tags and fields from incompatible variants rejected
Collection validationEmpty or duplicated verified findings rejected
Semantic completenessMissing required check rejected for verified branch
Evidence matchingIncorrect status, task or reference rejected
SerializationAccepted JSON round-trips through intended producer and consumer
Generated schemaRequired keys, tag mapping and constraints reviewed
Provider compatibilityActual request schema and supported subset tested
Agent integrationCompleted structured_response accepted against independently captured evidence
Version evolutionHistorical records and old/new consumers tested explicitly
PrivacyModel-visible metadata and response projection disclose only permitted data

The local test suite verifies a limited synthetic contract, not provider behavior. Actual integration tests need the exact installed framework, adapter, provider model and response strategy. Test with ordinary tools, missing evidence and an unsupported schema feature. Evaluate a paused or interrupted run without falsely presenting success. Invalid-output recovery mechanisms are the subject of the next lesson.

Monitor schema validity, evidence-supported acceptance, unnecessary review outcomes, consumer parsing failures, schema-version mismatch, latency and cost per accepted result. Do not optimize for parseability by weakening meaningful validation. If the model frequently returns incomplete findings, investigate the task, tool evidence, schema metadata and model compatibility rather than silently removing mandatory fields.

Interview-ready answer#

I design Pydantic response models around the downstream consumer's domain contract. I use BaseModel, Field descriptions, explicit required and nullable fields, Literal or Enum vocabularies, typed nested objects and discriminated unions for mutually exclusive outcomes. I use field validators and model validators for deterministic local rules and independently verify task identity, evidence, resource permissions and completeness before acceptance. I inspect model_json_schema, test actual provider compatibility, register the model as LangChain's response_format, and serialize only approved results. I version the contract and test old and new consumers. Schema validity is a prerequisite, not proof that the model's claims are true or that a business operation has succeeded.

Official documentation research leads and verification status#

Authorized offline research exception applied. These are official documentation research leads, not live-accessed citations. The standalone Python implementation was actually executed with Python 3.13.5 and Pydantic 2.13.5; all 21 checks passed. LangChain, langchain_core and langgraph were absent. The illustrative SDK integration, provider-specific union and schema compatibility, live documentation, Mermaid rendering and public website display remain unverified. All records and evidence are fictional. The lesson uses standard triple-backtick Mermaid blocks.

References

  1. 1.
    LangChain structured outputdocs.langchain.com
  2. 2.
    LangChain agentsdocs.langchain.com
  3. 3.
    Pydantic modelsdocs.pydantic.dev
  4. 4.
    Pydantic fieldsdocs.pydantic.dev
  5. 5.
    Pydantic unionsdocs.pydantic.dev
  6. 6.
    Pydantic validatorsdocs.pydantic.dev
  7. 7.
    Pydantic strict modedocs.pydantic.dev
  8. 8.
    Pydantic JSON Schemadocs.pydantic.dev
  9. 9.
    Pydantic serializationdocs.pydantic.dev

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.