Repository navigation
fix(506): score an LLM reply as a match only when it is exactly "true" - #583
Conversation
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
# Conflicts: # CHANGELOG.md
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Report generated by Automated Security Helper (ASH) at 2026-11-17T20:47:18+00:00 |
sromoam
left a comment
There was a problem hiding this comment.
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 trueandfalse\n\nThese are not true matches.all score 0.0 and warn. Ondevall 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
-
get_comparison_detailsstill calls the model twice. It calls_invoke_agentatllm.py:342and thencompare()at:347, sollm_responseisn'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 ondevalso 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 assertcall_count == 1intest_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.
- The new comment at
-
The
_comparedocstring 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), andtest_compare_exception_handlingasserts that. The stale text was already ondev. 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. -
Docs wording.
- Step 4 (
llm-as-a-judge.md:152), the CHANGELOG entry and the docstring atllm.py:250all say "trailing punctuation" without saying which characters. The code strips only ASCII.,;:!?(llm.py:60), sotrue…,true),true。and fullwidthtrue!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:152and:238,Comparators.md:114). Those files use "normalize"/"normalization" nearby, as doesNormalizedComparator.
- Step 4 (
-
Optional:
?counts as trailing punctuation (llm.py:60), so a baretrue?scores 1.0 with no warning (measured against this branch). That follows #506's "strip whitespace and punctuation" rule and the docs.devalready scored it 1.0, so it isn't a regression, and longer hedges likemaybe 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 atrue?case to the unparseable-reply tests. Otherwise no change is needed. -
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. Ondevthese 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." -
CHANGELOG conflict. GitHub shows the branch as conflicting with
dev.git merge-treeshowsCHANGELOG.mdis the only conflicting file, so it just needs a merge fromdevbefore 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 = ".,;:!?" |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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.
# Conflicts: # CHANGELOG.md
|
Thanks! Applied in 4b8f50b, after merging |
Issue Reference
Fixes #506
Description of Changes
LLMComparatordecided a match withif "true" in response_lower, so any reply containing the substring scored 1.0, includinguntrue,Not trueandfalse (it is not true). That turned correct "no" answers from chattier models into matches.Changes Made
_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. Exactlytruescores 1.0 and exactlyfalsescores 0.0.UserWarningnaming the comparator and showing the first 80 characters of the reply. It doesn't raise, so bulk runs continue.get_comparison_detailsscores viacompare(), so it follows the same rule. No other code in the repo parses LLM verdicts.llm-as-a-judge.md, the comparators README,Comparators.md) state exactly what counts as a match.true,True.,**true**,"true",“true”falseuntrue,Not true,false (it is not true)True, they are equivalent.Why These Changes Are Needed
The prompt asks for exactly
trueorfalse, and the docs say the LLM "responds with"true"or"false"". Substring matching made scores silently wrong.Testing
devand pass here.ruff check .clean.Checklist
CHANGELOG.mdentry under[Unreleased]→ Fixed, leading with the score changeAdditional Notes
warn_oncewould be the alternative.