Skip to content
derpx06.dev
WritingExplainersNotesAbout
works on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisationworks on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisation

Learning in public.

A student's notebook on system design, distributed systems and databases. Shared as I learn.

ReadWritingExplainersNotesAbout
ElsewhereGitHubLinkedInHugging FaceLeetCode
Say hellomanaskhairnar1511@gmail.com
derpx06
NORMALmain© 2026 Derpx06Pune, Indiatop ↑
Learn/LangChain Mastery/Part 3 · 2. LCEL & Prompt Architecture
Lesson 18 of 68

PydanticOutputParser

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

Derpx0610 Jan · 1 min read
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
Contents
1. The Problem: Missing Fields2. The Solution: Pydantic3. Why This is Powerful4. Summary
0% read · 1 min leftBack to top ↑
Course outline & contents0%
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
Contents
1. The Problem: Missing Fields2. The Solution: Pydantic3. Why This is Powerful4. Summary

1. The Problem: Missing Fields

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.

2. The Solution: Pydantic

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

3. Why This is Powerful

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.

4. Summary

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