LangChain Module 3: Structured Output with Pydantic
Introduction
Applications need data, not paragraphs. LangChain lets you describe the shape you want with a Pydantic model and get a validated object back. This module shows how to use it directly on a model and with agents.
Prerequisites
- Module 2 completed
- Familiarity with Pydantic models (BaseModel and Field)
Step-by-Step Guide
Step 1: Define the schema
Use a Pydantic model with typed fields. Field descriptions are sent to the model, so write them as instructions that explain what each field means.
from pydantic import BaseModel, Field
class Movie(BaseModel):
"""Details about a movie."""
title: str = Field(description="The movie's title")
year: int = Field(description="The year it was released")
director: str = Field(description="The director's full name")Step 2: Use with_structured_output
Wrap a model with the schema. The wrapped model returns an instance of your class instead of a message, so you can use attributes directly.
structured_model = model.with_structured_output(Movie)
movie = structured_model.invoke("Tell me about the movie Inception.")
print(movie.title, movie.year, movie.director)Step 3: Use response_format with agents
When you build an agent, pass the schema as response_format. The validated object is returned under the structured_response key of the result. The tools lesson explains agents in detail.
from langchain.agents import create_agent
agent = create_agent(model=model, response_format=Movie)
result = agent.invoke(
{"messages": [{"role": "user", "content": "Tell me about the movie Inception."}]}
)
print(result["structured_response"])Step 4: Know the schema options and limits
Pydantic models return validated instances, while dataclass, TypedDict, and JSON Schema inputs return dictionaries. A JSON Schema dictionary must be wrapped in an explicit strategy such as ToolStrategy or ProviderStrategy, and needs a top-level title and description. Use Pydantic when you can, since it also validates.
Step 5: Validate meaning, not just shape
A schema guarantees the structure, not the truth. Add your own checks, such as plausible ranges and cross-checks with trusted data, and decide what to do with outputs that fail.
FAQs
- Why not just ask for JSON in the prompt?
- Structured output uses the provider's native mechanisms or tool calling to enforce the schema, so you avoid parsing errors, stray commentary, and missing fields.
- What if my model does not support native structured output?
- LangChain falls back to a tool-calling strategy for models without native support, so the same code usually still works.
Summary
Describe the output with a Pydantic model, use with_structured_output on a model or response_format on an agent, and still validate the content in your own code.
Comments
Log in or create a free account to join the discussion.