PydanticOutputParser
Strict schema validation. Why JSON Mode isn't enough.
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.
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 access3. 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."