"""Hallucination Detection metric. Measures whether the generated answer contains information not present in the contexts. Uses DeepEval's hallucination metric when available, and otherwise an approximate word-coverage score. """ from __future__ import annotations from typing import Any from loguru import logger from openagent_eval.metrics.base import BaseMetric, MetricResult from openagent_eval.metrics.generation._negation import contradicts_by_negation class HallucinationDetection(BaseMetric): """Detects hallucinated content in generated answers. A score of 0.0 means no hallucination detected (lower is better). A score of 1.0 means all content is hallucinated. With DeepEval, the score is the share of contexts the answer contradicts. Without it, the score is only approximate: the share of the answer's words missing from the contexts, or 1.0 if the answer and a context disagree on a negation. A correct paraphrase can therefore score high. """ name = "hallucination" description = "Detects information in the answer not present in contexts" def evaluate(self, **kwargs: Any) -> MetricResult: """Evaluate hallucination. Args: answer: The generated answer. contexts: List of context strings. Returns: MetricResult with hallucination score (0=no hallucination, 1=all hallucinated). """ answer = kwargs.get("answer", "") contexts = kwargs.get("contexts", []) if not answer: return MetricResult( score=0.0, reason="No answer to evaluate", metadata={"method": "word_coverage"}, ) if not contexts: return MetricResult( score=1.0, reason="No contexts provided - cannot verify", metadata={"method": "word_coverage"}, ) # Try DeepEval if available. Fall back to local heuristic for any # runtime error (missing API key, model init failure, etc.). try: return self._evaluate_with_deepeval(answer, contexts) except (ImportError, Exception) as e: logger.debug("DeepEval hallucination unavailable, using fallback: {}", e) self._warn_word_coverage() # Fallback: word coverage return self._evaluate_simple(answer, contexts) def _warn_word_coverage(self) -> None: """Warn once per metric instance that scores are only approximate.""" if getattr(self, "_warned_word_coverage", False): return self._warned_word_coverage = True logger.warning( "hallucination is using approximate word coverage, so correct paraphrases " "can score high. For claim checking: pip install " "'openagent-eval[evaluation]' and set OPENAI_API_KEY" ) def _evaluate_with_deepeval(self, answer: str, contexts: list[str]) -> MetricResult: """Evaluate using DeepEval hallucination metric.""" from deepeval.metrics import HallucinationMetric from deepeval.test_case import LLMTestCase # Build context string for the input field context_text = "\n".join(contexts) if contexts else "" test_case = LLMTestCase( input=context_text, actual_output=answer, context=contexts, ) metric = HallucinationMetric(threshold=0.5) metric.measure(test_case) score = metric.score # DeepEval's HallucinationMetric already reports 0.0 = no hallucination # and 1.0 = fully hallucinated (lower is better), matching this metric's # contract and the simple fallback below. Do NOT invert. hallucination_score = float(score) return MetricResult( score=hallucination_score, reason=f"DeepEval hallucination: {hallucination_score:.4f}", metadata={"method": "deepeval"}, ) def _evaluate_simple(self, answer: str, contexts: list[str]) -> MetricResult: """Simple word coverage fallback.""" answer_words = set(answer.lower().split()) context_text = " ".join(contexts).lower() context_words = set(context_text.split()) if not answer_words: return MetricResult( score=0.0, reason="Empty answer", metadata={"method": "word_coverage"}, ) if contradicts_by_negation(answer, contexts): return MetricResult( score=1.0, reason="Approximate: answer and context disagree on a negation", metadata={"method": "word_coverage"}, ) unsupported = answer_words - context_words score = len(unsupported) / len(answer_words) return MetricResult( score=min(score, 1.0), reason=( f"Approximate: {len(unsupported)}/{len(answer_words)} " "words not in context" ), metadata={ "method": "word_coverage", "unsupported_words": len(unsupported), "total_words": len(answer_words), }, )