Repository navigation
fix(506): score an LLM reply as a match only when it is exactly "true" #583
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
Changes from all commits
1d724f7
d1aac1e
43e492c
4b8f50b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,7 +25,8 @@ | |
| """ | ||
|
|
||
| import html | ||
| from typing import TYPE_CHECKING, Any, Dict, Union | ||
| import warnings | ||
| from typing import TYPE_CHECKING, Any, Dict, Optional, Union | ||
|
|
||
| from stickler.comparators.base import BaseComparator | ||
|
|
||
|
|
@@ -52,6 +53,42 @@ class NoCredentialsError(Exception): | |
| pass | ||
|
|
||
|
|
||
| #: Quote, backtick and markdown-emphasis characters stripped from both ends of | ||
| #: a reply, along with whitespace, before it is read as a verdict. | ||
| _VERDICT_WRAPPERS = "\"'`*_“”‘’" | ||
| #: Characters additionally stripped from the end, e.g. ``true.``. | ||
| _VERDICT_TRAILING_PUNCTUATION = ".,;:!?" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Optional: with |
||
| #: Longest reply shown in the unparseable-verdict warning. | ||
| _REPLY_PREVIEW_CHARS = 80 | ||
|
|
||
|
|
||
| def _parse_verdict(response: str) -> Optional[bool]: | ||
| """Read an LLM reply as a ``true``/``false`` verdict (#506). | ||
|
|
||
| Repeatedly strips surrounding whitespace (``str.strip()``, so non-breaking | ||
| spaces too), quotes, backticks and markdown emphasis from both ends, and | ||
| punctuation from the end, then lower-cases. Returns ``True`` only for | ||
| exactly ``true``, ``False`` for exactly ``false``, and ``None`` for anything | ||
| else: a substring test would score "untrue" or "not true" as a match. | ||
| """ | ||
| verdict = response | ||
| while True: | ||
| stripped = ( | ||
| verdict.strip() | ||
| .strip(_VERDICT_WRAPPERS) | ||
| .rstrip(_VERDICT_TRAILING_PUNCTUATION) | ||
| ) | ||
| if stripped == verdict: | ||
| break | ||
| verdict = stripped | ||
| verdict = verdict.lower() | ||
| if verdict == "true": | ||
| return True | ||
| if verdict == "false": | ||
| return False | ||
| return None | ||
|
|
||
|
|
||
| class LLMComparator(BaseComparator): | ||
| """Large Language Model-based semantic comparator. | ||
|
|
||
|
|
@@ -205,14 +242,18 @@ def _compare(self, value1: Any, value2: Any) -> float: | |
| value2: Second value to compare. Can be any type that converts to string. | ||
|
|
||
| Returns: | ||
| float: Binary similarity score: | ||
| - 1.0 if the LLM determines the values are equivalent | ||
| - 0.0 if the LLM determines the values are not equivalent | ||
| - 0.0 if an error occurs during comparison | ||
| float: 1.0 if the normalized reply is exactly ``true``, otherwise 0.0. | ||
| Normalizing strips surrounding whitespace, quotes, backticks and | ||
| markdown emphasis, strips trailing ``.,;:!?``, and ignores case. A | ||
| reply that is neither ``true`` nor ``false`` also emits a | ||
| ``UserWarning``. | ||
|
|
||
| Raises: | ||
| NoCredentialsError: If AWS credentials are not found. | ||
| Exception: Any other error from the LLM call is re-raised. | ||
|
|
||
| Note: | ||
| - Error handling: Returns 0.0 for any exceptions during LLM calls | ||
| - Cost consideration: Each call incurs API costs and latency | ||
| Cost consideration: Each call incurs API costs and latency. | ||
|
|
||
| Example: | ||
| >>> comparator = LLMComparator() | ||
|
|
@@ -231,12 +272,6 @@ def _compare(self, value1: Any, value2: Any) -> float: | |
| try: | ||
| # Get LLM response | ||
| response = self._invoke_agent(formatted_prompt) | ||
| # Parse response to boolean | ||
| response_lower = response.strip().lower() | ||
| if "true" in response_lower: | ||
| return 1.0 | ||
| else: | ||
| return 0.0 | ||
|
|
||
| except NoCredentialsError: | ||
| print("Error: AWS credentials not found.") | ||
|
|
@@ -246,6 +281,24 @@ def _compare(self, value1: Any, value2: Any) -> float: | |
| print(f"Error during LLM call: {e}") | ||
| raise | ||
|
|
||
| verdict = _parse_verdict(response) | ||
| if verdict is None: | ||
| preview = response | ||
| if len(preview) > _REPLY_PREVIEW_CHARS: | ||
| preview = preview[:_REPLY_PREVIEW_CHARS] + "..." | ||
| warnings.warn( | ||
| f"LLMComparator could not read the model's reply as 'true' or " | ||
| f"'false', so it scored 0.0. Reply: {preview!r}", | ||
| UserWarning, | ||
| # _compare (1) -> BaseComparator.compare (2) -> compare()'s | ||
| # caller (3). That is user code only for a direct compare(); | ||
| # via __call__, binary_compare, get_comparison_details or | ||
| # compare_with it lands inside stickler. | ||
| stacklevel=3, | ||
| ) | ||
| return 0.0 | ||
| return 1.0 if verdict else 0.0 | ||
|
|
||
| def get_comparison_details(self, value1: Any, value2: Any) -> Dict[str, Any]: | ||
| """Get detailed information about a comparison operation. | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -212,9 +212,76 @@ def test_ambiguous_response(self): | |
|
|
||
| for response in ambiguous_responses: | ||
| self._mock_agent_response(response) | ||
| result = self.comparator.compare("value1", "value2") | ||
| with pytest.warns(UserWarning, match="LLMComparator"): | ||
| result = self.comparator.compare("value1", "value2") | ||
| assert result == 0.0, f"Failed for response: {response}" | ||
|
|
||
| # #506: the verdict is the normalized reply, compared exactly. A substring | ||
| # test scored "untrue" and "Not true" as matches. | ||
| @pytest.mark.parametrize( | ||
| "response", | ||
| [ | ||
| "true", | ||
| "True", | ||
| " TRUE. ", | ||
| "`true`", | ||
| '"true"', | ||
| "'true'\n", | ||
| "**true**", | ||
| "**True**.", | ||
| "“true”", | ||
| "‘true’", | ||
| "\xa0true\xa0", | ||
| "_true_", | ||
| ], | ||
| ) | ||
| def test_exact_true_verdict_scores_match(self, response, recwarn): | ||
| self._mock_agent_response(response) | ||
| assert self.comparator.compare("a", "b") == 1.0 | ||
| assert not [w for w in recwarn if issubclass(w.category, UserWarning)] | ||
|
|
||
| @pytest.mark.parametrize("response", ["false", " False! ", "`FALSE`"]) | ||
| def test_exact_false_verdict_scores_no_match(self, response, recwarn): | ||
| self._mock_agent_response(response) | ||
| assert self.comparator.compare("a", "b") == 0.0 | ||
| assert not [w for w in recwarn if issubclass(w.category, UserWarning)] | ||
|
|
||
| @pytest.mark.parametrize( | ||
| "response", | ||
| [ | ||
| "untrue", | ||
| "Not true", | ||
| "false (it is not true)", | ||
| "true or false", | ||
| "", | ||
| "True, they are equivalent.", | ||
| "true\n\nThe values are equivalent.", | ||
| '```json\n{"equivalent": true}\n```', | ||
| ], | ||
| ) | ||
| def test_unparseable_verdict_scores_zero_and_warns(self, response): | ||
| self._mock_agent_response(response) | ||
| with pytest.warns(UserWarning, match="LLMComparator") as record: | ||
| assert self.comparator.compare("a", "b") == 0.0 | ||
| assert repr(response) in str(record[0].message) | ||
| # Attributed to the caller of compare(), not to llm.py or base.py. | ||
| assert record[0].filename == __file__ | ||
|
|
||
| def test_unparseable_verdict_warning_truncates_long_reply(self): | ||
| self._mock_agent_response("The values are equivalent. " * 20 + "true") | ||
| with pytest.warns(UserWarning, match="LLMComparator") as record: | ||
| assert self.comparator.compare("a", "b") == 0.0 | ||
| message = str(record[0].message) | ||
| assert "..." in message | ||
| assert len(message) < 300 | ||
|
|
||
| def test_get_comparison_details_uses_strict_verdict(self): | ||
| self._mock_agent_response("Not true") | ||
| with pytest.warns(UserWarning, match="LLMComparator"): | ||
| details = self.comparator.get_comparison_details("a", "b") | ||
| assert details["llm_response"] == "Not true" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The mock returns the same reply on every call, so this test passes even though |
||
| assert details["comparison_result"] == 0.0 | ||
|
|
||
| def test_none_values(self): | ||
| """Test that None values are handled properly.""" | ||
| # Both None should return 1.0 without calling agent | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optional: step 5 covers this, but the Custom Evaluation Guidelines section at
:175could cross-reference it. A guideline like "explain your reasoning", if the model follows it, turns positive verdicts into 0.0 with a warning. Something like: "Guidelines should only shape the judgment, not the reply format: the model must still answer with one word, and a reply that adds reasoning scores 0.0 with a warning."