AI Hints
Home›LangChain Tutorial›Structured Output
LangChain · Lesson 30 of 120

with_structured_output

Typed answers.

⏱ 2 min read▶ Video at 32:07🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Now the key method. With structured output takes your Pydantic model, and returns a new runnable, that always answers with an instance of it.

with_structured_output
From the video: with_structured_output
  • Give it your model
  • Get a new runnable
  • Answers are objects

Asking for a Book

We call with structured output on the chat model, passing the book class. Then we invoke it with a plain question. Run it. Instead of a paragraph, we get a book object. Its year is a real integer, so we can do maths with it, and genres is a real list.

structured.pypython
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class Book(BaseModel):
    title: str
    year: int = Field(description="year first published")
    genres: list[str] = Field(description="1 to 3 genres")

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
structured = model.with_structured_output(Book)

book = structured.invoke("Tell me about the novel Frankenstein.")
print(book)
print("age in 2026:", 2026 - book.year, "| first genre:", book.genres[0])
Output
title='Frankenstein' year=1818 genres=['Gothic fiction', 'Science fiction', 'Horror']
age in 2026: 208 | first genre: Gothic fiction

How it works

Behind the scenes, LangChain turns your class into a schema, and uses the provider's own structured output or tool calling feature, so the model is guided to produce exactly those fields. Then the reply is checked by Pydantic. You get a valid object, or a clear error.

keyvalue
Your class→ a JSON schema
Providerguided to the schema
Pydanticchecks the reply
Resulta valid object

Summary

With structured output makes a model return instances of your Pydantic class, with real types. Next, lists and nested data.

Key takeaways
  • model.with_structured_output(Book)
  • Returns a Book
  • Real types
Next up: Lists and Nested Data — richer shapes