Lesson 4 of 9 · Core
Output Parsers
Turn LLM replies into data with LangChain: StrOutputParser, JsonOutputParser, PydanticOutputParser and with_structured_output, plus validation and retries.
- 8 min read
- Intermediate
- Reviewed
- Get plain text from a reply with StrOutputParser
- Parse JSON replies with JsonOutputParser
- Get validated objects with with_structured_output and a Pydantic schema
- Use PydanticOutputParser for models without structured output support
- Handle replies that don't fit the schema
From text to data
A chat model returns a message. Your program usually needs something more specific: a string to show, a dictionary to store, or an object with typed fields to act on.
The best option: structured output
Most modern chat models can be told to reply in a fixed structure. In LangChain, describe the structure as a Pydantic class and call with_structured_output:
from typing import Literal
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
class ReviewAnalysis(BaseModel):
"""Structured analysis of one customer review."""
sentiment: Literal["positive", "negative", "mixed"]
topics: list[str] = Field(description="Short topics the review mentions, e.g. delivery, battery")
needs_reply: bool = Field(description="True if the customer asks for help or is unhappy")
model = init_chat_model("anthropic:MODEL_NAME")
analyser = model.with_structured_output(ReviewAnalysis) # the reply comes back as a ReviewAnalysis
result = analyser.invoke("Great bike, but the battery died after two weeks. Can you help?")
print(result)
print(result.needs_reply, result.topics)sentiment='mixed' topics=['bike quality', 'battery'] needs_reply=True True ['bike quality', 'battery']
The class's field names, types and descriptions become instructions to the model, usually sent through the provider's tool-calling or structured-output feature. The reply is checked against the class and returned as a real Python object, so result.needs_reply is a bool you can use in an if, with no string handling.
Parsers in a chain
Parsers are Runnables too, so they go at the end of a chain:
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import JsonOutputParser, StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
model = init_chat_model("anthropic:MODEL_NAME")
# StrOutputParser: just the text of the reply
slogan = ChatPromptTemplate.from_template("Write a 6-word slogan for {shop}.") | model | StrOutputParser()
print(slogan.invoke({"shop": "a bike repair café"}))
# JsonOutputParser: parse a JSON reply (it copes with Markdown code fences around it)
extract = (
ChatPromptTemplate.from_template(
"Extract the city and date from: {text}\nAnswer with JSON with keys city and date (YYYY-MM-DD)."
)
| model
| JsonOutputParser()
)
print(extract.invoke({"text": "I'm arriving in Porto on the 3rd of May 2027."}))Broken bikes in, happy riders out.
{'city': 'Porto', 'date': '2027-05-03'}StrOutputParserreturns the reply's text, the most common last step of a chain.JsonOutputParserparses JSON from the reply into a dictionary. Models often wrap JSON in Markdown code fences, as in this reply, and the parser copes with that.
What a parser does, in plain Python
Here's the work of a JSON parser with a schema check: find the JSON, parse it, check the fields, and report what's wrong so the application can retry:
import json, re
# What an output parser does, in plain Python: find the JSON in a messy reply, then check it.
SCHEMA = {"city": str, "nights": int}
FENCE = "`" * 3 # three backticks, the Markdown code fence
def parse_reply(text):
fenced = re.search(FENCE + r"(?:json)?\s*(.*?)" + FENCE, text, re.S) # prefer a fenced block
candidate = fenced.group(1) if fenced else text[text.find("{"): text.rfind("}") + 1]
try:
data = json.loads(candidate)
except json.JSONDecodeError as e:
return None, [f"not valid JSON ({e.msg})"]
problems = [f"missing {k}" for k in SCHEMA if k not in data]
problems += [f"{k} should be {t.__name__}" for k, t in SCHEMA.items()
if k in data and not isinstance(data[k], t)]
return (data if not problems else None), problems
replies = [
'{"city": "Porto", "nights": 3}',
f'Sure! Here is the JSON:\n{FENCE}json\n{{"city": "Lisbon", "nights": 2}}\n{FENCE}\nAnything else?',
'The booking is {"city": "Faro", "nights": "two"}',
"I'm sorry, I can't help with that.",
]
for r in replies:
data, problems = parse_reply(r)
print(f"{r[:34]!r:<38} -> {data if data else 'RETRY: ' + '; '.join(problems)}")Two replies parsed. One had the wrong type ("two" instead of a number), and one wasn't JSON at all. Those are exactly the cases your application must plan for.
PydanticOutputParser
If a model can't do structured output, put the parser's format instructions in your prompt and parse the text reply:
from pydantic import BaseModel
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import PydanticOutputParser
class Booking(BaseModel):
city: str
nights: int
parser = PydanticOutputParser(pydantic_object=Booking)
print(parser.get_format_instructions()[:120], "...") # text to put in your prompt
print(parser.parse('{"city": "Porto", "nights": 3}'))
try:
parser.parse('{"city": "Porto", "nights": "a few"}') # a reply that breaks the schema
except OutputParserException as e:
print("Could not parse:", str(e)[:39], "...")The output should be formatted as a JSON instance that conforms to the JSON schema below. As an example, for the schema ... city='Porto' nights=3 Could not parse: Failed to parse Booking from completion ...
A reply that breaks the schema raises OutputParserException. Catch it and decide: retry (often with the error message added to the prompt so the model can fix its mistake), fall back to a default, or ask a person.
Common mistakes
Clean up a model reply before parsing it, as JsonOutputParser does for replies wrapped in Markdown code fences.
import json
replies = ['```json\n{"city": "Porto"}\n```', '{"city": "Faro"}', 'Here you go:\n```\n{"city": "Braga"}\n```']
# For each reply: if it contains ``` take the text between the first two ``` marks
# (and drop the word json if it starts with it); otherwise use the reply as it is.
# Then parse it with json.loads and print the city.
Why is with_structured_output usually better than asking for JSON and parsing the text?
Summary
- Output parsers turn replies into text, dictionaries or validated objects.
- Prefer
with_structured_outputwith a Pydantic class; field descriptions andLiteraltypes guide the model. StrOutputParserandJsonOutputParserend many chains.PydanticOutputParseradds format instructions for models without structured output.- Plan for failures: catch
OutputParserException, retry with the error, then fall back.
Next: chains with LCEL.
Finished reading? Tick it off to track your progress.