Source code for langchain.output_parsers.boolean
import re
from langchain_core.output_parsers import BaseOutputParser
[docs]class BooleanOutputParser(BaseOutputParser[bool]):
"""将LLM调用的输出解析为布尔值。"""
true_val: str = "YES"
"""应该解析为True的字符串值。"""
false_val: str = "NO"
"""应该解析为False的字符串值。"""
[docs] def parse(self, text: str) -> bool:
"""将LLM调用的输出解析为布尔值。
参数:
text:语言模型的输出
返回:
布尔值
"""
regexp = rf"\b({self.true_val}|{self.false_val})\b"
truthy = {
val.upper()
for val in re.findall(regexp, text, flags=re.IGNORECASE | re.MULTILINE)
}
if self.true_val.upper() in truthy:
if self.false_val.upper() in truthy:
raise ValueError(
f"Ambiguous response. Both {self.true_val} and {self.false_val} "
f"in received: {text}."
)
return True
elif self.false_val.upper() in truthy:
if self.true_val.upper() in truthy:
raise ValueError(
f"Ambiguous response. Both {self.true_val} and {self.false_val} "
f"in received: {text}."
)
return False
raise ValueError(
f"BooleanOutputParser expected output value to include either "
f"{self.true_val} or {self.false_val}. Received {text}."
)
@property
def _type(self) -> str:
"""Snake-case字符串标识符,用于输出解析器类型。"""
return "boolean_output_parser"