AI AgentsLangChain

How do you return validated structured output from an agent?

Question 301 of 324 · Updated

On this page

Direct answer#

In modern LangChain, pass a response schema to create_agent using response_format, invoke the agent normally, and retrieve the validated final result from the returned state's structured_response field. Supported schema forms include Pydantic models, dataclasses, TypedDict definitions and JSON Schema dictionaries, depending on the installed release and selected strategy. Passing a schema type can let LangChain choose an appropriate structured-output strategy. ProviderStrategy and ToolStrategy also allow explicit strategy selection in compatible versions.

A structured response is the agent's final application-facing result, not the return value of an ordinary business tool. Schema validation can establish that data has the required shape, types and declared constraints. It cannot independently establish factual correctness, authorization, freshness or successful execution of an external action. Validate those properties using trusted application evidence before accepting the result.

This lesson builds on source question #13 (AI Agents #293), which validates tool inputs, and #16 (#296), which separates tool observations from application artifacts. The objective here is the final agent response contract and its consumption by downstream software. Source questions #22–24 examine strategy trade-offs, detailed Pydantic response design and invalid-output recovery separately.

1. Why structured final responses matter#

Imagine a support agent that retrieves the status of an authorized order. A human can understand the sentence "Your order has shipped." A downstream support dashboard, however, needs a predictable order identifier, status and evidence reference. Parsing arbitrary prose with string matching is fragile: the same model can phrase the answer differently, include qualifications, or describe a failed lookup.

A final response schema defines a machine-readable interface. The application can use that interface to populate a dashboard, route a case for human review, or generate presentation text from verified fields.

RepresentationIntended consumerExample
Ordinary final messageHuman reader or conversation UIYour order has shipped
Business tool argumentsTool runtimeorder_id=O-1
Business tool observationModel and authorized applicationVerified status shipped, evidence E-1
Final structured agent responseDownstream applicationorder_id, status, evidence_id
Authoritative domain recordBusiness serviceCurrent order status and access policy

These representations can coexist. A LangChain agent can use several tools during its execution, then produce a single structured final response. It may also retain the conversation and tool observations in its state.

Do not assume the structured response replaces all messages, and do not parse the last message as the primary result if the configured agent provides structured_response. Different strategies and adapters can represent the final message differently.

Loading diagram…

This is an architectural representation. Actual validation, correction, state updates and exception behavior depend on the chosen strategy and installed versions. The application must enforce the final acceptance decision.

2. Configure response_format and read structured_response#

The modern create_agent interface supports response_format for a final structured response. A practical initial design uses a named Pydantic model with explicit business fields. The following example uses the SupportAnswer model defined and tested in section 7.

PYTHON
from langchain.agents import create_agent from langchain.tools import tool @tool def get_demo_order_status(order_id: str) -> dict: """Read the status of a fictional order; no order is modified.""" if order_id == "O-1": return {"order_id": "O-1", "status": "shipped", "evidence_id": "E-1"} return {"order_id": order_id, "status": "unavailable", "evidence_id": None} agent = create_agent( model="openai:gpt-4o-mini", tools=[get_demo_order_status], response_format=SupportAnswer, system_prompt=( "Report only verified fictional order status. " "Use unavailable when evidence cannot establish a status. " "Never invent an evidence identifier." ), ) state = agent.invoke({ "messages": [{ "role": "user", "content": "What is the status of fictional order O-1?" }] }) candidate = state["structured_response"] print(candidate.model_dump_json())

The intended successful result is an instance of SupportAnswer representing the verified fictional order O-1. That outcome is not guaranteed by the prompt or schema alone. A model could produce an unsupported status, claim an unrelated evidence reference, or fail to complete the run.

SDK verification limitation: LangChain, langchain_core and langgraph were not installed locally. All framework-specific snippets in this article are illustrative and unexecuted. The SupportAnswer schema and independent acceptance function in section 7 were tested with Python 3.13.5 and Pydantic 2.13.5. Verify the exact response_format signature, schema compatibility, strategy behavior and final state representation in the installed release. The model identifier is illustrative, not a current provider availability claim.

The synthetic tool only returns public fictional fixtures. A real tool must enforce authenticated tenant and resource authorization. The host should retain trusted evidence from the verified domain operation rather than trust an evidence ID supplied by the model. The response schema is not an access-control policy.

Handle the completion boundary explicitly#

Only consume structured_response when the invocation has completed through the expected path. A paused, interrupted or failed run may have no accepted final response. Do not substitute an empty object and report success.

Use a controlled host boundary to distinguish successful completion, incomplete execution and invalid evidence. Avoid silently falling back to arbitrary natural-language output for a consumer that requires a schema.

PYTHON
def extract_candidate(state): if "structured_response" not in state: raise ValueError("No completed structured response") result = state["structured_response"] if result is None: raise ValueError("Structured response unavailable") return result # Illustrative host integration. The evidence mapping must be # established independently from authorized tool/service observations. candidate = extract_candidate(state) accepted = accept( candidate, expected_order="O-1", evidence={"E-1": ("O-1", "shipped")}, ) payload = accepted.model_dump(mode="json")

In a real deployment, the host also checks the runtime's completion and interrupt semantics, not just field presence. The hardcoded evidence in this illustration is a trusted synthetic fixture. Never construct the trusted evidence mapping from the candidate response itself.

For asynchronous invocation, the analogous pattern is await agent.ainvoke(...) followed by the same final acceptance and serialization steps. A partial streaming event is not necessarily a complete validated response. Stream-specific behavior has a later dedicated lesson.

3. Compare supported response schema forms#

Different applications have different needs. The common modern schema choices are summarized below; exact strategy support depends on the framework and provider.

Schema typeIntended final representationUseful propertiesImportant caveat
Pydantic BaseModelValidated model instanceTypes, Field constraints, validators and serializationLocal validation still cannot verify external facts
DataclassUsually dictionary in the structured response contractLightweight Python declaration, familiar fieldsOrdinary dataclass annotations do not enforce runtime types
TypedDictDictionaryTyped mapping contract for static checkingPython does not automatically validate a dict against TypedDict
JSON Schema dictionaryDictionaryLanguage-neutral interface and schema portabilitySupported dialect and validation enforcement vary

Pydantic is a convenient choice when the application needs a validated Python object and executable local constraints. Dataclasses and TypedDict are attractive for lightweight declarations. A JSON Schema dictionary is useful when a schema is already maintained as an external API contract.

Do not overgeneralize the word validated. LangChain's response strategies can parse and validate supported schema types, but exact constraints and returned objects are implementation-dependent. A regular dataclass constructor or TypedDict annotation does not independently validate arbitrary data supplied by another caller. Explicitly validate the result at the trust boundary if the framework's guarantee is insufficient.

Alternative schema examples#

The following Python declarations describe equivalent simplified response shapes. They are illustrative alternatives, not additional executed framework tests. They omit the executable cross-field evidence constraint implemented in section 7.

PYTHON
from dataclasses import dataclass from typing import Literal, TypedDict @dataclass class OrderStatusData: order_id: str status: Literal["shipped", "pending", "unavailable"] evidence_id: str | None class OrderStatusDict(TypedDict): order_id: str status: Literal["shipped", "pending", "unavailable"] evidence_id: str | None order_status_json_schema = { "type": "object", "properties": { "order_id": {"type": "string", "pattern": "^O-[0-9]+$"}, "status": { "type": "string", "enum": ["shipped", "pending", "unavailable"], }, "evidence_id": { "anyOf": [ {"type": "string", "pattern": "^E-[0-9]+$"}, {"type": "null"}, ] }, }, "required": ["order_id", "status", "evidence_id"], "additionalProperties": False, }

The evidence_id field is required but nullable. In other words, the response must explicitly include it, even when its value is null. This makes the absence of evidence visible and distinguishes omission from an intentional unavailable result.

In compatible versions, these declarations can be supplied as supported response schemas, either directly or through an explicit response strategy. Check the selected integration because a provider may support only a subset of JSON Schema keywords. Do not assume the schema above will be accepted by every provider.

For a JSON Schema contract, validate locally using an appropriate validator and supported dialect in addition to domain checks when required. Schema portability does not imply universal provider compatibility.

4. Introduce ProviderStrategy and ToolStrategy#

When response_format receives a supported schema directly, modern LangChain can select a suitable strategy based on model capabilities and framework behavior. The response_format interface also supports explicit strategy wrappers in compatible releases.

ProviderStrategy uses a provider-native structured-output capability where supported. The model provider receives a schema through its native API, and the integration parses the resulting structured response.

ToolStrategy uses the model's tool-calling mechanism to represent the desired final response. The framework provides a special structured-response tool definition and interprets its arguments as the final result. This is distinct from a business tool that reads an order or changes external state.

PYTHON
from langchain.agents import create_agent from langchain.agents.structured_output import ( ProviderStrategy, ToolStrategy, ) # Each configuration is an alternative, not a sequential pipeline. native_agent = create_agent( model="openai:gpt-4o-mini", tools=[get_demo_order_status], response_format=ProviderStrategy(SupportAnswer), ) tool_strategy_agent = create_agent( model="openai:gpt-4o-mini", tools=[get_demo_order_status], response_format=ToolStrategy(SupportAnswer), )

These examples are unexecuted. Verify the installed imports, constructor options, provider capabilities and simultaneous support for ordinary tools and native structured output. In particular, explicit native strategy selection requires a compatible provider/model. Do not assume automatic fallback or native-schema support just from a model's name.

The direct schema configuration, explicit ProviderStrategy and explicit ToolStrategy are alternative configuration approaches. They are not three sequential validation stages. The result contract should remain consistent across supported configurations, but provider-specific behavior and error handling can differ.

Loading diagram…

This overview is deliberately limited. The next source question compares these strategies in detail, including capability detection, strictness, tool coexistence, reliability and migration considerations.

5. Distinguish structured responses from structured tool outputs#

Both tools and agents can have a response_format option, but they refer to different contracts.

A tool configured with response_format="content_and_artifact" returns a pair containing model-facing content and a richer artifact for application use. Its output belongs to an individual tool call and may appear as a ToolMessage. It is intermediate evidence, not the final agent response.

An agent configured with response_format=SupportAnswer produces a final response according to that schema and makes it accessible through structured_response in the completed state.

AspectTool outputStructured agent response
ProducerA registered business operation or retrieval toolAgent orchestration and model
TimingDuring an individual tool callAt completion of the relevant agent run
Main purposeSupply an observation or artifactProvide a machine-readable task result
CorrelationTool-call IDAgent invocation, task and final state
ValidationDomain result and tool-output contractResponse schema plus independent acceptance checks
Side-effect implicationMay report an external operation's outcomeDoes not itself establish an external commitment

For example, a tool observation may say an authorized service found status shipped for O-1 with evidence E-1. The agent might then synthesize a final SupportAnswer. The final result is accepted only if it matches that independently verified observation. A model cannot manufacture an authoritative record by generating an object that resembles the tool's output.

Do not expose raw artifacts to the model merely to make a final schema easier to fill. Pass the minimal authorized evidence needed for the task, retain richer data at the application boundary, and validate references to that data.

6. Separate structural correctness from semantic acceptance#

A schema-valid result can still be wrong in several ways:

Candidate defectWhy ordinary shape validation is insufficient
Wrong order IDBoth O-1 and O-2 are syntactically valid
Unsupported statuspending may be an allowed enum value even when the actual order shipped
Fabricated evidence IDE-99 may match the expected string pattern
Stale evidenceA previously valid observation may not establish the current status
Unauthorized resourceCorrectly formatted private identifiers still require permission
False mutation successA Boolean or status string cannot prove an external commit

Design the host to independently establish what was requested, what resources are authorized and which observations are trustworthy. Then compare the structured response with that evidence. Do not use the model's self-reported confidence as proof.

For a structured-output agent that returns an intended write command, the host must separately validate the operation, obtain any required approval, and execute it through an authorized service. A proposed structured action is not the same as an executed action. Similarly, if the schema reports that an operation completed, confirm against authoritative transaction evidence before claiming success.

Loading diagram…

The example below implements shape, identifier and evidence-matching checks. Freshness, real authentication and disclosure policy remain the production host's responsibility. They are not silently assumed to have been implemented.

7. Tested Python implementation: validate an agent result against evidence#

The following standalone program uses actual Pydantic v2 rather than a simulated schema validator. It defines a response contract and a small application acceptance function. It can run without LangChain or model-provider access. All evidence and orders are synthetic.

PYTHON
from typing import Literal, Self from pydantic import BaseModel, ConfigDict, Field, model_validator, ValidationError class SupportAnswer(BaseModel): model_config = ConfigDict(strict=True, extra='forbid', frozen=True) order_id: str = Field(pattern=r'^O-[0-9]+$') status: Literal['shipped', 'pending', 'unavailable'] evidence_id: str | None = Field(pattern=r'^E-[0-9]+$') @model_validator(mode='after') def consistent(self) -> Self: if (self.status == 'unavailable') != (self.evidence_id is None): raise ValueError('evidence required exactly for verified status') return self def accept(candidate, expected_order, evidence): # Revalidate even an already-created instance at the trust boundary. raw = candidate.model_dump() if isinstance(candidate, SupportAnswer) else candidate answer = SupportAnswer.model_validate(raw) if answer.order_id != expected_order: raise ValueError('order mismatch') if answer.status != 'unavailable': if evidence.get(answer.evidence_id) != (expected_order, answer.status): raise ValueError('unsupported claim') return answer evidence = {'E-1': ('O-1','shipped'), 'E-2': ('O-2','pending')} base = {'order_id':'O-1','status':'shipped','evidence_id':'E-1'} a = accept(base,'O-1',evidence) assert a.status == 'shipped' assert SupportAnswer.model_validate_json(a.model_dump_json()) == a assert accept(a,'O-1',evidence) == a assert accept({'order_id':'O-1','status':'unavailable','evidence_id':None},'O-1',evidence).status == 'unavailable' assert set(SupportAnswer.model_json_schema()['required']) == set(base) for patch, error in [ ({'status':'delivered'}, ValidationError), ({'order_id':1}, ValidationError), ({'extra':'secret'}, ValidationError), ({'evidence_id':None}, ValidationError), ({'status':'unavailable'}, ValidationError), ({'order_id':'O-2'}, ValueError), ({'evidence_id':'E-2'}, ValueError), ({'status':'pending'}, ValueError), ({'evidence_id':'E-9'}, ValueError), ]: try: accept({**base, **patch}, 'O-1', evidence) except error: pass else: raise AssertionError(f'accepted {patch}') try: accept({'order_id':'O-1','status':'shipped'}, 'O-1', evidence) except ValidationError: pass else: raise AssertionError('accepted missing field') print('15 checks passed') print(a.model_dump_json())

Actual local execution using Python 3.13.5 and Pydantic 2.13.5 produced:

15 checks passed
{"order_id":"O-1","status":"shipped","evidence_id":"E-1"}

The five positive checks verify acceptance, JSON round-trip, revalidation of an existing model object, explicit unavailable status and required fields. Ten negative checks reject malformed or unsupported responses.

Negative fixtureExpected boundary
Status deliveredSchema enum
Integer order IDStrict type
Unexpected fieldExtra-field policy
Verified status with null evidenceCross-field rule
Unavailable status with evidenceCross-field rule
Wrong order IDRequested resource match
Evidence from another orderEvidence match
Valid but incorrect status pendingEvidence match
Unknown evidence IDEvidence match
Omitted evidence fieldRequired-field rule

The frozen model prevents ordinary reassignment of its fields, but does not itself establish authenticity. Revalidation converts an existing SupportAnswer instance to a dictionary before applying the model's validation. The example uses only scalar fields; a frozen Pydantic model is not a universal deep-immutability guarantee.

The schema's cross-field validator requires an evidence reference for a verified status and forbids one for unavailable. This is executable local validation; it is not necessarily represented completely in generated JSON Schema or enforced by a native provider. The application therefore must not rely solely on provider schema enforcement.

The evidence mapping must contain trusted, authorized observations established by the host. In the example, E-1 supports O-1 shipped and E-2 supports O-2 pending. The mapping is not generated from the candidate. In a real system, retain the source revision, timestamp, scope and operation identity as appropriate, and check freshness and current permissions before accepting claims.

An unavailable result makes no positive status claim. This example accepts it as a safe shape-compatible outcome even when evidence exists. A production quality evaluation should separately detect unnecessary abstention when the agent could have answered correctly. Safe abstention and successful task completion are different metrics.

The example is not an authentication system, a live tool integration, a complete provider-response validator or a general schema migration library. It does not test actual LangChain response parsing or the behavior of an agent on malformed model output.

8. Serialize the accepted response for production consumers#

For Pydantic, model_dump() returns Python data, model_dump(mode="json") returns JSON-compatible data for supported types, and model_dump_json() returns a serialized JSON string. Choose the representation expected by the downstream boundary. Avoid double-encoding a JSON string when a web framework already serializes response objects.

For the accepted result in section 7, a JSON response body could be:

JSON
{ "order_id": "O-1", "status": "shipped", "evidence_id": "E-1" }

A production API might add an application-owned envelope with schema_version, request_id and a completion status. Generate those envelope fields in trusted host code rather than ask the model to invent transaction identifiers, signatures or authorization metadata.

Version the external schema. Adding a required field or removing an enum value may break a consumer even if the model can produce the new object. Introduce compatible changes deliberately, coordinate producers and consumers, and test historical records and resumable workflows.

Use explicit serialization policies for dates, decimal amounts, UUIDs, binary attachments and nullable fields. A JSON-compatible representation does not prove a consumer interprets units or timestamps correctly. For money, use integer minor units or a reviewed decimal representation and state the currency.

Return only approved fields. Do not serialize the complete agent state to the user simply because it includes structured_response. Messages, runtime artifacts and traces can contain private or internal information. Apply access control and retention rules to every downstream data path.

9. Handle unavailable or incomplete results truthfully#

A response contract should allow the application to represent legitimate uncertainty. If a model must output either shipped or pending with no unavailable option, it may be pressured to choose a status despite missing evidence.

The correct contract depends on the domain. In this fictional example, unavailable is a valid final status and evidence_id must explicitly be null. Other workloads might need a separate error envelope, human-review status, or incomplete outcome. Do not collapse all errors into a normal response if doing so hides an important operational failure.

When the model or framework fails to produce a valid structured response, treat it as incomplete execution. Apply bounded correction only when the failure is correctable and the remaining run budget allows it. Distinguish provider rejection, missing result, schema violation and business-evidence mismatch. Never silently relax a critical schema or policy merely to obtain a result.

Detailed handling of invalid structured output and strategy-specific correction behavior is reserved for source question #24. For now, the invariant is that the downstream consumer receives an accepted result or a truthful controlled failure, not a guessed record.

10. Production integration and evaluation#

Test the schema and domain acceptance independently, then exercise the actual agent runtime with a compatible installed release and a controlled model substitute.

Loading diagram…

The service-to-host evidence flow is an application design choice, not an automatic LangChain feature. Implement it through a trusted repository, service record or validated tool result captured by the host. Do not reconstruct evidence solely from untrusted model text.

Test layerAcceptance criterion
Schema unit testsRequired fields, strictness, nullability and declared constraints behave as intended
Domain evidence testsWrong identifier, fabricated reference and unsupported status rejected
Agent configurationActual response_format is accepted by the installed framework
Strategy integrationSelected provider or tool mechanism produces expected final state
Tool coexistenceOrdinary business tools and final structured response work together
Incomplete invocationMissing or paused final response never reported as success
Provider compatibilityActual generated schema and supported constraints inspected
SerializationAccepted object round-trips through the intended API or storage boundary
Authorization and privacyPrivate or cross-tenant evidence cannot be used or disclosed
Regression evaluationVerified task success remains acceptable across model/schema revisions

Use scripted model outputs to force invalid cases through the actual agent execution path where supported. Test malformed output, multiple structured response proposals, interrupted runs and provider schema rejection. Then run separately approved synthetic live-provider smoke tests. The exact recovery behavior must be tested for the chosen strategy rather than inferred from the standalone Pydantic checks.

Measure schema-valid response rate, evidence-supported response rate, end-to-end verified task success, unnecessary abstention, correction attempts, latency and cost per accepted result. Define each denominator before reporting metrics.

For a hypothetical evaluation of 100 tasks, suppose 96 responses satisfy the schema but only 90 satisfy the independent evidence contract. The schema-valid rate is 96%, the accepted-result rate is 90%, and six schema-valid responses fail the evidence check. Those figures are illustrative, not measured provider performance. A dashboard showing only the schema-valid rate would hide those unsupported results.

Keep schema revision, framework and integration versions, selected strategy, safe correlation identifiers and normalized validation outcomes in telemetry. Do not dump private tool payloads or full agent state into logs by default. Store detailed diagnostic evidence only under appropriate access and retention controls.

Common mistakes#

  • Parsing the last AI message instead of consuming the configured structured_response contract.
  • Confusing a tool's content_and_artifact format with an agent's final response schema.
  • Treating valid JSON as proof that a response meets the required schema.
  • Treating schema-valid output as proof that a claim is accurate or authorized.
  • Assuming dataclass or TypedDict annotations independently enforce runtime constraints.
  • Assuming a provider supports every JSON Schema keyword and Python validator.
  • Returning raw agent state instead of an approved response projection.
  • Reporting success when the agent is paused, failed or lacks a completed accepted response.
  • Automatically executing a model-generated structured action without independent permission and commitment checks.

Interview-ready answer#

I configure modern LangChain create_agent with response_format set to a supported schema such as a Pydantic BaseModel and retrieve the completed result through structured_response. The framework can select a structured-output strategy or I can explicitly configure a compatible ProviderStrategy or ToolStrategy. I distinguish this final application-facing object from ordinary intermediate tool observations. I validate declared schema constraints, independently compare claims with authorized and current domain evidence, and serialize only the accepted response for consumers. I test actual framework and provider integration separately from local schema tests, and represent missing evidence or incomplete execution honestly instead of fabricating a valid-looking object.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. Actual local execution on Python 3.13.5 and Pydantic 2.13.5 passed all 15 checks in the standalone acceptance program. Local inspection confirmed langchain, langchain_core and langgraph were absent. SDK examples, alternative schema integration, automatic strategy selection, provider behavior and live documentation were not executed or version-verified. All order records and evaluation figures are synthetic. Mermaid diagrams use standard triple-backtick fences; live rendering and public website display were not verified.

References

  1. 1.
    LangChain structured outputdocs.langchain.com
  2. 2.
    LangChain agentsdocs.langchain.com
  3. 3.
    LangChain modelsdocs.langchain.com
  4. 4.
    LangChain toolsdocs.langchain.com
  5. 5.
    LangChain API referencereference.langchain.com
  6. 6.
    Pydantic modelsdocs.pydantic.dev
  7. 7.
    Pydantic validatorsdocs.pydantic.dev
  8. 8.
    Pydantic serializationdocs.pydantic.dev
  9. 9.

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.