Learn/LangChain Mastery/Part 3 · 2. LCEL & Prompt Architecture
Lesson 18 of 68
SyllabusLangChain Mastery · Part 3

PydanticOutputParser

Strict schema validation. Why JSON Mode isn't enough.

Course outline & contents
LangChain Mastery
Your First Chatbot: Talking to an LLMLCEL: Why LangChain Is a Composition EngineThe Runnable Protocol (invoke, batch, stream)Pipe Operator & Data FlowRunnableLambda & Custom LogicRunnableParallel & BranchingPromptTemplate vs ChatPromptTemplateSystem, Human, AI MessagesPrompt Architecture & ReusabilityStructured Output with JSON ModePydanticOutputParserOutputFixingParserStreaming Tokens & Async Chains

JSON Mode guarantees valid JSON. It does not guarantee correct schema.

You asked for: {"name": str, "age": int} The model returns: {"full_name": "Bob", "years_old": 30}

It is valid JSON. But your code data["age"] crashes.

Pydantic is the standard data validation library in Python. LangChain uses it to define schemas.

pydantic_chain.py
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.output_parsers import PydanticOutputParser

# 1. Define the Schema
class Joke(BaseModel):
  setup: str = Field(description="The setup of the joke")
  punchline: str = Field(description="The funny part")
  rating: int = Field(description="Rating from 1 to 10")

# 2. Create the Parser
parser = PydanticOutputParser(pydantic_object=Joke)

# 3. Inject Instructions into Prompt
# The parser generates format instructions for us!
print(parser.get_format_instructions())
# "The output should be formatted as a JSON instance that conforms to..."

prompt = ChatPromptTemplate.from_template(
  "Tell a joke about {topic}.\n{format_instructions}"
)

# 4. The Chain
chain = prompt.partial(format_instructions=parser.get_format_instructions()) | model | parser

# 5. Result
joke_obj = chain.invoke({"topic": "bears"})
print(joke_obj.setup)      # Safe access
print(joke_obj.punchline)  # Safe access

If the model returns a string for rating ("5/10"), Pydantic will try to cast it to an int (5). If it fails, it throws a validation error. You fail fast and safe.

Don't trust the model to remember field names. Inject the schema into the prompt, and validate the output with Pydantic.

Key Intuition: "Trust is enforced, not assumed."

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonStructured Output with JSON ModeNext lesson →OutputFixingParser