Output Parsers
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/output_parsers/base.py
- libs/core/langchain_core/output_parsers/string.py
- libs/core/langchain_core/output_parsers/json.py
- libs/core/langchain_core/output_parsers/pydantic.py
- libs/langchain/langchain/output_parsers/retry.py
- libs/langchain/langchain/output_parsers/format_instructions.py
Output Parsers are a fundamental component in LangChain responsible for structuring the output from Language Models (LLMs). LLMs typically return text strings, which may not be in a ready-to-use format for downstream applications. Output Parsers bridge this gap by taking the raw text from an LLM and converting it into a structured format, such as JSON, a Pydantic object, or a simple string.
These components are designed to be composable and are implemented as Runnables, allowing them to be seamlessly integrated into chains using the LangChain Expression Language (LCEL). A key feature of many output parsers is their ability to provide formatting instructions to the LLM, guiding it to generate output in a way that the parser can easily understand and process. This dual role of parsing and providing instructions makes them essential for building robust and reliable LLM-powered applications that require structured data.
Core Concepts and Base Classes
The output parser system is built upon a set of abstract base classes that define a consistent interface for all parser implementations.
Sources: libs/core/langchain_core/output_parsers/base.py
Class Hierarchy
The following diagram illustrates the inheritance structure of the core output parser classes.
This diagram shows that all output parsers are Runnable and Serializable, with specialized base classes for different types of model outputs.
Sources: libs/core/langchain_core/output_parsers/base.py, libs/core/langchain_core/output_parsers/string.py, libs/core/langchain_core/output_parsers/json.py, libs/core/langchain_core/output_parsers/pydantic.py, libs/langchain/langchain/output_parsers/retry.py
BaseOutputParser
This is the primary abstract class that all output parsers inherit from. It is a generic class parameterized by the type of the output T.
Sources: libs/core/langchain_core/output_parsers/base.py:20-111
| Method | Description |
|---|---|
parse(text: str) -> T | The core method that takes a string output from an LLM and parses it into the desired structure T. This method must be implemented by subclasses. |
get_format_instructions() -> str | Returns a string containing instructions for the LLM on how to format its output. This helps ensure the output is parsable. |
| `invoke(input: str | BaseMessage |
parse_result(result: list[Generation], *, partial: bool = False) -> T | Parses the output of a chat or LLM call, which is a list of Generation objects. It extracts the text from the first generation and passes it to the parse method. |
Other Base Classes
BaseLLMOutputParser: A subclass ofBaseOutputParserspecifically for parsing the output of an LLM call. It introduces theparse_resultmethod.BaseGenerationOutputParser: A subclass ofBaseLLMOutputParserthat further specializes in parsing a list ofGenerationobjects, which is the standard output format from language models in LangChain.
Sources: libs/core/langchain_core/output_parsers/base.py:114-143
Concrete Parser Implementations
LangChain provides several concrete implementations of output parsers for common use cases.
StrOutputParser
The simplest output parser. It takes the output from the language model and returns it as a raw string. It does not perform any structural changes.
Sources: libs/core/langchain_core/output_parsers/string.py:9-25
JsonOutputParser
This parser is designed to extract a JSON object from an LLM's text output. It can handle JSON formatted within a markdown code block (e.g., json ... ). It can optionally be initialized with a Pydantic model to validate the parsed JSON against a schema.
pydantic_object: An optional Pydantic model used for validation and to provide detailed format instructions to the LLM.parse(text: str) -> Any: Extracts and parses the JSON string.
Sources: libs/core/langchain_core/output_parsers/json.py:23-90
SimpleJsonOutputParser
A simpler version of the JSON parser that directly attempts to load the LLM output as a JSON object using json.loads. It does not handle markdown code blocks or offer Pydantic-based validation.
Sources: libs/core/langchain_core/output_parsers/json.py:93-111
PydanticOutputParser
A powerful parser that leverages Pydantic models to define the desired output structure. It automatically generates format instructions for the LLM based on the Pydantic model's JSON schema, and then parses the LLM's output into an instance of that model.
The workflow for this parser is as follows:
- A Pydantic model is provided to the parser.
- The parser generates a JSON schema from the model.
- It creates
get_format_instructionsbased on this schema, which are included in the prompt to the LLM. - The LLM generates a JSON string conforming to the schema.
- The parser validates and parses this string into a Pydantic object instance.
Sources: libs/core/langchain_core/output_parsers/pydantic.py:14-69
The diagram below shows the data flow for the PydanticOutputParser.
Advanced Features
Format Instructions
A crucial feature of output parsers is their ability to generate format instructions. These are text snippets injected into the prompt to guide the LLM in producing output in the correct format. Different parsers have different instruction templates.
| Instruction Constant | Purpose | Source File |
|---|---|---|
STRUCTURED_FORMAT_INSTRUCTIONS | For generic structured data, expects a markdown JSON block. | format_instructions.py |
PYDANTIC_FORMAT_INSTRUCTIONS | For Pydantic objects, provides the JSON schema to conform to. | format_instructions.py |
YAML_FORMAT_INSTRUCTIONS | For YAML output, provides a JSON schema and examples. | format_instructions.py |
Sources: libs/langchain/langchain/output_parsers/format_instructions.py:1-55
RetryOutputParser
Parsing can fail if the LLM does not perfectly adhere to the format instructions. The RetryOutputParser is a wrapper that adds a retry mechanism. If the initial parsing attempt fails, it can invoke an LLM chain (retry_chain) with the original prompt, the failed output, and the parsing error to generate a corrected output, which is then parsed again.
Key components:
parser: The primaryBaseOutputParserto attempt parsing with.retry_chain: AnLLMChainthat is run to fix the poorly formatted output.
Sources: libs/langchain/langchain/output_parsers/retry.py:20-63
The following sequence diagram illustrates the retry logic.
Conclusion
Output Parsers are indispensable tools in the LangChain framework for transforming raw, unstructured text from language models into structured, usable data formats. By providing a clear contract through base classes and a variety of implementations ranging from simple string conversion to complex Pydantic model instantiation, they enable developers to build more reliable and predictable applications. Advanced features like automatic retries and format instruction generation further enhance their utility, making them a cornerstone of structured data extraction with LLMs.