pythonintermediate

Structured LLM Output with Pydantic

Parse LLM responses into validated Pydantic models using LangChain's structured output binding.

python
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from typing import Optional

class MovieReview(BaseModel):
    title:       str                = Field(description='Movie title')
    year:        int                = Field(description='Release year')
    rating:      float              = Field(ge=0, le=10, description='Rating 0-10')
    genres:      list[str]          = Field(description='List of genres')
    summary:     str                = Field(description='One-sentence summary')
    recommended: bool               = Field(description='Worth watching?')

llm = ChatOpenAI(model='gpt-4o-mini')
structured_llm = llm.with_structured_output(MovieReview)

review = structured_llm.invoke('Review the movie Inception from 2010.')
print(review.model_dump_json(indent=2))

Use Cases

  • structured extraction
  • LLM output validation
  • typed AI responses

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.