LangChain Output Parsers
LangChain output parsers convert the raw text a chat model returns into a Python value your program can use, such as a string, a dictionary or a list. They sit at the end of a chain.
StrOutputParser
The most common parser simply extracts the text content from an AIMessage. You already used it in the LCEL lesson. Use it whenever you want plain text.
JsonOutputParser
JsonOutputParser parses JSON text into a dictionary. Its get_format_instructions method gives text you can put in the prompt to tell the model what to produce:
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import ChatOllama
parser = JsonOutputParser()
prompt = ChatPromptTemplate.from_template(
"Return a JSON object with keys name and country for the city {city}. "
"Only output JSON.\n{format_instructions}"
).partial(format_instructions=parser.get_format_instructions())
llm = ChatOllama(model="llama3.2", temperature=0, format="json")
chain = prompt | llm | parser
data = chain.invoke({"city": "Lahore"})
print(data, type(data))Sample output:
{'name': 'Lahore', 'country': 'Pakistan'} <class 'dict'>format="json" asks Ollama to constrain the model to valid JSON, which makes small models far more reliable. JsonOutputParser also supports streaming partial JSON as it arrives.
Comma-Separated List Parser
from langchain_core.output_parsers import CommaSeparatedListOutputParser
list_parser = CommaSeparatedListOutputParser()
chain = (
ChatPromptTemplate.from_template("List 4 {thing}, comma separated, nothing else.")
| ChatOllama(model="llama3.2", temperature=0)
| list_parser
)
print(chain.invoke({"thing": "primary school subjects"}))Sample output: ['Math', 'English', 'Science', 'Art']
Custom Parsing with a Function
Any function can act as a parser in a chain. This one extracts a number from the reply:
import re
def to_number(msg) -> float:
match = re.search(r"-?\d+(\.\d+)?", msg.content)
return float(match.group()) if match else float("nan")
chain = ChatPromptTemplate.from_template("What is {expr}? Answer with the number only.") | ChatOllama(model="llama3.2", temperature=0) | to_number
print(chain.invoke({"expr": "17 + 25"}) * 2)Sample output: 84.0
Parsers vs Structured Output
- Parsers work with any model because they only read text.
- Text parsing can fail if the model adds extra words; always handle errors.
- For typed objects, prefer with_structured_output (next lesson), which uses the provider's native JSON schema or tool-calling support.
Frequently asked questions
Why does my JsonOutputParser raise OutputParserException?
The model returned text that is not valid JSON, often with extra explanation. Tell it to output only JSON, use a lower temperature, set format="json" for Ollama, or switch to with_structured_output.
Is PydanticOutputParser deprecated?
It still exists in langchain-core, but with_structured_output is the recommended way to get Pydantic objects from models that support it.
Can output parsers stream?
Yes. StrOutputParser and JsonOutputParser stream, so you can display partial results while the model is still generating.