Enum Output Parser in LangChain
https://python.langchain.com.cn/docs/modules/model_io/output_parsers/enum
Enum Output Parser in LangChain
This content is based on LangChain’s official documentation (langchain.com.cn) and explains the EnumOutputParser—a tool to parse LLM outputs into Python Enum (fixed set of valid values)—in simplified terms. It strictly preserves original source codes, examples, and knowledge points without arbitrary additions or modifications.
1. What is EnumOutputParser?
EnumOutputParser ensures LLM outputs match one of the predefined values in a Python Enum class.
- Use case: When you need the LLM to choose from a fixed list of options (e.g., colors, categories) and want to validate the response.
- Key features:
- Automatically trims spaces and newlines from the LLM output.
- Raises a clear error if the output is not in the predefined
Enumvalues.
Enum(short for “enumeration”): A Python class that defines a set of named constants (fixed valid values).
2. Step 1: Import Required Modules
The code below imports all necessary classes—exactly as in the original documentation:
from langchain.output_parsers.enum import EnumOutputParser
from enum import Enum
Note: OutputParserException is implicitly imported (used for error handling) but not listed in the original imports—no need to add it manually.
3. Step 2: Define a Python Enum Class
Create an Enum class with fixed valid values. The original example uses a Colors enum:
class Colors(Enum):RED = "red"GREEN = "green"BLUE = "blue"
This means the only valid outputs are "red", "green", or "blue".
4. Step 3: Initialize the EnumOutputParser
Link the parser to the Colors enum (so it knows which values to accept):
parser = EnumOutputParser(enum=Colors)
5. Step 4: Test the Parser with Valid Inputs
The parser handles spaces and newlines automatically. Below are the original examples and their outputs:
Example 1: Parse Exact Valid Value
parser.parse("red")
Output (exact as original):
<Colors.RED: 'red'>
Example 2: Parse Value with Leading Space
parser.parse(" green") # Leading space is trimmed
Output (exact as original):
<Colors.GREEN: 'green'>
Example 3: Parse Value with Trailing Newline
parser.parse("blue\n") # Trailing newline is trimmed
Output (exact as original):
<Colors.BLUE: 'blue'>
6. Step 5: Test the Parser with Invalid Input
If the output is not in the Colors enum, the parser raises an OutputParserException. The original error example and traceback core content are preserved:
Code:
parser.parse("yellow") # "yellow" is not a valid Colors value
Error Output (Core Content as Original):
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
File ~/workplace/langchain/langchain/output_parsers/enum.py:25, in EnumOutputParser.parse(self, response)24 try:
---> 25 return self.enum(response.strip())26 except ValueError:File ~/.pyenv/versions/3.9.1/lib/python3.9/enum.py:315, in EnumMeta.__call__(cls, value, names, module, qualname, type, start)314 if names is None: # simple value lookup
--> 315 return cls.__new__(cls, value)File ~/.pyenv/versions/3.9.1/lib/python3.9/enum.py:611, in Enum.__new__(cls, value)610 if result is None and exc is None:
--> 611 raise ve_excValueError: 'yellow' is not a valid ColorsDuring handling of the above exception, another exception occurred:OutputParserException Traceback (most recent call last)
Cell In[8], line 21 # And raises errors when appropriate
----> 2 parser.parse("yellow")File ~/workplace/langchain/langchain/output_parsers/enum.py:27, in EnumOutputParser.parse(self, response)25 return self.enum(response.strip())26 except ValueError:
---> 27 raise OutputParserException(28 f"Response '{response}' is not one of the "29 f"expected values: {self._valid_values}"30 )OutputParserException: Response 'yellow' is not one of the expected values: ['red', 'green', 'blue']
Key Takeaways
EnumOutputParservalidates LLM outputs against a fixedEnumclass.- It trims whitespace (spaces, newlines) from inputs automatically.
- Invalid values trigger
OutputParserExceptionwith a clear error message. - Ideal for use cases requiring strict value validation (e.g., user choices, category selection).
