From 1d724f7a541a1bf79b917216dc1ba63a51aec631 Mon Sep 17 00:00:00 2001 From: Harry Cavanagh Date: Fri, 13 Nov 2026 11:24:32 -0300 Subject: [PATCH 1/2] fix(506): score an LLM reply as a match only when it is exactly "true" LLMComparator._compare tested `"true" in reply`, so "untrue", "Not true" and "false (it is not true)" all scored 1.0. The prompt asks for exactly one word, true or false. The reply is now normalised and compared exactly: surrounding whitespace (including non-breaking spaces), quotes (ASCII and curly), backticks and markdown emphasis are stripped from both ends and punctuation from the end, then case is ignored. "true" scores 1.0 and "false" scores 0.0, so "**True**." still matches. Any other reply, such as "True, they are equivalent.", scores 0.0 and emits a UserWarning naming LLMComparator and showing the first 80 characters of the reply. It does not raise, so one verbose reply does not stop a bulk run. get_comparison_details scores through compare(), so it follows the same rule. Scores change for models that reply with more than one word. Fixes #506 --- CHANGELOG.md | 10 +++ docs/docs/Guides/Comparators/README.md | 2 +- .../docs/Guides/Comparators/llm-as-a-judge.md | 7 +- src/stickler/comparators/Comparators.md | 2 +- src/stickler/comparators/llm.py | 71 ++++++++++++++++--- tests/common/comparators/test_llm.py | 69 +++++++++++++++++- 6 files changed, 146 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de40d642..a2f5bee6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,16 @@ Each release links to full notes on the ### Fixed +- **`LLMComparator` scores a reply as a match only when it is exactly `true`** + ([#506](https://github.com/awslabs/stickler/issues/506)). Scores change: + verbose replies such as `True, they are equivalent.` previously scored 1.0 + and now score 0.0 with a `UserWarning`, and replies that only contained + "true" as a substring (`untrue`, `Not true`) no longer match. Formatted + replies still match: surrounding whitespace, quotes, backticks, markdown + emphasis and trailing punctuation are stripped and case is ignored, so + `**True**.` scores 1.0 and `"false"` scores 0.0. Any other reply scores 0.0 + and warns, showing the start of the reply, rather than raising. + - `DateComparator` now treats a naive date against a tz-aware one the same way in range comparisons as for single dates: the aware side's own calendar date is used and the naive side is read on that calendar diff --git a/docs/docs/Guides/Comparators/README.md b/docs/docs/Guides/Comparators/README.md index 4b93debe..48d547dc 100644 --- a/docs/docs/Guides/Comparators/README.md +++ b/docs/docs/Guides/Comparators/README.md @@ -485,7 +485,7 @@ The default model is `distilbert-base-uncased`, loaded globally via the `evaluat ### LLMComparator -Uses a Large Language Model (via AWS Bedrock and the `strands-agents` library) to perform intelligent semantic comparisons. The LLM receives both values and optional evaluation guidelines, then returns a binary equivalence judgment. This is the most flexible comparator but also the most expensive. +Uses a Large Language Model (via AWS Bedrock and the `strands-agents` library) to perform intelligent semantic comparisons. The LLM receives both values and optional evaluation guidelines, then returns a binary equivalence judgment: 1.0 only when the normalised reply is exactly `true`, otherwise 0.0 (with a `UserWarning` when the reply is neither `true` nor `false`). See [LLM-as-a-Judge](llm-as-a-judge.md#llmcomparator) for the exact rule. This is the most flexible comparator but also the most expensive. **When to use:** Complex comparisons that require reasoning, domain-specific logic, or understanding of abbreviations and conventions. See [LLM-as-a-Judge Comparators](llm-as-a-judge.md) for a detailed guide. diff --git a/docs/docs/Guides/Comparators/llm-as-a-judge.md b/docs/docs/Guides/Comparators/llm-as-a-judge.md index 2af3552e..18c5d16a 100644 --- a/docs/docs/Guides/Comparators/llm-as-a-judge.md +++ b/docs/docs/Guides/Comparators/llm-as-a-judge.md @@ -145,8 +145,9 @@ The `LLMComparator` sends both values to a Large Language Model and asks it to d 1. A prompt is constructed with both values and optional evaluation guidelines using a Jinja2 template. 2. The prompt is sent to an LLM via the `strands-agents` library and AWS Bedrock. -3. The LLM responds with `"true"` or `"false"`. -4. The response is mapped to 1.0 (equivalent) or 0.0 (not equivalent). +3. The LLM is asked to reply with one word, `true` or `false`. +4. The reply is normalised: surrounding whitespace, quotes, backticks and markdown emphasis (`*`, `_`) and trailing punctuation are stripped, and case is ignored. Exactly `true` scores 1.0 and exactly `false` scores 0.0, so `**True**.` and `"false"` are read as verdicts. +5. Any other reply, such as `untrue`, `Not true` or `True, they are equivalent.`, scores 0.0 and emits a `UserWarning` showing the start of the reply. It does not raise, so one verbose reply does not stop a bulk run. ### Setup @@ -231,7 +232,7 @@ comparator = LLMComparator( details = comparator.get_comparison_details("St. John's Street", "Saint John's St") print(details["prompt"]) # The formatted prompt sent to the LLM -print(details["llm_response"]) # Raw LLM response ("true" or "false") +print(details["llm_response"]) # Raw LLM reply, before normalisation print(details["comparison_result"]) # Final score (1.0 or 0.0) ``` diff --git a/src/stickler/comparators/Comparators.md b/src/stickler/comparators/Comparators.md index 9d1389bc..f4705781 100644 --- a/src/stickler/comparators/Comparators.md +++ b/src/stickler/comparators/Comparators.md @@ -111,7 +111,7 @@ comparator = LLMComparator( - Uses LLM to determine semantic equivalence - Customizable prompt templates - Configurable temperature -- Binary output (1.0 or 0.0) +- Binary output: 1.0 only when the normalised reply is exactly `true`; any other reply scores 0.0 (with a `UserWarning` unless it is exactly `false`) - Note: Implementation in progress ### 4. Structured Data Comparators diff --git a/src/stickler/comparators/llm.py b/src/stickler/comparators/llm.py index 32713db7..045b3a36 100644 --- a/src/stickler/comparators/llm.py +++ b/src/stickler/comparators/llm.py @@ -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 = ".,;:!?" +#: 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. @@ -206,8 +243,12 @@ def _compare(self, value1: Any, value2: Any) -> float: 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 + - 1.0 if the LLM replies exactly ``true`` + - 0.0 if the LLM replies exactly ``false`` + - 0.0, with a ``UserWarning``, for any other reply. Before + comparing, surrounding whitespace, quotes, backticks and + markdown emphasis and trailing punctuation are stripped and + case is ignored. - 0.0 if an error occurs during comparison Note: @@ -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. diff --git a/tests/common/comparators/test_llm.py b/tests/common/comparators/test_llm.py index 4981316c..2c7c3797 100644 --- a/tests/common/comparators/test_llm.py +++ b/tests/common/comparators/test_llm.py @@ -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 normalised 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" + 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 From 4b8f50b4d40c8be8ef3507124df5e98be11c6e7c Mon Sep 17 00:00:00 2001 From: Harry Cavanagh Date: Tue, 17 Nov 2026 17:42:58 -0300 Subject: [PATCH 2/2] fix(506): apply review wording and docstring fixes --- CHANGELOG.md | 6 +++--- docs/docs/Guides/Comparators/README.md | 2 +- .../docs/Guides/Comparators/llm-as-a-judge.md | 7 +++++-- src/stickler/comparators/Comparators.md | 2 +- src/stickler/comparators/llm.py | 20 +++++++++---------- tests/common/comparators/test_llm.py | 2 +- 6 files changed, 21 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c7e55b3..12c33bb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,9 +27,9 @@ Each release links to full notes on the and now score 0.0 with a `UserWarning`, and replies that only contained "true" as a substring (`untrue`, `Not true`) no longer match. Formatted replies still match: surrounding whitespace, quotes, backticks, markdown - emphasis and trailing punctuation are stripped and case is ignored, so - `**True**.` scores 1.0 and `"false"` scores 0.0. Any other reply scores 0.0 - and warns, showing the start of the reply, rather than raising. + emphasis and trailing `.` `,` `;` `:` `!` `?` are stripped and case is + ignored, so `**True**.` scores 1.0 and `"false"` scores 0.0. Any other reply + scores 0.0 and warns, showing the start of the reply, rather than raising. - Corrected introductory example scores, the default text comparator description, and the sample amount in the documentation and README diff --git a/docs/docs/Guides/Comparators/README.md b/docs/docs/Guides/Comparators/README.md index 48d547dc..bab238c6 100644 --- a/docs/docs/Guides/Comparators/README.md +++ b/docs/docs/Guides/Comparators/README.md @@ -485,7 +485,7 @@ The default model is `distilbert-base-uncased`, loaded globally via the `evaluat ### LLMComparator -Uses a Large Language Model (via AWS Bedrock and the `strands-agents` library) to perform intelligent semantic comparisons. The LLM receives both values and optional evaluation guidelines, then returns a binary equivalence judgment: 1.0 only when the normalised reply is exactly `true`, otherwise 0.0 (with a `UserWarning` when the reply is neither `true` nor `false`). See [LLM-as-a-Judge](llm-as-a-judge.md#llmcomparator) for the exact rule. This is the most flexible comparator but also the most expensive. +Uses a Large Language Model (via AWS Bedrock and the `strands-agents` library) to perform intelligent semantic comparisons. The LLM receives both values and optional evaluation guidelines, then returns a binary equivalence judgment: 1.0 only when the normalized reply is exactly `true`, otherwise 0.0 (with a `UserWarning` when the reply is neither `true` nor `false`). See [LLM-as-a-Judge](llm-as-a-judge.md#llmcomparator) for the exact rule. This is the most flexible comparator but also the most expensive. **When to use:** Complex comparisons that require reasoning, domain-specific logic, or understanding of abbreviations and conventions. See [LLM-as-a-Judge Comparators](llm-as-a-judge.md) for a detailed guide. diff --git a/docs/docs/Guides/Comparators/llm-as-a-judge.md b/docs/docs/Guides/Comparators/llm-as-a-judge.md index 1fda4af4..d3441054 100644 --- a/docs/docs/Guides/Comparators/llm-as-a-judge.md +++ b/docs/docs/Guides/Comparators/llm-as-a-judge.md @@ -149,7 +149,7 @@ The `LLMComparator` sends both values to a Large Language Model and asks it to d 1. A prompt is constructed with both values and optional evaluation guidelines using a Jinja2 template. 2. The prompt is sent to an LLM via the `strands-agents` library and AWS Bedrock. 3. The LLM is asked to reply with one word, `true` or `false`. -4. The reply is normalised: surrounding whitespace, quotes, backticks and markdown emphasis (`*`, `_`) and trailing punctuation are stripped, and case is ignored. Exactly `true` scores 1.0 and exactly `false` scores 0.0, so `**True**.` and `"false"` are read as verdicts. +4. The reply is normalized: surrounding whitespace, quotes, backticks and markdown emphasis (`*`, `_`) and any trailing `.` `,` `;` `:` `!` `?` are stripped, and case is ignored. Exactly `true` scores 1.0 and exactly `false` scores 0.0, so `**True**.` and `"false"` are read as verdicts. 5. Any other reply, such as `untrue`, `Not true` or `True, they are equivalent.`, scores 0.0 and emits a `UserWarning` showing the start of the reply. It does not raise, so one verbose reply does not stop a bulk run. ### Setup @@ -186,6 +186,8 @@ comparator = LLMComparator( ) ``` +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 (see step 5 above). + ### Example This example is based on the [`examples/scripts/llm_comparator_demo.py`](https://github.com/awslabs/stickler/blob/main/examples/scripts/llm_comparator_demo.py) script. @@ -235,7 +237,8 @@ comparator = LLMComparator( details = comparator.get_comparison_details("St. John's Street", "Saint John's St") print(details["prompt"]) # The formatted prompt sent to the LLM -print(details["llm_response"]) # Raw LLM reply, before normalisation +print(details["llm_response"]) # Raw reply from one LLM call, not normalized + # (the score below comes from a separate call) print(details["comparison_result"]) # Final score (1.0 or 0.0) ``` diff --git a/src/stickler/comparators/Comparators.md b/src/stickler/comparators/Comparators.md index f4705781..12a7cbd7 100644 --- a/src/stickler/comparators/Comparators.md +++ b/src/stickler/comparators/Comparators.md @@ -111,7 +111,7 @@ comparator = LLMComparator( - Uses LLM to determine semantic equivalence - Customizable prompt templates - Configurable temperature -- Binary output: 1.0 only when the normalised reply is exactly `true`; any other reply scores 0.0 (with a `UserWarning` unless it is exactly `false`) +- Binary output: 1.0 only when the normalized reply is exactly `true`; any other reply scores 0.0 (with a `UserWarning` unless it is exactly `false`) - Note: Implementation in progress ### 4. Structured Data Comparators diff --git a/src/stickler/comparators/llm.py b/src/stickler/comparators/llm.py index 045b3a36..1afcc3e3 100644 --- a/src/stickler/comparators/llm.py +++ b/src/stickler/comparators/llm.py @@ -242,18 +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 replies exactly ``true`` - - 0.0 if the LLM replies exactly ``false`` - - 0.0, with a ``UserWarning``, for any other reply. Before - comparing, surrounding whitespace, quotes, backticks and - markdown emphasis and trailing punctuation are stripped and - case is ignored. - - 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() diff --git a/tests/common/comparators/test_llm.py b/tests/common/comparators/test_llm.py index 2c7c3797..99389493 100644 --- a/tests/common/comparators/test_llm.py +++ b/tests/common/comparators/test_llm.py @@ -216,7 +216,7 @@ def test_ambiguous_response(self): result = self.comparator.compare("value1", "value2") assert result == 0.0, f"Failed for response: {response}" - # #506: the verdict is the normalised reply, compared exactly. A substring + # #506: the verdict is the normalized reply, compared exactly. A substring # test scored "untrue" and "Not true" as matches. @pytest.mark.parametrize( "response",