From 17350b383ed8b7ee98cf81457802a061781d5574 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20=C3=81d=C3=A1m?= Date: Fri, 6 Nov 2026 22:44:31 +0100 Subject: [PATCH 1/3] docs: cite the GroundLM 2026 paper (#125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: cite the v2 paper (GroundLM 2026 at EMNLP 2026) The v2 paper is published in the GroundLM 2026 workshop proceedings at EMNLP 2026 (https://aclanthology.org/2026.groundlm-1.44/). Add its ACL BibTeX to the README and the v2 model card mirrors, which still said the paper was in preparation, and link it from the v2 section and the dataset doc. The arXiv link (2607.00895) stays. Signed-off-by: Kovács Ádám * docs: add the DOI to the GroundLM 2026 citation and name the paper by its content --------- Signed-off-by: Kovács Ádám --- README.md | 33 +++++++++++++++++++ docs/code-hallucination/index.md | 2 ++ .../model_card_v2_mmbert_base.md | 32 ++++++++++++++++-- docs/code-hallucination/model_card_v2_qwen.md | 32 ++++++++++++++++-- .../model_card_v2_taxonomy_head.md | 29 ++++++++++++++++ 5 files changed, 122 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f1fd8b3..e93b546 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ LettuceDetect now detects hallucinations in **coding-agent** answers — grounde - **Models:** `lettucedect-v2-qwen-2b` (generative, emits typed spans in one pass) and `lettucedect-v2-mmbert-base` (fast encoder) — a single model across code, tool output, and prose (including 14-language [PsiloQA](https://huggingface.co/datasets/s-nlp/PsiloQA) and [RAGTruth](https://aclanthology.org/2024.acl-long.585/)). - **Benchmark:** a span-annotated code + tool-output + structured-document hallucination dataset — [KRLabsOrg/lettucedetect-code-hallucination](https://huggingface.co/datasets/KRLabsOrg/lettucedetect-code-hallucination). +- **Paper:** [Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents](https://aclanthology.org/2026.groundlm-1.44/) (GroundLM 2026 workshop at EMNLP 2026) · [arXiv:2607.00895](https://arxiv.org/abs/2607.00895) - On code-agent answers, the fine-tuned 2B detector substantially outperforms the off-the-shelf detectors and large LLM judges we evaluated, which over-flag generated code:

Code-agent hallucination detection comparison

@@ -181,6 +182,7 @@ For detailed performance metrics and evaluations of our models: - [English model documentation](docs/README.md) - [Multilingual model documentation](docs/EUROBERT.md) - [Paper](https://arxiv.org/abs/2502.17125) +- [Paper: span-level detection over code, tool output and documents](https://aclanthology.org/2026.groundlm-1.44/) (GroundLM 2026 workshop at EMNLP 2026) - [Model cards](https://huggingface.co/KRLabsOrg) ## How does it work? @@ -384,3 +386,34 @@ Please cite the following paper if you use LettuceDetect in your work: url={https://arxiv.org/abs/2502.17125}, } ``` + +For the models that cover code, tool output and documents, and the unified benchmark, please cite: + +```bibtex +@inproceedings{kovacs-etal-2026-beyond, + title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents", + author = "Kov{\'a}cs, {\'A}d{\'a}m and + He, Bowei and + Liu, Xue and + Boros, Istv{\'a}n and + T{\'o}th, Szilveszter and + Recski, Gabor", + editor = "Wang, Yimu and + Choi, Yee Man and + Wu, Di and + Ouyang, Siqi and + Azadani, Mozhgan Nasr and + Fung, Yi R. (May)", + booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)", + month = oct, + year = "2026", + address = "Budapest, Hungary", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2026.groundlm-1.44/", + doi = "10.18653/2026.groundlm-1.44", + pages = "566--577", + ISBN = "979-8-89176-478-1" +} +``` + +Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). diff --git a/docs/code-hallucination/index.md b/docs/code-hallucination/index.md index badf10a..6580320 100644 --- a/docs/code-hallucination/index.md +++ b/docs/code-hallucination/index.md @@ -8,6 +8,8 @@ character-level annotations marking the hallucinated spans. Published as the `lettucedetect-code-agent` source of [`KRLabsOrg/lettucedetect-code-hallucination`](https://huggingface.co/datasets/KRLabsOrg/lettucedetect-code-hallucination). +**Paper:** [Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents](https://aclanthology.org/2026.groundlm-1.44/) (GroundLM 2026 workshop at EMNLP 2026) · [arXiv:2607.00895](https://arxiv.org/abs/2607.00895) + ## Why this dataset Existing hallucination-detection datasets (RAGTruth, RAGBench) focus on **text** — diff --git a/docs/code-hallucination/model_card_v2_mmbert_base.md b/docs/code-hallucination/model_card_v2_mmbert_base.md index a9f24c6..a79482f 100644 --- a/docs/code-hallucination/model_card_v2_mmbert_base.md +++ b/docs/code-hallucination/model_card_v2_mmbert_base.md @@ -159,6 +159,35 @@ spans, then type each span with the label-conditioned taxonomy head (see ## Citing +```bibtex +@inproceedings{kovacs-etal-2026-beyond, + title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents", + author = "Kov{\'a}cs, {\'A}d{\'a}m and + He, Bowei and + Liu, Xue and + Boros, Istv{\'a}n and + T{\'o}th, Szilveszter and + Recski, Gabor", + editor = "Wang, Yimu and + Choi, Yee Man and + Wu, Di and + Ouyang, Siqi and + Azadani, Mozhgan Nasr and + Fung, Yi R. (May)", + booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)", + month = oct, + year = "2026", + address = "Budapest, Hungary", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2026.groundlm-1.44/", + doi = "10.18653/2026.groundlm-1.44", + pages = "566--577", + ISBN = "979-8-89176-478-1" +} +``` + +Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). LettuceDetect itself: + ```bibtex @article{Kovacs2025LettuceDetect, title={LettuceDetect: A Hallucination Detection Framework for RAG Applications}, @@ -167,6 +196,3 @@ spans, then type each span with the label-conditioned taxonomy head (see year={2025} } ``` - -*A dedicated paper for the unified code+prose benchmark and the v2 models is in -preparation; this card will be updated with its citation on release.* diff --git a/docs/code-hallucination/model_card_v2_qwen.md b/docs/code-hallucination/model_card_v2_qwen.md index 46a2fa5..45084df 100644 --- a/docs/code-hallucination/model_card_v2_qwen.md +++ b/docs/code-hallucination/model_card_v2_qwen.md @@ -272,6 +272,35 @@ near chance) because a generated code patch is not literally present in the cont ## Citing +```bibtex +@inproceedings{kovacs-etal-2026-beyond, + title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents", + author = "Kov{\'a}cs, {\'A}d{\'a}m and + He, Bowei and + Liu, Xue and + Boros, Istv{\'a}n and + T{\'o}th, Szilveszter and + Recski, Gabor", + editor = "Wang, Yimu and + Choi, Yee Man and + Wu, Di and + Ouyang, Siqi and + Azadani, Mozhgan Nasr and + Fung, Yi R. (May)", + booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)", + month = oct, + year = "2026", + address = "Budapest, Hungary", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2026.groundlm-1.44/", + doi = "10.18653/2026.groundlm-1.44", + pages = "566--577", + ISBN = "979-8-89176-478-1" +} +``` + +Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). LettuceDetect itself: + ```bibtex @article{Kovacs2025LettuceDetect, title={LettuceDetect: A Hallucination Detection Framework for RAG Applications}, @@ -280,6 +309,3 @@ near chance) because a generated code patch is not literally present in the cont year={2025} } ``` - -*A dedicated paper for the unified code+prose benchmark and the v2 models is in -preparation; this card will be updated with its citation on release.* diff --git a/docs/code-hallucination/model_card_v2_taxonomy_head.md b/docs/code-hallucination/model_card_v2_taxonomy_head.md index 7fd1323..3133307 100644 --- a/docs/code-hallucination/model_card_v2_taxonomy_head.md +++ b/docs/code-hallucination/model_card_v2_taxonomy_head.md @@ -74,6 +74,35 @@ Wikipedia, plus RAGTruth and 14-language PsiloQA. ## Citing +```bibtex +@inproceedings{kovacs-etal-2026-beyond, + title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents", + author = "Kov{\'a}cs, {\'A}d{\'a}m and + He, Bowei and + Liu, Xue and + Boros, Istv{\'a}n and + T{\'o}th, Szilveszter and + Recski, Gabor", + editor = "Wang, Yimu and + Choi, Yee Man and + Wu, Di and + Ouyang, Siqi and + Azadani, Mozhgan Nasr and + Fung, Yi R. (May)", + booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)", + month = oct, + year = "2026", + address = "Budapest, Hungary", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2026.groundlm-1.44/", + doi = "10.18653/2026.groundlm-1.44", + pages = "566--577", + ISBN = "979-8-89176-478-1" +} +``` + +Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). LettuceDetect itself: + ```bibtex @article{Kovacs2025LettuceDetect, title={LettuceDetect: A Hallucination Detection Framework for RAG Applications}, From eac44c7cb9321fae6e134a925a4e5e4e27575d2e Mon Sep 17 00:00:00 2001 From: Clannad <99583076+Clannad47@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:24:57 +0800 Subject: [PATCH 2/3] fix: keep unscored spans in the Claude Code hook --min-confidence filter (#124) The Stop hook filtered spans with (confidence or hallucination_score or 0.0) >= min_confidence, so a span without a score counted as 0.0 and was dropped once --min-confidence was above 0. In --llm-model mode neither the judge path nor the native v2 generative path produces a score, so every flagged span was dropped and the hook reported a clean answer. Keep unscored spans, the same rule as BaseDetector._filter_spans_by_confidence, and document in --help and the integration README that the threshold applies to scored spans only. Closes #117 Signed-off-by: Clannad47 Co-authored-by: Clannad47 --- CHANGELOG.md | 5 ++ .../integrations/claude_code/README.md | 2 +- .../integrations/claude_code/check_answer.py | 10 ++- tests/test_claude_code_hook_pytest.py | 75 +++++++++++++++++++ 4 files changed, 89 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a809502..78f036e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ All notable changes to LettuceDetect are documented here. +## [Unreleased] + +### Fixed +- Claude Code Stop hook: `--min-confidence` above `0.0` no longer drops every span in `--llm-model` mode. Unscored spans are kept, matching `BaseDetector._filter_spans_by_confidence` (#117) + ## [0.2.3] - 2026-08-14 ### Added diff --git a/lettucedetect/integrations/claude_code/README.md b/lettucedetect/integrations/claude_code/README.md index b0c94d8..b69de55 100644 --- a/lettucedetect/integrations/claude_code/README.md +++ b/lettucedetect/integrations/claude_code/README.md @@ -60,7 +60,7 @@ found the agent receives them and revises. | `--llm-model ID` | Generative detector or LLM judge; use `KRLabsOrg/lettucedect-v2-qwen-2b` for typed spans in one pass | | `--llm-base-url URL` | OpenAI-compatible endpoint for `--llm-model` (e.g. `vllm serve KRLabsOrg/lettucedect-v2-qwen-2b`) | | `--context-file F` | Grounding passage file, repeatable; default `context.md` | -| `--min-confidence X` | Report only spans at or above this confidence | +| `--min-confidence X` | Report only spans at or above this confidence; spans the detector did not score (every span in `--llm-model` mode) are always reported | Models: `KRLabsOrg/lettucedect-base-modernbert-en-v1` for prose RAG answers; `KRLabsOrg/lettucedect-v2-mmbert-base` plus diff --git a/lettucedetect/integrations/claude_code/check_answer.py b/lettucedetect/integrations/claude_code/check_answer.py index eb6b019..24ab1a7 100644 --- a/lettucedetect/integrations/claude_code/check_answer.py +++ b/lettucedetect/integrations/claude_code/check_answer.py @@ -195,7 +195,11 @@ def main(argv: list[str] | None = None) -> int: "--min-confidence", type=float, default=0.0, - help="Report only spans at or above this confidence (default 0.0)", + help=( + "Report only spans at or above this confidence (default 0.0). " + "Applies to scored spans only; spans the detector did not score " + "(every span in --llm-model mode) are always reported." + ), ) args = parser.parse_args(argv) @@ -231,7 +235,9 @@ def main(argv: list[str] | None = None) -> int: flagged = [ s for s in spans - if (s.get("confidence", s.get("hallucination_score")) or 0.0) >= args.min_confidence + if args.min_confidence <= 0.0 + or s.get("confidence", s.get("hallucination_score")) is None + or s.get("confidence", s.get("hallucination_score")) >= args.min_confidence ] if not flagged: return 0 diff --git a/tests/test_claude_code_hook_pytest.py b/tests/test_claude_code_hook_pytest.py index ac51381..6c9e6ba 100644 --- a/tests/test_claude_code_hook_pytest.py +++ b/tests/test_claude_code_hook_pytest.py @@ -168,6 +168,81 @@ def test_min_confidence_filters(self, tmp_path): ) assert code == 0 + def test_min_confidence_keeps_unscored_spans(self, tmp_path, capsys): + """Test min confidence keeps unscored spans.""" + ctx = self.make_context(tmp_path) + code = run_main( + ["--model-path", "stub", "--context-file", ctx, "--min-confidence", "0.5"], + {"transcript_path": str(FIXTURE)}, + spans=[ + {"text": "69 million", "hallucination_score": None}, + {"text": "wrong version", "start": 0, "end": 13}, + ], + ) + assert code == 2 + captured = capsys.readouterr() + assert "69 million" in captured.err + assert "wrong version" in captured.err + + def test_min_confidence_mixes_scored_and_unscored(self, tmp_path, capsys): + """Test min confidence keeps unscored spans and drops scored ones.""" + ctx = self.make_context(tmp_path) + code = run_main( + ["--model-path", "stub", "--context-file", ctx, "--min-confidence", "0.5"], + {"transcript_path": str(FIXTURE)}, + spans=[ + {"text": "low confidence", "confidence": 0.1}, + {"text": "native typed span", "category": "unsupported_addition"}, + {"text": "high confidence", "confidence": 0.9}, + ], + ) + assert code == 2 + err = capsys.readouterr().err + assert "low confidence" not in err + assert "native typed span" in err + assert "high confidence" in err + + def test_llm_mode_unscored_spans_reported_above_threshold(self, tmp_path, capsys): + """Test llm mode unscored spans reported above threshold.""" + ctx = self.make_context(tmp_path) + seen = {} + + class StubDetector: + """Stub LLM detector returning native-path spans without confidence.""" + + def __init__(self, **kwargs): + seen.update(kwargs) + + def predict(self, **kwargs): + return [ + { + "text": "added retry logic", + "start": 0, + "end": 19, + "category": "unsupported_addition", + } + ] + + with ( + patch("sys.stdin", io.StringIO(json.dumps({"transcript_path": str(FIXTURE)}))), + patch("lettucedetect.models.inference.HallucinationDetector", StubDetector), + ): + code = main( + [ + "--llm-model", + "KRLabsOrg/lettucedect-v2-qwen-2b", + "--llm-base-url", + "http://localhost:8001/v1", + "--context-file", + ctx, + "--min-confidence", + "0.5", + ] + ) + assert seen["base_url"] == "http://localhost:8001/v1" + assert code == 2 + assert "added retry logic" in capsys.readouterr().err + def test_invalid_stdin_exits_0(self): """Test invalid stdin exits 0.""" with patch("sys.stdin", io.StringIO("not json")): From dcce161ff7c8a46147cae5f0bda14118bef7a2d6 Mon Sep 17 00:00:00 2001 From: Yassin Nouh <70436855+YassinNouh21@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:25:14 +0100 Subject: [PATCH 3/3] fix: shared batch length check in BaseDetector (#122) Add BaseDetector._validate_batch_lengths(prompts, answers). It raises ValueError when the two lengths differ. The message shows both lengths. TransformerDetector, LLMDetector and RAGFactCheckerDetector now call the helper instead of an inline check. The old message text stays as a prefix, so the #113 tests pass without edits. RAGFactCheckerDetector.predict_prompt_batch now zips the answers and the backend results with strict=True. Before this change, a short backend result dropped answers with no error. Add tests for the helper and a new test file for the RAG detector. Follow-up to #113, refs #114. Signed-off-by: yassinnouh21 --- lettucedetect/detectors/base.py | 14 +++++ lettucedetect/detectors/llm.py | 3 +- lettucedetect/detectors/rag_fact_checker.py | 5 +- lettucedetect/detectors/transformer.py | 3 +- tests/test_inference_pytest.py | 17 ++++++ tests/test_rag_fact_checker_pytest.py | 65 +++++++++++++++++++++ 6 files changed, 100 insertions(+), 7 deletions(-) create mode 100644 tests/test_rag_fact_checker_pytest.py diff --git a/lettucedetect/detectors/base.py b/lettucedetect/detectors/base.py index 2fee358..acb505c 100644 --- a/lettucedetect/detectors/base.py +++ b/lettucedetect/detectors/base.py @@ -71,6 +71,20 @@ def _validate_min_confidence(min_confidence: float) -> None: if not 0.0 <= min_confidence <= 1.0: raise ValueError(f"min_confidence must be in [0, 1], got {min_confidence}") + @staticmethod + def _validate_batch_lengths(prompts: list[str], answers: list[str]) -> None: + """Validate that ``prompts`` and ``answers`` have the same length. + + :param prompts: The prompt strings of the batch. + :param answers: The answer strings of the batch. + :raises ValueError: If ``len(prompts) != len(answers)``. + """ + if len(prompts) != len(answers): + raise ValueError( + "Number of prompts must match number of answers, " + f"got {len(prompts)} prompts and {len(answers)} answers" + ) + @staticmethod def _filter_spans_by_confidence( result: list, output_format: str, min_confidence: float diff --git a/lettucedetect/detectors/llm.py b/lettucedetect/detectors/llm.py index ef560b4..c83cc4f 100644 --- a/lettucedetect/detectors/llm.py +++ b/lettucedetect/detectors/llm.py @@ -603,8 +603,7 @@ def predict_prompt_batch( ``output_format="tokens"``. :raises ValueError: If ``len(prompts) != len(answers)``. """ - if len(prompts) != len(answers): - raise ValueError("Number of prompts must match number of answers") + self._validate_batch_lengths(prompts, answers) if output_format not in ["tokens", "spans"]: raise ValueError( f"LLMDetector doesn't support '{output_format}' format. Use 'tokens' or 'spans'" diff --git a/lettucedetect/detectors/rag_fact_checker.py b/lettucedetect/detectors/rag_fact_checker.py index c5b87d0..f22ac8b 100644 --- a/lettucedetect/detectors/rag_fact_checker.py +++ b/lettucedetect/detectors/rag_fact_checker.py @@ -107,8 +107,7 @@ def predict_prompt_batch( min_confidence: float = 0.0, ) -> list[list[dict[str, Any]]]: """Batch prediction using RAGFactChecker's batch processing.""" - if len(prompts) != len(answers): - raise ValueError("Number of prompts must match number of answers") + self._validate_batch_lengths(prompts, answers) self._validate_min_confidence(min_confidence) contexts = [[prompt] for prompt in prompts] # Convert prompts to context lists @@ -116,7 +115,7 @@ def predict_prompt_batch( # Convert each result to lettuceDetect format converted_results = [] - for i, (answer, rag_result) in enumerate(zip(answers, rag_results)): + for i, (answer, rag_result) in enumerate(zip(answers, rag_results, strict=True)): if output_format == "tokens": converted = self._convert_to_tokens(answer, rag_result) elif output_format == "spans": diff --git a/lettucedetect/detectors/transformer.py b/lettucedetect/detectors/transformer.py index c488ddf..9a0e1d6 100644 --- a/lettucedetect/detectors/transformer.py +++ b/lettucedetect/detectors/transformer.py @@ -546,8 +546,7 @@ def predict_prompt_batch( :returns: List of prediction lists, one per input pair. :raises ValueError: If ``len(prompts) != len(answers)``. """ - if len(prompts) != len(answers): - raise ValueError("Number of prompts must match number of answers") + self._validate_batch_lengths(prompts, answers) if not prompts: return [] if output_format not in ("tokens", "spans"): diff --git a/tests/test_inference_pytest.py b/tests/test_inference_pytest.py index f16eb6e..c711f52 100644 --- a/tests/test_inference_pytest.py +++ b/tests/test_inference_pytest.py @@ -454,6 +454,23 @@ def test_filter_keeps_spans_without_confidence(self): assert BaseDetector._filter_spans_by_confidence(spans, "spans", 0.9) == spans +class TestBatchLengthValidation: + """Unit tests for the shared BaseDetector._validate_batch_lengths helper.""" + + def test_mismatch_message_shows_both_lengths(self): + """A length mismatch raises a ValueError that shows the two lengths.""" + with pytest.raises(ValueError, match="got 2 prompts and 1 answers"): + BaseDetector._validate_batch_lengths(["p1", "p2"], ["a1"]) + + @pytest.mark.parametrize( + ("prompts", "answers"), + [([], []), (["p1"], ["a1"]), (["p1", "p2"], ["a1", "a2"])], + ) + def test_equal_lengths_raise_no_error(self, prompts, answers): + """The helper accepts equal lengths, including two empty lists.""" + BaseDetector._validate_batch_lengths(prompts, answers) + + class TestTransformerMinConfidence: """min_confidence behaviour wired through TransformerDetector.""" diff --git a/tests/test_rag_fact_checker_pytest.py b/tests/test_rag_fact_checker_pytest.py new file mode 100644 index 0000000..1513b3a --- /dev/null +++ b/tests/test_rag_fact_checker_pytest.py @@ -0,0 +1,65 @@ +"""Pytest tests for RAGFactCheckerDetector batch prediction.""" + +from unittest.mock import patch + +import pytest + +from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector + +HALLUCINATED_RESULT = {"hallucinated_triplets": [["Paris", "is capital of", "Germany"]]} +CLEAN_RESULT = {"hallucinated_triplets": []} + + +@pytest.fixture +def detector(): + """RAGFactCheckerDetector with a mock backend. The tests need no API key and no network.""" + with patch("lettucedetect.ragfactchecker.RAGFactChecker"): + return RAGFactCheckerDetector() + + +class TestPredictPromptBatchRAG: + """predict_prompt_batch() keeps one result for each (prompt, answer) pair.""" + + @pytest.mark.parametrize( + ("prompts", "answers"), + [ + (["p1", "p2"], ["a1"]), + (["p1"], ["a1", "a2"]), + (["p1"], []), + ([], ["a1"]), + ], + ) + def test_mismatched_lengths_raise_value_error(self, detector, prompts, answers): + """A length mismatch raises a ValueError before the backend gets a request.""" + with pytest.raises(ValueError, match="Number of prompts must match number of answers"): + detector.predict_prompt_batch(prompts, answers) + detector.rag.detect_hallucinations_batch.assert_not_called() + + def test_matched_lengths_return_spans_in_input_order(self, detector): + """Equal lengths give one spans result for each pair, in input order.""" + detector.rag.detect_hallucinations_batch.return_value = [HALLUCINATED_RESULT, CLEAN_RESULT] + answers = ["Paris is the capital of Germany.", "Berlin is the capital of Germany."] + + results = detector.predict_prompt_batch(["c1", "c2"], answers, output_format="spans") + + assert len(results) == 2 + assert [span["text"] for span in results[0]] == ["Germany"] + assert results[1] == [] + + def test_matched_lengths_return_tokens_in_input_order(self, detector): + """Equal lengths give one tokens result for each pair, in input order.""" + detector.rag.detect_hallucinations_batch.return_value = [HALLUCINATED_RESULT, CLEAN_RESULT] + answers = ["Paris is the capital of Germany.", "Berlin is the capital of Germany."] + + results = detector.predict_prompt_batch(["c1", "c2"], answers, output_format="tokens") + + assert [len(tokens) for tokens in results] == [6, 6] + assert any(token["pred"] == 1 for token in results[0]) + assert all(token["pred"] == 0 for token in results[1]) + + def test_short_backend_result_raises_instead_of_truncating(self, detector): + """The call raises a ValueError when the backend returns fewer results than answers.""" + detector.rag.detect_hallucinations_batch.return_value = [CLEAN_RESULT] + + with pytest.raises(ValueError, match="shorter"): + detector.predict_prompt_batch(["c1", "c2"], ["a1", "a2"], output_format="spans")