Source code for langchain.output_parsers.enum
from enum import Enum
from typing import Any, Dict, List, Type
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.pydantic_v1 import root_validator
[docs]class EnumOutputParser(BaseOutputParser):
"""解析一个属于一组值之一的输出。"""
enum: Type[Enum]
"""要解析的枚举。其值必须是字符串。"""
@root_validator()
def raise_deprecation(cls, values: Dict) -> Dict:
enum = values["enum"]
if not all(isinstance(e.value, str) for e in enum):
raise ValueError("Enum values must be strings")
return values
@property
def _valid_values(self) -> List[str]:
return [e.value for e in self.enum]
[docs] def parse(self, response: str) -> Any:
try:
return self.enum(response.strip())
except ValueError:
raise OutputParserException(
f"Response '{response}' is not one of the "
f"expected values: {self._valid_values}"
)