枚举解析器
本笔记本展示了如何使用枚举输出解析器
from langchain.output_parsers.enum import EnumOutputParser
API 参考:
- EnumOutputParser 来自
langchain.output_parsers.enum
from enum import Enum
class Colors(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
parser = EnumOutputParser(enum=Colors)
parser.parse("red")
输出结果:
<Colors.RED: 'red'>
# 可以处理空格
parser.parse(" green")
输出结果:
<Colors.GREEN: 'green'>
# 可以处理换行符
parser.parse("blue\n")
输出结果:
<Colors.BLUE: 'blue'>
# 在适当的情况下会引发错误
parser.parse("yellow")
输出结果:
---------------------------------------------------------------------------
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)
316 # otherwise, functional API: we're creating a new Enum type
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
612 elif exc is None:
ValueError: 'yellow' 不是一个有效的 Colors
During handling of the above exception, another exception occurred:
OutputParserException Traceback (most recent call last)
Cell In[8], line 2
1 # 在适当的情况下会引发错误
----> 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}' 不是预期值之一:{self._valid_values}"
29 )
OutputParserException: Response 'yellow' 不是预期值之一:['red', 'green', 'blue']