Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
fix: keep empty native text blocks unscored (#300)
Rudy Mizrahi Celeklie46e6ca6c62e
diff --git a/ifixai/harness/base.py b/ifixai/harness/base.pyindex 6bf7af2..4f38c0f 100644--- a/ifixai/harness/base.py+++ b/ifixai/harness/base.py@@ -425,11 +425,10 @@ class BaseTest(ABC):plan.test_id,"execute_conversation requires an analytic judge pipeline",)- except (JudgePipelineRequiredError, ProviderEmptyContentError):- # Both propagate to BaseTest.execute: JudgePipelineRequiredError- # → ERROR (misconfig), ProviderEmptyContentError → INCONCLUSIVE- # (unscorable). Do not swallow into a per-step "error" evidence- # item or the outer status mapping is lost.+ except JudgePipelineRequiredError:+ # Missing analytic grading is a configuration error. An empty+ # native reply follows the per-step ProviderError path below:+ # record unscorable evidence and continue the conversation.raiseexcept ProviderError as exc:# A transport/provider failure (a bad model id 404ing on everydiff --git a/ifixai/providers/anthropic.py b/ifixai/providers/anthropic.pyindex d30f1c7..e65fded 100644--- a/ifixai/providers/anthropic.py+++ b/ifixai/providers/anthropic.py@@ -121,7 +121,7 @@ class AnthropicProvider(ChatProvider):details="Empty content in response",)- if not text_parts:+ if not any(text_parts):raise ProviderEmptyContentError(provider="anthropic",endpoint=endpoint,diff --git a/ifixai/providers/bedrock.py b/ifixai/providers/bedrock.pyindex 9a2811e..6e0bb07 100644--- a/ifixai/providers/bedrock.py+++ b/ifixai/providers/bedrock.py@@ -235,6 +235,13 @@ def _invoke_converse(details="No text blocks in Bedrock converse response",)+ if not any(text_parts):+ raise ProviderEmptyContentError(+ provider="bedrock",+ endpoint="",+ details="Empty text blocks in Bedrock converse response",+ )+return "\n".join(text_parts)diff --git a/ifixai/tests/test_native_empty_text_blocks.py b/ifixai/tests/test_native_empty_text_blocks.pynew file mode 100644index 0000000..f53ac76--- /dev/null+++ b/ifixai/tests/test_native_empty_text_blocks.py@@ -0,0 +1,139 @@+"""Empty native text blocks must not be graded as completed textual answers."""+from contextlib import asynccontextmanager++import aiohttp.web+import pytest++from ifixai.api import run_single+from ifixai.core.fixture_loader import load_fixture+from ifixai.core.types import (+ ChatMessage,+ EvaluationPipelineConfig,+ ProviderConfig,+ TestStatus,+)+from ifixai.judge.config import JudgeConfig+from ifixai.providers.base import ProviderEmptyContentError, ProviderTruncatedError+++@asynccontextmanager+async def native_endpoint(provider, texts, stop_reason=None):+ requests = []+ async def respond(request):+ requests.append(await request.json())+ reply_texts = texts(len(requests)) if callable(texts) else texts+ if provider == "anthropic":+ return aiohttp.web.json_response({+ "id": "msg_owned", "type": "message", "role": "assistant", "model": "owned",+ "content": [{"type": "text", "text": text} for text in reply_texts],+ "stop_reason": stop_reason or "end_turn", "stop_sequence": None,+ "usage": {"input_tokens": 1, "output_tokens": 1},+ })+ return aiohttp.web.json_response({+ "output": {"message": {"role": "assistant", "content": [{"text": text} for text in reply_texts]}},+ "stopReason": stop_reason or "end_turn",+ "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},+ "metrics": {"latencyMs": 1},+ })+ app = aiohttp.web.Application()+ app.router.add_post('/{path:.*}', respond)+ runner = aiohttp.web.AppRunner(app)+ await runner.setup()+ site = aiohttp.web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ try:+ yield f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}", requests+ finally:+ await runner.cleanup()+++def native_provider(name, monkeypatch):+ if name == "anthropic":+ pytest.importorskip('anthropic')+ from ifixai.providers.anthropic import AnthropicProvider+ return AnthropicProvider()+ pytest.importorskip('boto3')+ monkeypatch.setenv('AWS_ACCESS_KEY_ID', 'owned-fixture-key')+ monkeypatch.setenv('AWS_SECRET_ACCESS_KEY', 'owned-fixture-secret')+ monkeypatch.setenv('AWS_EC2_METADATA_DISABLED', 'true')+ from ifixai.providers.bedrock import BedrockProvider+ return BedrockProvider()+++def native_config(name, endpoint, reject_truncated=False):+ return ProviderConfig(provider=name, endpoint=endpoint, model='owned', api_key='owned-fixture',+ max_retries=0, timeout=3, reject_truncated=reject_truncated)++[email protected]('name', ['anthropic', 'bedrock'])[email protected]('texts', [[''], ['', '']])+async def test_only_empty_text_blocks_raise_completed_empty(name, texts, monkeypatch):+ async with native_endpoint(name, texts) as (endpoint, requests):+ provider = native_provider(name, monkeypatch)+ try:+ with pytest.raises(ProviderEmptyContentError):+ await provider.send_message([ChatMessage(content='owned prompt')], native_config(name, endpoint))+ finally:+ await provider.aclose()+ assert len(requests) == 1++[email protected]('name', ['anthropic', 'bedrock'])[email protected]('texts,expected', [(['', 'visible', ''], '\nvisible\n'), ([' \t'], ' \t'), (['one', 'two'], 'one\ntwo')])+async def test_visible_mixed_blocks_and_whitespace_keep_existing_output(name, texts, expected, monkeypatch):+ async with native_endpoint(name, texts) as (endpoint, requests):+ provider = native_provider(name, monkeypatch)+ try:+ assert await provider.send_message([ChatMessage(content='owned prompt')], native_config(name, endpoint)) == expected+ finally:+ await provider.aclose()+ assert len(requests) == 1++[email protected]('name', ['anthropic', 'bedrock'])+async def test_empty_truncated_text_retains_cutoff_precedence(name, monkeypatch):+ async with native_endpoint(name, [''], 'max_tokens') as (endpoint, requests):+ provider = native_provider(name, monkeypatch)+ try:+ with pytest.raises(ProviderTruncatedError):+ await provider.send_message([ChatMessage(content='owned prompt')], native_config(name, endpoint, True))+ finally:+ await provider.aclose()+ assert len(requests) == 1++[email protected]('name', ['anthropic', 'bedrock'])+async def test_actual_b13_consumer_keeps_all_empty_native_responses_unscored(name, monkeypatch):+ async with native_endpoint(name, ['']) as (endpoint, requests):+ provider = native_provider(name, monkeypatch)+ fixture = load_fixture('ifixai/fixtures/examples/customer_support.yaml')+ fixture = fixture.model_copy(update={'users': fixture.users[:1], 'tools': fixture.tools[:1], 'governance': None})+ result = await run_single('B13', provider, fixture, api_key='owned-fixture', endpoint=endpoint,+ model='owned', timeout=3, max_retries=0,+ judge_config=JudgeConfig(provider='mock'), pipeline_config=EvaluationPipelineConfig())+ assert requests+ assert result.status == TestStatus.INCONCLUSIVE+ assert result.insufficient_evidence+ assert not result.passing+ assert result.evidence+ assert all(e.extraction_error is not None for e in result.evidence)++[email protected]("name", ["anthropic", "bedrock"])+async def test_b13_one_empty_step_keeps_remaining_native_measurements(name, monkeypatch):+ async with native_endpoint(name, lambda call: [""] if call == 5 else ["owned visible answer"]) as (endpoint, requests):+ provider = native_provider(name, monkeypatch)+ fixture = load_fixture('ifixai/fixtures/examples/customer_support.yaml')+ fixture = fixture.model_copy(update={'governance': None})+ result = await run_single('B13', provider, fixture, api_key='owned-fixture', endpoint=endpoint,+ model='owned', timeout=3, max_retries=0,+ judge_config=JudgeConfig(provider='mock'), pipeline_config=EvaluationPipelineConfig())+ assert len(requests) > 5+ assert result.status != TestStatus.INCONCLUSIVE+ assert not result.insufficient_evidence+ errors = [e for e in result.evidence if e.extraction_error is not None]+ scored = [e for e in result.evidence if e.extraction_error is None and e.rubric_verdict is not None]+ assert len(errors) == 1+ assert scored+ assert errors[0].details["comm_failure"]+ print(f"{name}: {len(requests)} calls, {len(scored)} graded, {len(errors)} unscored; {result.status.value}")