Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `.` `,` `;` `:` `!` `?` 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
([#478](https://github.com/awslabs/stickler/issues/478)).
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Guides/Comparators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.

Expand Down
10 changes: 7 additions & 3 deletions docs/docs/Guides/Comparators/llm-as-a-judge.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,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 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.

Copy link
Copy Markdown
Contributor

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 :175 could 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."


### Setup

Expand Down Expand Up @@ -185,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.
Expand Down Expand Up @@ -234,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 response ("true" or "false")
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)
```

Expand Down
2 changes: 1 addition & 1 deletion src/stickler/comparators/Comparators.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
Expand Down
79 changes: 66 additions & 13 deletions src/stickler/comparators/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 = ".,;:!?"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: with ? in this set, a bare true? scores 1.0 with no warning (measured against this branch). That matches #506's rule and dev already did it, so it isn't a regression, and maybe true? now correctly warns. If you'd rather treat a trailing ? as a hedge, dropping it here and adding a true? case to the unparseable tests would do it. Fine either way.

#: 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.

Expand Down Expand Up @@ -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()
Expand All @@ -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.")
Expand All @@ -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.

Expand Down
69 changes: 68 additions & 1 deletion tests/common/comparators/test_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 get_comparison_details makes two agent calls. If you fix that here, assert self.mock_agent.call_count == 1 would pin it.

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
Expand Down
Loading