pythonintermediate
Structured LLM Output with Pydantic
Parse LLM responses into validated Pydantic models using LangChain's structured output binding.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
Best for: Review analysis
#ai#openai
pythonintermediate
LangChain Pydantic Output Parser
Use LangChain's PydanticOutputParser to reliably parse structured data from LLM text responses.
Best for: information extraction
#langchain#pydantic
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai
typescriptintermediate
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
Best for: data extraction
#openai#zod