当前位置: 首页 > news >正文

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_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

  • 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).
http://www.dtcms.com/a/609607.html

相关文章:

  • Problem: lab-week10-exercise02 Building a Fiber Network
  • 在 Linux 环境中配置 Eclipse 以开发 Hadoop 应用
  • 新手如何自己做网站app网站建设存在的困难问题
  • 视觉学习——卷积与神经网络:从原理到应用(量大管饱)
  • java 给鉴权kafka2.7(sasl)发送消息权限异常处理
  • 手机论坛网站源码和卫通app下载
  • 零基础学JAVA--Day32(ArrayList底层+Vector+LinkedList)
  • 了解Bootstrap ——初学者
  • 启动Nginx
  • 手机编程网站网站建设软件是什么意思
  • 设计兼职网站推荐自己做的网站网页错位
  • 第1章 机器学习的诞生与演化
  • 从零开始刷算法——二分-搜索旋转排序数组
  • Spring Boot + Vue 全栈开发实战指南
  • 深度智能体-人机回环
  • ASC学习笔记0013:添加一个新的属性集(初始化为默认值)
  • SpringIOC-注解
  • 关闭网站跳转代码wordpress 图片云存储
  • Java练习——数组练习
  • 导航仪企业网站源码那个网站做拍手比较好
  • 离别的十字路口: 是否还记得曾经追求的梦想
  • 3D地球可视化教程 - 第4篇:第5篇:星空背景与粒子系统
  • Unity Shader Graph 3D 实例 - 一个简单的红外线扫描全身效果
  • 【Mastergo】Mastergo总览
  • steam安装游戏为什么磁盘写入错误?磁盘写入错误怎么办?,同样问题解决方案
  • Unity官方文档 Asset Workflow:Importing Assets 阅读笔记
  • UD动作游戏开发读书笔记--. D游戏所需要的数学知识
  • 网站多语切换怎么做网站跳出率多少合适
  • MySQL数据类型全面解析:从数值精度到字符串优化的最佳实践
  • 太阳光模拟器应用:汽车太阳能天窗的发电效能动态测试