AI Hints
Home›LangChain Tutorial›Examples, Chains, Parsers
LangChain · Lesson 18 of 120

Output Parsers

Just the text.

⏱ 2 min read▶ Video at 18:25🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

A chain that ends with a model returns an AI message. Usually we just want the text. An output parser is a final step that reshapes the model's reply.

Output Parsers
From the video: Output Parsers
  • Chains return AIMessage
  • We want text
  • A parser reshapes it

StrOutputParser

String output parser takes an AI message, and returns just its text, as a normal Python string. We add it to the end of the chain, with another pipe. Run it. The result is now a plain string, ready to print, save, or send to another step.

parser.pypython
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
prompt = ChatPromptTemplate.from_template("Name one classic novel about {theme}. Title only.")

chain = prompt | model | StrOutputParser()
result = chain.invoke({"theme": "the sea"})
print("is a string:", isinstance(result, str), "->", result)
Output
is a string: True -> Moby-Dick

Parsing a list

Parsers can do more. The comma separated list parser splits text into a Python list. We ask the model for comma separated genres, and the parser does the splitting. Run it. We get a real list, with a length we can check, not just a string with commas in it.

list_parser.pypython
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import CommaSeparatedListOutputParser

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
prompt = ChatPromptTemplate.from_template(
    "List 4 book genres, comma separated, nothing else.")

chain = prompt | model | CommaSeparatedListOutputParser()
genres = chain.invoke({})
print(genres, len(genres))
Output
['Fantasy', 'Mystery', 'Romance', 'Sci-Fi'] 4

Summary

Output parsers turn the model's reply into what you need. Str output parser gives text, and list parsers split it up. For structured data, there's a better tool, which we'll meet soon. Next, runnables.

Key takeaways
  • StrOutputParser
  • List parser
  • Last step of a chain
Next up: Runnables — one interface