Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 32 ยท Models, Prompts and Parsers

Output Parsers

Turn model replies into usable data with LangChain output parsers: StrOutputParser, JsonOutputParser, PydanticOutputParser and list parsers, with format instructions and error handling.

A chat model returns an AIMessage whose content is text. Programs want strings, lists, numbers and objects. An output parser is the last step of a chain: it takes the model's reply and converts it into the shape your code needs. Parsers are Runnables too, so they slot in after the model with |.

StrOutputParser: just the text

The simplest and most common parser extracts .content from the message and returns a plain str:

Python
from langchain_core.output_parsers import StrOutputParser

chain = prompt | model | StrOutputParser()
chain.invoke({"topic": "DNS"})        # "DNS translates names into IP addresses..."

Without it, you get an AIMessage and must write .content yourself. With it, a chain ends in a clean string, and streaming gives you string chunks.

JsonOutputParser

When you ask for JSON, the reply is still a string that happens to contain JSON, sometimes wrapped in a Markdown code fence or preceded by chatter. JsonOutputParser strips the wrapping and parses it into a Python dict or list:

Python
from langchain_core.output_parsers import JsonOutputParser

parser = JsonOutputParser()
prompt = ChatPromptTemplate.from_messages([
    ("system", "Reply only with JSON. {format_instructions}"),
    ("human", "Give name and year for the language {language}."),
]).partial(format_instructions=parser.get_format_instructions())

chain = prompt | model | parser
chain.invoke({"language": "Python"})   # {'name': 'Python', 'year': 1991}

get_format_instructions() returns text you paste into the prompt that tells the model the expected shape. It can also stream partial JSON objects as they grow.

PydanticOutputParser: validated objects

A dict can still have missing keys or wrong types. Describe the shape with a Pydantic model and the parser validates what comes back:

Python
from pydantic import BaseModel, Field
from langchain_core.output_parsers import PydanticOutputParser

class Book(BaseModel):
    title: str
    year: int = Field(description="Year of first publication")
    genres: list[str]

parser = PydanticOutputParser(pydantic_object=Book)
chain = prompt | model | parser
book = chain.invoke({"topic": "a classic dystopian novel"})
print(book.title, book.year)

You get a real Book object, or a clear validation error. The next lesson shows the modern alternative, with_structured_output, which uses the provider's native structured-output feature instead of asking nicely in the prompt. Parsers are still valuable when a model does not support that feature.

List and other simple parsers

CommaSeparatedListOutputParser splits "red, green, blue" into ["red", "green", "blue"]. There are also parsers for numbered lists, Markdown lists, booleans, XML and datetimes. They all share the same two jobs: give format instructions and parse the reply.

The two jobs of a parser (runnable)

This stand-in builds a small parser class with both jobs, plus the "clean the fence" step that makes JSON parsing forgiving.

Python Stand-in: a JSON parser that tolerates code fences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last case is the realistic failure: the model ignored the instructions and returned prose. Real parsers raise OutputParserException with the offending text so you can see what went wrong.

Validating with a schema (runnable)

Pydantic is the real tool. Pyodide includes pydantic, so you can run actual Pydantic validation here: the part LangChain delegates to it. (The LangChain parser class itself is only shown read-only above.)

Python Real Pydantic validation of a parsed dict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fixing and retrying bad output

Parsing can fail. Options, from cheap to elaborate:

  1. Better prompt: include format instructions and one example.
  2. OutputFixingParser: on failure it sends the bad text and the error back to a model asking for a corrected version.
  3. RetryOutputParser: re-asks with the original prompt too.
  4. Native structured output (next lesson) which makes failures rare.
  5. A retry wrapper around the whole chain with .with_retry() (see retries and fallbacks).

The retry idea in plain Python: try to parse, and on failure ask the "model" again with the error message.

Python Stand-in: parse, and on failure ask again with the error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Choosing a parser

You want Use
Plain text StrOutputParser
A dict or list from JSON JsonOutputParser
A validated typed object PydanticOutputParser or with_structured_output
A Python list from comma text CommaSeparatedListOutputParser
A full AIMessage (metadata, tool calls) No parser: leave the message

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does StrOutputParser return?

    It extracts .content, so the chain ends in a str.
  2. 2. What is get_format_instructions() for?

    You put those instructions in the prompt so the model's reply can be parsed.
  3. 3. Why use PydanticOutputParser instead of JsonOutputParser?

    Pydantic checks that fields exist and have the right types, so bad output fails early with a clear error.
  4. 4. What does OutputFixingParser do when parsing fails?

    It sends the bad text and error back to a model to repair it.

Summary

  • A parser is the last chain step that converts an AIMessage into the data your code needs.
  • StrOutputParser gives text; JsonOutputParser gives dicts; PydanticOutputParser gives validated objects.
  • Parsers supply format instructions for the prompt and raise errors on bad output.
  • Recover with better prompts, fixing parsers, retries or native structured output.

Next: Structured Output