diff --git a/CHANGELOG.md b/CHANGELOG.md index dcf4ea81..a7133306 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,10 @@ Each release links to full notes on the ### Fixed +- **`LLMComparator` no longer raises `KeyError: 'text'` when the reply does not + start with a text block**, as with a reasoning model that sends + `reasoningContent` first. The verdict is read from the reply's text blocks; a + reply with none still raises, now as a `ValueError` that says so. - A `field_comparisons` row that meets its threshold only through the `1e-10` allowance now reads `within threshold tolerance ( vs )` for a top-level or nested-model field too, where it read `above threshold` (or diff --git a/docs/docs/Guides/Comparators/llm-as-a-judge.md b/docs/docs/Guides/Comparators/llm-as-a-judge.md index 9bd49375..7684e5f0 100644 --- a/docs/docs/Guides/Comparators/llm-as-a-judge.md +++ b/docs/docs/Guides/Comparators/llm-as-a-judge.md @@ -151,8 +151,8 @@ 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 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. +4. Only the reply's text blocks are read, so a reasoning model's reasoning is skipped. 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. A reply with no text block, including one that holds only reasoning, raises `ValueError` from `compare()` and from `compare_with()`. ### Setup @@ -188,7 +188,7 @@ 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). +Guidelines should only shape the judgment, not the reply format: the model must still answer with one word, and a reply whose text adds reasoning scores 0.0 with a warning (see step 5 above). ### Example diff --git a/src/stickler/comparators/llm.py b/src/stickler/comparators/llm.py index 13978491..ef0f0213 100644 --- a/src/stickler/comparators/llm.py +++ b/src/stickler/comparators/llm.py @@ -222,13 +222,18 @@ def _invoke_agent(self, prompt: str) -> str: prompt: The formatted prompt string to send to the LLM. Returns: - str: The text response from the LLM. + str: The reply's text blocks, joined. Other blocks, such as the + ``reasoningContent`` a reasoning model sends first, are skipped. Raises: Exception: If the agent call fails or response format is unexpected. """ result = self.agent(prompt) - return result.message["content"][0]["text"] + content = result.message["content"] + texts = [block["text"] for block in content if "text" in block] + if not texts: + raise ValueError("LLM reply has no text content block") + return "".join(texts) def _compare(self, value1: Any, value2: Any) -> float: """Compare two values using LLM-based semantic analysis. diff --git a/tests/common/comparators/test_llm.py b/tests/common/comparators/test_llm.py index d25125bf..47865a54 100644 --- a/tests/common/comparators/test_llm.py +++ b/tests/common/comparators/test_llm.py @@ -111,6 +111,19 @@ def test_client_initialization(self): ) assert new_comp.agent is self.mock_agent_class.return_value + def test_compare_skips_non_text_blocks(self): + """A reasoning model puts a ``reasoningContent`` block before the text.""" + mock_result = MagicMock() + mock_result.message = { + "content": [ + {"reasoningContent": {"reasoningText": {"text": "false?"}}}, + {"text": "true"}, + ] + } + self.mock_agent.return_value = mock_result + + assert self.comparator.compare("St.", "Street") == 1.0 + @pytest.mark.parametrize( "response", ["true", "TRUE", "True", " true ", " TRUE "] ) @@ -519,7 +532,7 @@ def test_malformed_response_empty_content_array(self): mock_result.message = {"content": []} self.mock_agent.return_value = mock_result - with pytest.raises(Exception): + with pytest.raises(ValueError, match="no text content block"): self.comparator.compare("value1", "value2") def test_malformed_response_missing_text_key(self): @@ -528,9 +541,28 @@ def test_malformed_response_missing_text_key(self): mock_result.message = {"content": [{"no_text": "value"}]} self.mock_agent.return_value = mock_result - with pytest.raises(Exception): + with pytest.raises(ValueError, match="no text content block"): self.comparator.compare("value1", "value2") + def test_compare_reasoning_only_raises(self): + """A reply that holds only a reasoning block has no text to read.""" + mock_result = MagicMock() + mock_result.message = { + "content": [ + {"reasoningContent": {"reasoningText": {"text": "maybe"}}}, + ] + } + self.mock_agent.return_value = mock_result + + with pytest.raises(ValueError, match="no text content block"): + self.comparator.compare("St.", "Street") + + details = self.comparator.get_comparison_details("St.", "Street") + assert details == { + "error": "LLM reply has no text content block", + "comparison_result": False, + } + def test_get_comparison_details_comprehensive_error_handling(self): """Test comprehensive error handling in get_comparison_details.""" # Test NoCredentialsError