|
| 1 | +"""Tests for hallucination detection guardrail.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from guardrails.checks.text.hallucination_detection import ( |
| 10 | + HallucinationDetectionConfig, |
| 11 | + HallucinationDetectionOutput, |
| 12 | + hallucination_detection, |
| 13 | +) |
| 14 | +from guardrails.checks.text.llm_base import LLMOutput |
| 15 | +from guardrails.types import TokenUsage |
| 16 | + |
| 17 | + |
| 18 | +def _mock_token_usage() -> TokenUsage: |
| 19 | + """Return a mock TokenUsage for tests.""" |
| 20 | + return TokenUsage(prompt_tokens=100, completion_tokens=50, total_tokens=150) |
| 21 | + |
| 22 | + |
| 23 | +class _FakeResponse: |
| 24 | + """Fake response from responses.parse.""" |
| 25 | + |
| 26 | + def __init__(self, parsed_output: Any, usage: TokenUsage) -> None: |
| 27 | + self.output_parsed = parsed_output |
| 28 | + self.usage = usage |
| 29 | + |
| 30 | + |
| 31 | +class _FakeGuardrailLLM: |
| 32 | + """Fake guardrail LLM client.""" |
| 33 | + |
| 34 | + def __init__(self, response: _FakeResponse) -> None: |
| 35 | + self._response = response |
| 36 | + self.responses = self |
| 37 | + |
| 38 | + async def parse(self, **kwargs: Any) -> _FakeResponse: |
| 39 | + """Mock parse method.""" |
| 40 | + return self._response |
| 41 | + |
| 42 | + |
| 43 | +class _FakeContext: |
| 44 | + """Context stub providing LLM client.""" |
| 45 | + |
| 46 | + def __init__(self, llm_response: _FakeResponse) -> None: |
| 47 | + self.guardrail_llm = _FakeGuardrailLLM(llm_response) |
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.asyncio |
| 51 | +async def test_hallucination_detection_includes_reasoning_when_enabled() -> None: |
| 52 | + """When include_reasoning=True, output should include reasoning and detail fields.""" |
| 53 | + parsed_output = HallucinationDetectionOutput( |
| 54 | + flagged=True, |
| 55 | + confidence=0.95, |
| 56 | + reasoning="The claim contradicts documented information", |
| 57 | + hallucination_type="factual_error", |
| 58 | + hallucinated_statements=["Premium plan costs $299/month"], |
| 59 | + verified_statements=["Customer support available"], |
| 60 | + ) |
| 61 | + response = _FakeResponse(parsed_output, _mock_token_usage()) |
| 62 | + context = _FakeContext(response) |
| 63 | + |
| 64 | + config = HallucinationDetectionConfig( |
| 65 | + model="gpt-test", |
| 66 | + confidence_threshold=0.7, |
| 67 | + knowledge_source="vs_test123", |
| 68 | + include_reasoning=True, |
| 69 | + ) |
| 70 | + |
| 71 | + result = await hallucination_detection(context, "Test claim", config) |
| 72 | + |
| 73 | + assert result.tripwire_triggered is True # noqa: S101 |
| 74 | + assert result.info["flagged"] is True # noqa: S101 |
| 75 | + assert result.info["confidence"] == 0.95 # noqa: S101 |
| 76 | + assert "reasoning" in result.info # noqa: S101 |
| 77 | + assert result.info["reasoning"] == "The claim contradicts documented information" # noqa: S101 |
| 78 | + assert "hallucination_type" in result.info # noqa: S101 |
| 79 | + assert result.info["hallucination_type"] == "factual_error" # noqa: S101 |
| 80 | + assert "hallucinated_statements" in result.info # noqa: S101 |
| 81 | + assert result.info["hallucinated_statements"] == ["Premium plan costs $299/month"] # noqa: S101 |
| 82 | + assert "verified_statements" in result.info # noqa: S101 |
| 83 | + assert result.info["verified_statements"] == ["Customer support available"] # noqa: S101 |
| 84 | + |
| 85 | + |
| 86 | +@pytest.mark.asyncio |
| 87 | +async def test_hallucination_detection_excludes_reasoning_when_disabled() -> None: |
| 88 | + """When include_reasoning=False (default), output should only include flagged and confidence.""" |
| 89 | + parsed_output = LLMOutput( |
| 90 | + flagged=False, |
| 91 | + confidence=0.2, |
| 92 | + ) |
| 93 | + response = _FakeResponse(parsed_output, _mock_token_usage()) |
| 94 | + context = _FakeContext(response) |
| 95 | + |
| 96 | + config = HallucinationDetectionConfig( |
| 97 | + model="gpt-test", |
| 98 | + confidence_threshold=0.7, |
| 99 | + knowledge_source="vs_test123", |
| 100 | + include_reasoning=False, |
| 101 | + ) |
| 102 | + |
| 103 | + result = await hallucination_detection(context, "Test claim", config) |
| 104 | + |
| 105 | + assert result.tripwire_triggered is False # noqa: S101 |
| 106 | + assert result.info["flagged"] is False # noqa: S101 |
| 107 | + assert result.info["confidence"] == 0.2 # noqa: S101 |
| 108 | + assert "reasoning" not in result.info # noqa: S101 |
| 109 | + assert "hallucination_type" not in result.info # noqa: S101 |
| 110 | + assert "hallucinated_statements" not in result.info # noqa: S101 |
| 111 | + assert "verified_statements" not in result.info # noqa: S101 |
| 112 | + |
| 113 | + |
| 114 | +@pytest.mark.asyncio |
| 115 | +async def test_hallucination_detection_requires_valid_vector_store() -> None: |
| 116 | + """Should raise ValueError if knowledge_source is invalid.""" |
| 117 | + context = _FakeContext(_FakeResponse(LLMOutput(flagged=False, confidence=0.0), _mock_token_usage())) |
| 118 | + |
| 119 | + # Missing vs_ prefix |
| 120 | + config = HallucinationDetectionConfig( |
| 121 | + model="gpt-test", |
| 122 | + confidence_threshold=0.7, |
| 123 | + knowledge_source="invalid_id", |
| 124 | + ) |
| 125 | + |
| 126 | + with pytest.raises(ValueError, match="knowledge_source must be a valid vector store ID starting with 'vs_'"): |
| 127 | + await hallucination_detection(context, "Test", config) |
| 128 | + |
| 129 | + # Empty string |
| 130 | + config_empty = HallucinationDetectionConfig( |
| 131 | + model="gpt-test", |
| 132 | + confidence_threshold=0.7, |
| 133 | + knowledge_source="", |
| 134 | + ) |
| 135 | + |
| 136 | + with pytest.raises(ValueError, match="knowledge_source must be a valid vector store ID starting with 'vs_'"): |
| 137 | + await hallucination_detection(context, "Test", config_empty) |
| 138 | + |
0 commit comments