Session 6· 08· 15 min
Structured Output with Pydantic
What you'll learn
- ▸Use model.with_structured_output(PydanticModel)
- ▸Get a typed Python object back from any provider
- ▸Compare to Session 5's responses.parse() approach
with_structured_output wraps the model so every call returns a typed Pydantic instance instead of free-form text. Under the hood LangChain uses the provider's best structured-output mechanism — JSON schema for OpenAI, tool-style for Claude, schema hint for Gemini. Same line of Python code either way.
scripts/08_structured_output_pydantic.py
from pydantic import BaseModel, Field ①
class Movie(BaseModel):
"""A movie with details.""" ②
title: str = Field(description="Movie title")
year: int = Field(description="Release year")
director: str = Field(description="Director name")
rating: float = Field(description="Rating out of 10")
structured = model.with_structured_output(Movie) ③
result = structured.invoke("Tell me about the movie Inception.") ④
print(result.title, result.year, result.director, result.rating) ⑤①Pydantic BaseModel + Field(description=…) — descriptions help the model understand each field.
②The class docstring becomes the overall schema description.
③with_structured_output returns a NEW runnable that will always produce a Movie.
④invoke returns a Movie instance directly — no json.loads, no .output_parsed.
⑤Typed attributes — your IDE knows result.title is a string.
$ python scripts/08_structured_output_pydantic.py
Session 5 parse()
- •client.responses.parse(..., text_format=Movie)
- •response.output_parsed
- •OpenAI-only
Session 6 with_structured_output
- •model.with_structured_output(Movie).invoke(...)
- •Result is Movie directly
- •Works on OpenAI, Claude, Gemini, more
Knowledge Check
What does with_structured_output return?
Recap — what you just learned
- ✓with_structured_output(PydanticModel) is the LangChain equivalent of responses.parse
- ✓invoke() on the wrapped model returns a typed Pydantic instance
- ✓Same code works on every provider LangChain supports
- ✓Use Field(description=…) to give each field a hint the model understands