Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

langchain: Make BooleanOutputParser more robust to non-binary responses #17810

Merged
merged 3 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 16 additions & 5 deletions libs/langchain/langchain/output_parsers/boolean.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,24 @@ def parse(self, text: str) -> bool:
boolean

"""
cleaned_text = text.strip()
if cleaned_text.upper() not in (self.true_val.upper(), self.false_val.upper()):
cleaned_upper_text = text.strip().upper()
if (
self.true_val.upper() in cleaned_upper_text
and self.false_val.upper() in cleaned_upper_text
):
raise ValueError(
f"BooleanOutputParser expected output value to either be "
f"{self.true_val} or {self.false_val}. Received {cleaned_text}."
f"Ambiguous response. Both {self.true_val} and {self.false_val} in "
f"received: {text}."
)
elif self.true_val.upper() in cleaned_upper_text:
return True
elif self.false_val.upper() in cleaned_upper_text:
return False
else:
raise ValueError(
f"BooleanOutputParser expected output value to include either "
f"{self.true_val} or {self.false_val}. Received {text}."
)
return cleaned_text.upper() == self.true_val.upper()

@property
def _type(self) -> str:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ def test_boolean_output_parser_parse() -> None:
result = parser.parse("no")
assert result is False

# Test valid input
result = parser.parse("Not relevant (NO)")
assert result is False

# Test ambiguous input
try:
parser.parse("yes and no")
assert False, "Should have raised ValueError"
except ValueError:
pass

# Test invalid input
try:
parser.parse("INVALID")
Expand Down