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 Enum values.
  • 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_exc

ValueError: 'yellow' is not a valid Colors

During handling of the above exception, another exception occurred:

OutputParserException                     Traceback (most recent call last)
Cell In[8], line 2
      1 # 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

  • EnumOutputParser validates LLM outputs against a fixed Enum class.
  • It trims whitespace (spaces, newlines) from inputs automatically.
  • Invalid values trigger OutputParserException with a clear error message.
  • Ideal for use cases requiring strict value validation (e.g., user choices, category selection).
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值