Output Parsers
A model always gives you back an AIMessage full of text.
But your program often wants something else. A plain string. A list. A dict.
An output parser is a little machine that turns the message into the shape you want.
Think of a coin sorter. Mixed coins go in. Neat stacks come out.
StrOutputParser: just the words
The simplest parser pulls out .content and hands you a string.
Every parser has invoke, just like a model. You feed it the message, it feeds you the result.
You will see this parser at the end of almost every chain.
CommaSeparatedListOutputParser: a Python list
Ask the model for items separated by commas. The parser splits them into a real list.
get_format_instructions returns a sentence telling the model how to format its answer. You paste it into your prompt.
The model follows the instructions. The parser trusts them and splits on commas.
JsonOutputParser: a dict
Ask for JSON, and the parser turns the text into a Python dict.
Now you can use square brackets like any dict. No string slicing needed.
If the model wraps the JSON in a code fence, the parser strips it off for you.
PydanticOutputParser: a checked object
A dict is loose. Pydantic lets you describe the exact shape you want and checks it.
The class describes the fields. The format instructions describe the class to the model.
If the model returns bad data, say age is a word, the parser raises an error instead of passing junk along.
A better way is coming
Parsers that read JSON out of text are a bit fragile. Modern models can be asked for structured output directly with with_structured_output.
That method uses the model's own JSON mode or tool calling. It is more reliable and needs no format instructions.
We cover it in lesson 12. For now, know that PydanticOutputParser still matters for models without that feature.
Which parser when
StrOutputParser: you just want the text. Use this most of the time.
CommaSeparatedListOutputParser: a short flat list of words.
JsonOutputParser: a dict, and you do not need strict checking.
PydanticOutputParser: a dict with checked types, on models without structured output.
Remember: a parser has invoke just like a model. Message goes in, the shape you want comes out.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.