Parsing Outputs with LangChain
Learn how to parse the output of an LLM as structured information using output parsers in the LangChain framework.
We'll cover the following...
LLMs typically provide a string of text as an output. However, when creating an LLM-powered application, we might need a more structured and formatted output that provides us with concise information rather than reading the complete response.
Output parsers
Parsers are a tool that can help us in getting a structured output. If we don’t use parsers for our responses, then the expected output will be a plain text as a string.
LangChain provides us with different types of parsers. All parsers take either a string or a Message
as the input. The output depends on the type of parser being used. Let’s explore them:
Parser type | Details |
| Parses texts from message objects. Useful for handling variable formats of message content (e.g., extracting text from content blocks). |
| Returns a list of comma-separated values. |
| Parses response into a |
| Parses response into one of the provided enum values. |
| Returns a JSON object as specified. You can specify a Pydantic model and it will return JSON for that model. Probably the most reliable output parser for getting structured data that does NOT use function calling. |
| Wraps another output parser. If that output parser errors, then this will pass the error message and the bad output to an LLM and ask it to fix the output. |
| Useful for doing operations with pandas DataFrames. |
| Takes a user defined Pydantic model and returns data in that format. |
| Wraps another output parser. If that output parser errors, then this will pass the original inputs, the bad output, and the error message to an LLM and ask it to fix it. Compared to OutputFixingParser, this one also sends the original instructions. |
| An output parser that returns structured information. It is less powerful than other output parsers since it only allows for fields to be strings. This can be useful when you are working with smaller LLMs. |
| Returns a dictionary of tags. Use when XML output is needed. Use with models that are good at writing XML (like Anthropic's). |
| Takes a user defined Pydantic model and returns data in that format. Uses YAML to encode it. |
Most parsers support two common methods:
get_format_instructions()
: This method returns the formatting instructions in a string format. This information is sent to the model, allowing it to format the output as per our requirements.parse()
: This method parses the string output from the model and returns an object of the required type.
For the sake of simplicity, we’ll only discuss the Datetime, CSV, and Pydantic parsers in detail.
Datetime parser
The DatetimeOutputParser
converts the date and time in a string to a ...