Skip to content

fix(506): score an LLM reply as a match only when it is exactly "true" - #583

Merged
harrycav merged 4 commits into
awslabs:devfrom
harrycav:fix/506-llm-strict-verdict
Nov 17, 2026
Merged

harrycav merged 4 commits into
awslabs:devfrom
harrycav:fix/506-llm-strict-verdict

Conversation

@harrycav

Copy link
Copy Markdown
Contributor

Issue Reference

Fixes #506

Description of Changes

LLMComparator decided a match with if "true" in response_lower, so any reply containing the substring scored 1.0, including untrue, Not true and false (it is not true). That turned correct "no" answers from chattier models into matches.

Changes Made

  • A new _parse_verdict() normalises the reply: plain .strip() (non-breaking spaces included), then surrounding quotes (", ', curly quotes), backticks, markdown emphasis (*, _) and trailing punctuation, repeated until stable, then lower-cased. Exactly true scores 1.0 and exactly false scores 0.0.
  • Anything else scores 0.0 and emits a UserWarning naming the comparator and showing the first 80 characters of the reply. It doesn't raise, so bulk runs continue.
  • get_comparison_details scores via compare(), so it follows the same rule. No other code in the repo parses LLM verdicts.
  • Docs (llm-as-a-judge.md, the comparators README, Comparators.md) state exactly what counts as a match.
Reply Before After
true, True., **true**, "true", “true” 1.0 1.0
false 0.0 0.0
untrue, Not true, false (it is not true) 1.0 0.0 + warning
True, they are equivalent. 1.0 0.0 + warning
empty reply 0.0 0.0 + warning

Why These Changes Are Needed

The prompt asks for exactly true or false, and the docs say the LLM "responds with "true" or "false"". Substring matching made scores silently wrong.

Testing

  • 65 LLM comparator tests (exact, wrapped, unparseable, truncated replies, and where the warning points). The new ones fail on dev and pass here.
  • Full suite green; ruff check . clean.

Checklist

  • Self-review plus an independent review
  • Documentation updated
  • CHANGELOG.md entry under [Unreleased] → Fixed, leading with the score change

Additional Notes

  • Score change, intended for 1.0.2: verbose replies that used to score 1.0 now score 0.0 with a warning. It fixes behaviour the docs already describe, like fix(comparators): align naive/aware dates in DateComparator range paths #546's DateComparator fix.
  • Warning noise: there's one warning per distinct reply, so an always-chatty model warns per document. That's deliberate, so the drop is visible. warn_once would be the alternative.
  • Follow-up: structured output (forcing a boolean verdict) for models that support it, keeping this parsing as the fallback, is tracked separately.

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 awslabs#506
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-11-17T20:47:17+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-11-17T20:44:00+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 0 0 0 6754 0 0 PASSED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 0 0 0 0 0 0 PASSED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Report generated by Automated Security Helper (ASH) at 2026-11-17T20:47:18+00:00

@sromoam sromoam left a comment

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.

Thanks Harry, this is a clean fix. _parse_verdict is small and easy to reason about, and the before/after table made the review quick. The tests really do pin the change: run against dev source, 11 of the 65 fail, and all 65 pass here.

Measured against this branch: tests/common/comparators/test_llm.py gives 65 passed, and CI is green on every job at d1aac1e0 (test 3.10 to 3.14, lint, build, security, strands-evals). I also ran hand-written replies through compare():

  • Formatted verdicts still match: True., 'true', **True**, ```\ntrue\n```, __**true**__ and "True". all score 1.0 with no warning.
  • The substring false positives are gone: untrue, Not true and false\n\nThese are not true matches. all score 0.0 and warn. On dev all three score 1.0.
  • As intended, correct but chatty replies now score 0.0 and warn: True, they are equivalent., The answer is true., Answer: true, <thinking>...</thinking>\ntrue, a reasoning paragraph ending in \n\ntrue, and {"equivalent": true}. That's consistent with the prompt and the docs, so I'm not asking for a change there.

Smaller

  1. get_comparison_details still calls the model twice. It calls _invoke_agent at llm.py:342 and then compare() at :347, so llm_response isn't the reply that got scored. I stubbed the agent to return "true" and then "True, they are equivalent." and got {'llm_response': 'true', 'comparison_result': 0.0} after 2 agent calls (measured against this branch). The same stub on dev also makes 2 calls but scores 1.0, so this predates the PR. Strict parsing just makes the mismatch visible.

    • The new comment at llm-as-a-judge.md:238 ("Raw LLM reply, before normalisation") reads as though the score came from that reply.
    • One fix is to score the reply you already have, using _parse_verdict(response) with the same None handling as _compare, and assert call_count == 1 in test_get_comparison_details_uses_strict_verdict (test_llm.py:278). That test can't catch the problem today because the mock returns the same reply on both calls.
    • This would also halve the Bedrock calls per get_comparison_details. Leaving it for a follow-up is fine with me too.
  2. The _compare docstring still says errors return 0.0. mkdocs re-admits _compare (docs/mkdocs.yml, filter ^_compare$), so this docstring is published on the API reference page. Two lines in the block you rewrote are stale: "0.0 if an error occurs during comparison" (llm.py:252) and the Note "Returns 0.0 for any exceptions during LLM calls" (:255). Both except branches re-raise (:276-282), and test_compare_exception_handling asserts that. The stale text was already on dev. Suggested replacement:

    Returns:
        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.
    
  3. Docs wording.

    • Step 4 (llm-as-a-judge.md:152), the CHANGELOG entry and the docstring at llm.py:250 all say "trailing punctuation" without saying which characters. The code strips only ASCII .,;:!? (llm.py:60), so true…, true), true。 and fullwidth true! score 0.0 and warn (measured against this branch). A reader of "trailing punctuation" would expect those to count. Either list . , ; : ! ? in all three places, or strip trailing Unicode punctuation in code. Listing the set is the smaller change.
    • The rest of the user docs spell it "normalize", and this PR adds the only "normalised"/"normalisation" (README.md:488, llm-as-a-judge.md:152 and :238, Comparators.md:114). Those files use "normalize"/"normalization" nearby, as does NormalizedComparator.
  4. Optional: ? counts as trailing punctuation (llm.py:60), so a bare true? scores 1.0 with no warning (measured against this branch). That follows #506's "strip whitespace and punctuation" rule and the docs. dev already scored it 1.0, so it isn't a regression, and longer hedges like maybe true? now warn and score 0.0. If you'd rather a trailing ? count as a non-verdict, drop it from the set and add a true? case to the unparseable-reply tests. Otherwise no change is needed.

  5. Optional: a note under Custom Evaluation Guidelines (llm-as-a-judge.md:175). Suppose a guideline asks for more than the one-word verdict, such as "explain your reasoning", and the model follows it. Its replies then score 0.0 with a warning, positive verdicts included (measured with stubbed replies against this branch). The prompt still ends with "Only return one word", so a model may well ignore the guideline. Step 5 already covers what happens. On dev these replies were silently mis-scored, often as 1.0. A cross-reference would help, e.g. "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."

  6. CHANGELOG conflict. GitHub shows the branch as conflicting with dev. git merge-tree shows CHANGELOG.md is the only conflicting file, so it just needs a merge from dev before landing.

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

Comment thread src/stickler/comparators/llm.py Outdated
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

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.

This bullet and the Note at :255 ("Returns 0.0 for any exceptions") contradict the code: both except branches re-raise, and test_compare_exception_handling asserts that. _compare is published on the API reference page, so it would be good to fix them while you're in this block. There's a suggested Returns/Raises in the review body.

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.

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.

Could this list the trailing characters (. , ; : ! ?)? The code strips only those, so true…, true) and true。 score 0.0 with a warning (measured against this branch), which "trailing punctuation" doesn't suggest. The CHANGELOG entry and the _compare docstring use the same wording. Also, the rest of the user docs spell it "normalize", so "normalized" here and in the other three spots would match.

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.

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."

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

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.

Heads up: get_comparison_details calls the model twice, so llm_response can differ from the reply that produced comparison_result. Measured against this branch with a stub returning "true" then "True, they are equivalent.": llm_response='true', comparison_result=0.0. This predates the PR, but this comment now implies the score came from this reply. Fine as a follow-up if you'd rather not widen the PR.

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.

@harrycav

Copy link
Copy Markdown
Contributor Author

Thanks! Applied in 4b8f50b, after merging dev (kept both CHANGELOG entries): the _compare docstring now says errors re-raise, using your text; "trailing punctuation" lists .,;:!? in the guide, the CHANGELOG and the docstring; "normalize" spelling throughout; the llm_response comment no longer implies it is the scored reply; and there is a note under Custom Evaluation Guidelines that reasoning in the reply scores 0.0 with a warning. Left true? as is. The double model call is now #589.

@harrycav
harrycav merged commit b59c7ce into awslabs:dev Nov 17, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LLMComparator scores any response containing "true" as a match, so "untrue" and "not true" score 1.0

2 participants