From 5d8e157588ee49273df1712b523edef17d9cb636 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:37:21 +0100 Subject: [PATCH 01/60] test: pin today's TransformerDetector output with golden fixtures (#128) Add tests/golden.py (assert_golden, UPDATE_GOLDEN=1 to rewrite, readable unified diff, floats rounded to 6 places) and record predict, predict_prompt and predict_prompt_batch in "tokens" and "spans" format on a stub model with the local tokenizer, plus a multi-group context and spans typed by a stub typer. Recorded as-is: "tokens" output ends with the trailing [SEP], and the multi-group path flags a token at prob >= 0.5 while the single-group path uses argmax. Co-Authored-By: Claude Sonnet 5.5 --- ...transformer_predict_multi_group_spans.json | 42 +++++ ...ransformer_predict_multi_group_tokens.json | 78 ++++++++ ...ransformer_predict_prompt_batch_spans.json | 44 +++++ ...ansformer_predict_prompt_batch_tokens.json | 88 +++++++++ .../transformer_predict_prompt_spans.json | 44 +++++ .../transformer_predict_prompt_tokens.json | 88 +++++++++ .../golden/transformer_predict_spans.json | 44 +++++ .../golden/transformer_predict_tokens.json | 93 ++++++++++ .../golden/transformer_typed_spans.json | 170 ++++++++++++++++++ tests/golden.py | 69 +++++++ tests/test_golden_transformer_pytest.py | 157 ++++++++++++++++ 11 files changed, 917 insertions(+) create mode 100644 tests/fixtures/golden/transformer_predict_multi_group_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_multi_group_tokens.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_batch_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_tokens.json create mode 100644 tests/fixtures/golden/transformer_predict_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_tokens.json create mode 100644 tests/fixtures/golden/transformer_typed_spans.json create mode 100644 tests/golden.py create mode 100644 tests/test_golden_transformer_pytest.py diff --git a/tests/fixtures/golden/transformer_predict_multi_group_spans.json b/tests/fixtures/golden/transformer_predict_multi_group_spans.json new file mode 100644 index 0000000..2d1339c --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_multi_group_spans.json @@ -0,0 +1,42 @@ +{ + "groups": [ + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "short answer word . short answer word . short answer word ." + ], + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "word word word word word word word word word word word word word word ." + ] + ], + "output": [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 23, + "start": 13, + "text": "capital of" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + }, + { + "confidence": 0.993307, + "end": 53, + "start": 46, + "text": "is word" + } + ] +} diff --git a/tests/fixtures/golden/transformer_predict_multi_group_tokens.json b/tests/fixtures/golden/transformer_predict_multi_group_tokens.json new file mode 100644 index 0000000..863309d --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_multi_group_tokens.json @@ -0,0 +1,78 @@ +{ + "groups": [ + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "short answer word . short answer word . short answer word ." + ], + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "word word word word word word word word word word word word word word ." + ] + ], + "output": [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 0, + "prob": 0.119203, + "token": "answer" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +} diff --git a/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json b/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json new file mode 100644 index 0000000..aad175b --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json @@ -0,0 +1,44 @@ +[ + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + } + ], + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json b/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json new file mode 100644 index 0000000..b2d95a5 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json @@ -0,0 +1,88 @@ +[ + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_prompt_spans.json b/tests/fixtures/golden/transformer_predict_prompt_spans.json new file mode 100644 index 0000000..aad175b --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_spans.json @@ -0,0 +1,44 @@ +[ + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + } + ], + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_prompt_tokens.json b/tests/fixtures/golden/transformer_predict_prompt_tokens.json new file mode 100644 index 0000000..b2d95a5 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_tokens.json @@ -0,0 +1,88 @@ +[ + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_spans.json b/tests/fixtures/golden/transformer_predict_spans.json new file mode 100644 index 0000000..065dce4 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_spans.json @@ -0,0 +1,44 @@ +[ + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + } + ], + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + }, + { + "confidence": 0.880797, + "end": 17, + "start": 12, + "text": "short" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_tokens.json b/tests/fixtures/golden/transformer_predict_tokens.json new file mode 100644 index 0000000..6ceceb7 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_tokens.json @@ -0,0 +1,93 @@ +[ + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.006693, + "token": "." + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 0, + "prob": 0.119203, + "token": "answer" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "short" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +] diff --git a/tests/fixtures/golden/transformer_typed_spans.json b/tests/fixtures/golden/transformer_typed_spans.json new file mode 100644 index 0000000..52879c4 --- /dev/null +++ b/tests/fixtures/golden/transformer_typed_spans.json @@ -0,0 +1,170 @@ +{ + "predict": [ + [ + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 11, + "start": 4, + "subcategory": "SUB[32]", + "text": "capital" + }, + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 24, + "start": 22, + "subcategory": "SUB[32]", + "text": "is" + } + ], + [ + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 8, + "start": 6, + "subcategory": "SUB[32]", + "text": "is" + }, + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 20, + "start": 13, + "subcategory": "SUB[32]", + "text": "capital" + } + ], + [ + { + "category": "CAT[word]", + "confidence": 0.993307, + "end": 4, + "start": 0, + "subcategory": "SUB[19]", + "text": "word" + }, + { + "category": "CAT[short]", + "confidence": 0.880797, + "end": 17, + "start": 12, + "subcategory": "SUB[19]", + "text": "short" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 8, + "start": 6, + "subcategory": "SUB[32]", + "text": "is" + }, + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 20, + "start": 13, + "subcategory": "SUB[32]", + "text": "capital" + } + ], + [ + { + "category": "CAT[word]", + "confidence": 0.993307, + "end": 4, + "start": 0, + "subcategory": "SUB[17]", + "text": "word" + } + ], + [ + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 11, + "start": 4, + "subcategory": "SUB[54]", + "text": "capital" + }, + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 24, + "start": 22, + "subcategory": "SUB[54]", + "text": "is" + }, + { + "category": "CAT[and]", + "confidence": 0.880797, + "end": 34, + "start": 31, + "subcategory": "SUB[54]", + "text": "and" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 8, + "start": 6, + "subcategory": "SUB[32]", + "text": "is" + }, + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 20, + "start": 13, + "subcategory": "SUB[32]", + "text": "capital" + } + ], + [ + { + "category": "CAT[word]", + "confidence": 0.993307, + "end": 4, + "start": 0, + "subcategory": "SUB[17]", + "text": "word" + } + ], + [ + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 11, + "start": 4, + "subcategory": "SUB[54]", + "text": "capital" + }, + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 24, + "start": 22, + "subcategory": "SUB[54]", + "text": "is" + }, + { + "category": "CAT[and]", + "confidence": 0.880797, + "end": 34, + "start": 31, + "subcategory": "SUB[54]", + "text": "and" + } + ] + ] +} diff --git a/tests/golden.py b/tests/golden.py new file mode 100644 index 0000000..fc30bb2 --- /dev/null +++ b/tests/golden.py @@ -0,0 +1,69 @@ +"""Golden-file helper for characterization tests. + +``assert_golden(name, data)`` compares ``data`` with ``tests/fixtures/golden/.json`` and +fails on any difference, printing a unified diff. Run with ``UPDATE_GOLDEN=1`` to rewrite the +file instead (review the resulting git diff: a changed fixture is an intended behaviour change). + +Floats are rounded to 6 places on both sides before comparing, so cross-platform softmax noise +does not flake the suite while any real change still fails. +""" + +from __future__ import annotations + +import difflib +import json +import os +from pathlib import Path +from typing import Any + +GOLDEN_DIR = Path(__file__).parent / "fixtures" / "golden" +_FLOAT_PLACES = 6 + + +def _normalize(value: Any) -> Any: # noqa: ANN401 + """Round floats and turn tuples into lists, recursively.""" + if isinstance(value, float): + return round(value, _FLOAT_PLACES) + if isinstance(value, dict): + return {str(k): _normalize(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_normalize(v) for v in value] + return value + + +def _dump(data: Any) -> str: # noqa: ANN401 + return json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False) + "\n" + + +def assert_golden(name: str, data: Any) -> None: # noqa: ANN401 + """Assert that ``data`` equals the checked-in golden file ``.json``. + + :param name: Fixture name, without the ``.json`` suffix. + :param data: JSON-serializable value to compare. + """ + path = GOLDEN_DIR / f"{name}.json" + actual = _dump(_normalize(json.loads(json.dumps(data, ensure_ascii=False)))) + + if os.environ.get("UPDATE_GOLDEN") == "1": + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(actual, encoding="utf-8") + return + + if not path.exists(): + raise AssertionError( + f"Golden file {path} does not exist. Record it with UPDATE_GOLDEN=1 and review it." + ) + expected = _dump(_normalize(json.loads(path.read_text(encoding="utf-8")))) + if actual != expected: + diff = "".join( + difflib.unified_diff( + expected.splitlines(keepends=True), + actual.splitlines(keepends=True), + fromfile=f"golden/{name}.json (checked in)", + tofile=f"golden/{name}.json (actual)", + ) + ) + raise AssertionError( + f"Output differs from golden file {name}.json " + f"(UPDATE_GOLDEN=1 rewrites it if the change is intended):\n{diff}" + ) diff --git a/tests/test_golden_transformer_pytest.py b/tests/test_golden_transformer_pytest.py new file mode 100644 index 0000000..071cde0 --- /dev/null +++ b/tests/test_golden_transformer_pytest.py @@ -0,0 +1,157 @@ +"""Golden (characterization) tests pinning today's ``TransformerDetector`` output. + +The model is a stub whose logits are a closed-form function of the token id and the tokenizer is +the local WordPiece one from ``conftest.py``, so the tests are deterministic and network-free. +Recorded output lives in ``tests/fixtures/golden/transformer_*.json``. + +Today's quirks are recorded as-is: ``"tokens"`` output ends with the trailing ``[SEP]`` token, and +the multi-group path flags a token at ``prob >= 0.5`` while the single-group path uses argmax. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors.transformer import TransformerDetector +from tests.golden import assert_golden + +FORMATS = ["tokens", "spans"] +MULTI_MAX_LENGTH = 90 + +# (context passages, answer, question); question None means summarisation. +PREDICT_INPUTS = [ + ( + ["the capital of france is paris ."], + "the capital of france is paris", + "the capital of france ?", + ), + (["the capital of france is paris ."], "paris is the capital .", None), + (["short answer word ."], "word answer short", "short ?"), +] +PROMPTS = [ + "the capital of france is paris .", + "short answer word", + "the capital of france is paris . the capital of france", +] +ANSWERS = ["paris is the capital", "word", "the capital of france is paris and paris"] + +MULTI_CONTEXT = [ + "the capital of france is paris . the capital of france is paris .", + "short answer word . short answer word . short answer word .", + "the capital of france is paris . the capital of france is paris .", + "word word word word word word word word word word word word word word .", +] +MULTI_QUESTION = "the capital of france ?" +MULTI_ANSWER = "paris is the capital of france and the answer is word" + + +def _stub_forward(input_ids=None, attention_mask=None, **kwargs): + """Logits depend only on the token id: P(hallucination) = sigmoid((id*7) % 11 - 5).""" + score = ((input_ids * 7) % 11 - 5).float() / 2 + logits = torch.stack([-score, score], dim=-1) + output = MagicMock() + output.logits = logits + return output + + +def _build(tokenizer, max_length: int) -> TransformerDetector: + model = MagicMock(side_effect=_stub_forward) + with ( + patch( + "lettucedetect.detectors.transformer.AutoTokenizer.from_pretrained", + return_value=tokenizer, + ), + patch( + "lettucedetect.detectors.transformer.AutoModelForTokenClassification.from_pretrained", + return_value=model, + ), + ): + return TransformerDetector(model_path="dummy_path", max_length=max_length) + + +class _StubTyper: + """Types every span from its own text and the context string it was handed.""" + + def type_spans(self, answer, context, spans): + for span in spans: + span["category"] = f"CAT[{span['text']}]" + span["subcategory"] = f"SUB[{len(context)}]" + return spans + + +@pytest.fixture +def detector(local_wordpiece_tokenizer): + return _build(local_wordpiece_tokenizer, 512) + + +@pytest.fixture +def multi_detector(local_wordpiece_tokenizer): + return _build(local_wordpiece_tokenizer, MULTI_MAX_LENGTH) + + +def _predict_all(det, output_format): + return [det.predict(c, a, q, output_format=output_format) for c, a, q in PREDICT_INPUTS] + + +def _predict_prompt_all(det, output_format): + return [det.predict_prompt(p, a, output_format=output_format) for p, a in zip(PROMPTS, ANSWERS)] + + +def _predict_prompt_batch(det, output_format): + return det.predict_prompt_batch(PROMPTS, ANSWERS, output_format=output_format) + + +@pytest.mark.parametrize("output_format", FORMATS) +class TestTransformerGolden: + """Every public entry point in both output formats.""" + + def test_predict(self, detector, output_format): + """predict() on the small inputs.""" + assert_golden(f"transformer_predict_{output_format}", _predict_all(detector, output_format)) + + def test_predict_prompt(self, detector, output_format): + """predict_prompt() on the small inputs.""" + assert_golden( + f"transformer_predict_prompt_{output_format}", + _predict_prompt_all(detector, output_format), + ) + + def test_predict_prompt_batch(self, detector, output_format): + """predict_prompt_batch() on the small inputs.""" + assert_golden( + f"transformer_predict_prompt_batch_{output_format}", + _predict_prompt_batch(detector, output_format), + ) + + def test_multi_group(self, multi_detector, output_format): + """A context needing several passage groups, aggregated with max().""" + groups = multi_detector._group_passages_into_chunks( + MULTI_CONTEXT, MULTI_QUESTION, MULTI_ANSWER + ) + assert len(groups) > 1, "the multi-group fixture must really need several groups" + output = multi_detector.predict( + MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION, output_format=output_format + ) + assert_golden( + f"transformer_predict_multi_group_{output_format}", + {"groups": groups, "output": output}, + ) + + +class TestTransformerTypedSpansGolden: + """Spans typed by a stub typer.""" + + def test_typed_spans(self, detector): + """The typer sees joined passages in predict and the full prompt elsewhere.""" + detector.typer = _StubTyper() + assert_golden( + "transformer_typed_spans", + { + "predict": _predict_all(detector, "spans"), + "predict_prompt": _predict_prompt_all(detector, "spans"), + "predict_prompt_batch": _predict_prompt_batch(detector, "spans"), + }, + ) From f06fa7caff0e62de949599cbb324f3d084a3f0c6 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:40:03 +0100 Subject: [PATCH 02/60] test: pin today's LLMDetector output with golden fixtures (#129) Record predict, predict_prompt and predict_prompt_batch in "tokens" and "spans" format through a fake LLMClient: the judge with defaults, zero_shot, include_reasoning, each include_taxonomy form (True, list, flat dict, nested dict), verify, and native mode with and without include_reasoning. Also record today's behaviour in the cases the epic changes (llm_defect_*): a reply without hallucination_list, an unparseable reply, an item that is not found in the answer, and spans without confidence. Co-Authored-By: Claude Sonnet 5.5 --- .../llm_defect_item_not_in_answer_spans.json | 50 +++ .../llm_defect_item_not_in_answer_tokens.json | 290 ++++++++++++++++++ ...lm_defect_no_hallucination_list_spans.json | 14 + ...m_defect_no_hallucination_list_tokens.json | 290 ++++++++++++++++++ ..._defect_span_without_confidence_spans.json | 56 ++++ ...defect_span_without_confidence_tokens.json | 290 ++++++++++++++++++ .../llm_defect_unparseable_reply_spans.json | 14 + .../llm_defect_unparseable_reply_tokens.json | 290 ++++++++++++++++++ .../golden/llm_include_reasoning_spans.json | 62 ++++ .../golden/llm_include_reasoning_tokens.json | 290 ++++++++++++++++++ .../golden/llm_judge_defaults_spans.json | 50 +++ .../golden/llm_judge_defaults_tokens.json | 290 ++++++++++++++++++ .../llm_native_include_reasoning_spans.json | 68 ++++ .../llm_native_include_reasoning_tokens.json | 290 ++++++++++++++++++ tests/fixtures/golden/llm_native_spans.json | 62 ++++ tests/fixtures/golden/llm_native_tokens.json | 290 ++++++++++++++++++ .../golden/llm_taxonomy_flat_dict_spans.json | 56 ++++ .../golden/llm_taxonomy_flat_dict_tokens.json | 290 ++++++++++++++++++ .../golden/llm_taxonomy_list_spans.json | 56 ++++ .../golden/llm_taxonomy_list_tokens.json | 290 ++++++++++++++++++ .../llm_taxonomy_nested_dict_spans.json | 62 ++++ .../llm_taxonomy_nested_dict_tokens.json | 290 ++++++++++++++++++ .../golden/llm_taxonomy_true_spans.json | 62 ++++ .../golden/llm_taxonomy_true_tokens.json | 290 ++++++++++++++++++ tests/fixtures/golden/llm_verify_spans.json | 50 +++ tests/fixtures/golden/llm_verify_tokens.json | 290 ++++++++++++++++++ .../fixtures/golden/llm_zero_shot_spans.json | 50 +++ .../fixtures/golden/llm_zero_shot_tokens.json | 290 ++++++++++++++++++ tests/test_golden_llm_pytest.py | 229 ++++++++++++++ 29 files changed, 5001 insertions(+) create mode 100644 tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json create mode 100644 tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json create mode 100644 tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json create mode 100644 tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json create mode 100644 tests/fixtures/golden/llm_defect_span_without_confidence_spans.json create mode 100644 tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json create mode 100644 tests/fixtures/golden/llm_defect_unparseable_reply_spans.json create mode 100644 tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json create mode 100644 tests/fixtures/golden/llm_include_reasoning_spans.json create mode 100644 tests/fixtures/golden/llm_include_reasoning_tokens.json create mode 100644 tests/fixtures/golden/llm_judge_defaults_spans.json create mode 100644 tests/fixtures/golden/llm_judge_defaults_tokens.json create mode 100644 tests/fixtures/golden/llm_native_include_reasoning_spans.json create mode 100644 tests/fixtures/golden/llm_native_include_reasoning_tokens.json create mode 100644 tests/fixtures/golden/llm_native_spans.json create mode 100644 tests/fixtures/golden/llm_native_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_list_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_list_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_true_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_true_tokens.json create mode 100644 tests/fixtures/golden/llm_verify_spans.json create mode 100644 tests/fixtures/golden/llm_verify_tokens.json create mode 100644 tests/fixtures/golden/llm_zero_shot_spans.json create mode 100644 tests/fixtures/golden/llm_zero_shot_tokens.json create mode 100644 tests/test_golden_llm_pytest.py diff --git a/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json b/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json b/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json b/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json new file mode 100644 index 0000000..53801cd --- /dev/null +++ b/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json @@ -0,0 +1,14 @@ +{ + "predict": [ + [], + [] + ], + "predict_prompt": [ + [], + [] + ], + "predict_prompt_batch": [ + [], + [] + ] +} diff --git a/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json b/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json new file mode 100644 index 0000000..fbeff16 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json b/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json new file mode 100644 index 0000000..69547a5 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json @@ -0,0 +1,56 @@ +{ + "predict": [ + [ + { + "end": 38, + "reasoning": "no score given", + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "reasoning": "no score given", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "reasoning": "no score given", + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "reasoning": "no score given", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "reasoning": "no score given", + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "reasoning": "no score given", + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json b/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json b/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json new file mode 100644 index 0000000..53801cd --- /dev/null +++ b/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json @@ -0,0 +1,14 @@ +{ + "predict": [ + [], + [] + ], + "predict_prompt": [ + [], + [] + ], + "predict_prompt_batch": [ + [], + [] + ] +} diff --git a/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json b/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json new file mode 100644 index 0000000..fbeff16 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_include_reasoning_spans.json b/tests/fixtures/golden/llm_include_reasoning_spans.json new file mode 100644 index 0000000..268b5be --- /dev/null +++ b/tests/fixtures/golden/llm_include_reasoning_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "confidence": 0.93, + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "text": "69 million" + } + ], + [ + { + "confidence": 0.88, + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.93, + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "text": "69 million" + } + ], + [ + { + "confidence": 0.88, + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.93, + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "text": "69 million" + } + ], + [ + { + "confidence": 0.88, + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_include_reasoning_tokens.json b/tests/fixtures/golden/llm_include_reasoning_tokens.json new file mode 100644 index 0000000..4205620 --- /dev/null +++ b/tests/fixtures/golden/llm_include_reasoning_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.93, + "token": "69" + }, + { + "pred": 1, + "prob": 0.93, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.88, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.93, + "token": "69" + }, + { + "pred": 1, + "prob": 0.93, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.88, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.93, + "token": "69" + }, + { + "pred": 1, + "prob": 0.93, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.88, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_judge_defaults_spans.json b/tests/fixtures/golden/llm_judge_defaults_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_judge_defaults_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_judge_defaults_tokens.json b/tests/fixtures/golden/llm_judge_defaults_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_judge_defaults_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_include_reasoning_spans.json b/tests/fixtures/golden/llm_native_include_reasoning_spans.json new file mode 100644 index 0000000..06bd954 --- /dev/null +++ b/tests/fixtures/golden/llm_native_include_reasoning_spans.json @@ -0,0 +1,68 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_include_reasoning_tokens.json b/tests/fixtures/golden/llm_native_include_reasoning_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_native_include_reasoning_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_spans.json b/tests/fixtures/golden/llm_native_spans.json new file mode 100644 index 0000000..0f9e745 --- /dev/null +++ b/tests/fixtures/golden/llm_native_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_tokens.json b/tests/fixtures/golden/llm_native_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_native_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json b/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json new file mode 100644 index 0000000..779f88e --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json @@ -0,0 +1,56 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json b/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_list_spans.json b/tests/fixtures/golden/llm_taxonomy_list_spans.json new file mode 100644 index 0000000..779f88e --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_list_spans.json @@ -0,0 +1,56 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_list_tokens.json b/tests/fixtures/golden/llm_taxonomy_list_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_list_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json b/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json new file mode 100644 index 0000000..0f9e745 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json b/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_true_spans.json b/tests/fixtures/golden/llm_taxonomy_true_spans.json new file mode 100644 index 0000000..0f9e745 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_true_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_true_tokens.json b/tests/fixtures/golden/llm_taxonomy_true_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_true_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_verify_spans.json b/tests/fixtures/golden/llm_verify_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_verify_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_verify_tokens.json b/tests/fixtures/golden/llm_verify_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_verify_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_zero_shot_spans.json b/tests/fixtures/golden/llm_zero_shot_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_zero_shot_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_zero_shot_tokens.json b/tests/fixtures/golden/llm_zero_shot_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_zero_shot_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/test_golden_llm_pytest.py b/tests/test_golden_llm_pytest.py new file mode 100644 index 0000000..46d4893 --- /dev/null +++ b/tests/test_golden_llm_pytest.py @@ -0,0 +1,229 @@ +"""Golden (characterization) tests pinning today's ``LLMDetector`` output. + +Every configuration runs through a fake ``LLMClient`` that returns fixed replies, so the tests are +network-free and need no API key. Each recording holds ``predict``, ``predict_prompt`` and +``predict_prompt_batch`` output for one configuration and one output format, in +``tests/fixtures/golden/llm__.json``. + +The ``llm_defect_*`` recordings are today's behaviour where the detectors epic changes it (spans +without ``confidence``, unparseable replies returning no spans, items missing from the answer); the +pull request that fixes one updates its fixture as an intended change. +""" + +from __future__ import annotations + +import json + +import pytest + +from lettucedetect.detectors.llm import LLMDetector +from lettucedetect.detectors.llm_client import LLMClient +from tests.golden import assert_golden + +FORMATS = ["tokens", "spans"] + +# (context passages, answer, question); the answers are not substrings of each other, so the fake +# client can tell which reply to give from the request text alone. +CASES = [ + ( + ["France has about 67 million people."], + "The population of France is 69 million and Paris is its capital.", + "What is the population of France?", + ), + (["Lisbon is the capital of Portugal."], "Lisbon is the capital of Spain.", None), +] +ANSWERS = [case[1] for case in CASES] +PROMPTS = ["Source: France has about 67 million people.", "Source: Lisbon is in Portugal."] + +VERIFY_SYSTEM_MARKER = "strict fact-checker" + + +class FakeClient(LLMClient): + """Returns a fixed reply per answer (judge/native) or per answer (verify), no network.""" + + def __init__(self, replies: dict[str, str], verify_replies: dict[str, str] | None = None): + """Store replies keyed by the answer they respond to.""" + self.replies = replies + self.verify_replies = verify_replies or {} + + def complete(self, system, user, model, temperature, schema) -> str: + """Pick the reply of the answer found in ``user``; verification has its own replies.""" + table = self.verify_replies if VERIFY_SYSTEM_MARKER in system else self.replies + for answer, reply in table.items(): + if answer in user: + return reply + raise AssertionError(f"no fixed reply for request: {user[:200]!r}") + + +def _judge(*items_per_answer: list) -> dict[str, str]: + return { + answer: json.dumps({"hallucination_list": items}) + for answer, items in zip(ANSWERS, items_per_answer) + } + + +def _native(*spans_per_answer: list) -> dict[str, str]: + return { + answer: json.dumps({"hallucinated_spans": spans}) + for answer, spans in zip(ANSWERS, spans_per_answer) + } + + +def _verdicts(*rejected_per_answer: list) -> dict[str, str]: + return { + answer: json.dumps( + {"verifications": [{"text": t, "reasoning": "r", "is_hallucination": False} for t in r]} + ) + for answer, r in zip(ANSWERS, rejected_per_answer) + } + + +PLAIN = _judge(["69 million"], ["Spain"]) +REASONED = _judge( + [ + { + "text": "69 million", + "reasoning": "source says 67 million", + "confidence": 0.93, + "is_hallucination": True, + }, + { + "text": "Paris", + "reasoning": "not stated, but harmless", + "confidence": 0.31, + "is_hallucination": False, + }, + ], + [ + { + "text": "Spain", + "reasoning": "source says Portugal", + "confidence": 0.88, + "is_hallucination": True, + } + ], +) +TYPED = _judge( + [{"text": "69 million", "category": "contradiction", "subcategory": "numerical"}], + [{"text": "Spain", "category": "contradiction", "subcategory": "entity"}], +) +TYPED_CATEGORY_ONLY = _judge( + [{"text": "69 million", "category": "contradiction"}], + [{"text": "Spain", "category": "contradiction"}], +) +CUSTOM_CATEGORIES = { + "wrong_number": "A number that differs from the source", + "other": "Anything else", +} +NATIVE_PLAIN = _native( + [{"text": "69 million", "category": "contradiction", "subcategory": "numerical"}], + [{"text": "Spain", "category": "contradiction", "subcategory": "entity"}], +) +NATIVE_EXPLAINED = _native( + [ + { + "text": "69 million", + "category": "contradiction", + "subcategory": "numerical", + "explanation": "source says 67 million", + } + ], + [ + { + "text": "Spain", + "category": "contradiction", + "subcategory": "entity", + "explanation": "source says Portugal", + } + ], +) + +# name -> (constructor kwargs, judge/native replies, verification replies) +CONFIGS = { + "judge_defaults": ({}, PLAIN, None), + "zero_shot": ({"zero_shot": True}, PLAIN, None), + "include_reasoning": ({"include_reasoning": True}, REASONED, None), + "taxonomy_true": ({"include_taxonomy": True}, TYPED, None), + "taxonomy_list": ( + {"include_taxonomy": ["contradiction", "fabricated_reference"]}, + TYPED_CATEGORY_ONLY, + None, + ), + "taxonomy_flat_dict": ({"include_taxonomy": CUSTOM_CATEGORIES}, TYPED_CATEGORY_ONLY, None), + "taxonomy_nested_dict": ( + { + "include_taxonomy": { + "categories": CUSTOM_CATEGORIES, + "subcategories": {"digits": "A wrong digit", "name": "A wrong name"}, + } + }, + TYPED, + None, + ), + "verify": ( + {"verify": True}, + _judge(["69 million", "Paris"], ["Spain"]), + _verdicts(["Paris"], []), + ), + "native": ({"native": True}, NATIVE_PLAIN, None), + "native_include_reasoning": ( + {"native": True, "include_reasoning": True}, + NATIVE_EXPLAINED, + None, + ), + # Defect cases: today's output where later tickets change the behaviour. + "defect_no_hallucination_list": ( + {}, + {answer: json.dumps({"analysis": "nothing to list"}) for answer in ANSWERS}, + None, + ), + "defect_unparseable_reply": ({}, {answer: "not json at all" for answer in ANSWERS}, None), + "defect_item_not_in_answer": ( + {}, + _judge(["Mars", "69 million"], ["Spain", "Madrid"]), + None, + ), + "defect_span_without_confidence": ( + {"include_reasoning": True}, + _judge( + [{"text": "69 million", "reasoning": "no score given"}], + [{"text": "Spain", "reasoning": "no score given"}], + ), + None, + ), +} + + +def _run(name: str, output_format: str, tmp_path) -> dict: + kwargs, replies, verify_replies = CONFIGS[name] + kwargs = {"native": False, **kwargs} + counter = iter(range(100)) + + def detector() -> LLMDetector: + # A fresh cache per entry point, so no entry point is answered from another's cache. + return LLMDetector( + client=FakeClient(replies, verify_replies), + cache_file=str(tmp_path / f"cache_{next(counter)}.json"), + **kwargs, + ) + + return { + "predict": [ + detector().predict(ctx, ans, question, output_format=output_format) + for ctx, ans, question in CASES + ], + "predict_prompt": [ + detector().predict_prompt(prompt, ans, output_format=output_format) + for prompt, ans in zip(PROMPTS, ANSWERS) + ], + "predict_prompt_batch": detector().predict_prompt_batch( + PROMPTS, ANSWERS, output_format=output_format + ), + } + + +@pytest.mark.parametrize("output_format", FORMATS) +@pytest.mark.parametrize("name", list(CONFIGS)) +def test_llm_golden(name, output_format, tmp_path): + """Pin every entry point for one configuration and one output format.""" + assert_golden(f"llm_{name}_{output_format}", _run(name, output_format, tmp_path)) From 305ab25b27fd18a0c12848f3668b731efe247dd0 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:41:47 +0100 Subject: [PATCH 03/60] test: pin today's RAGFactCheckerDetector output with golden fixtures (#130) Record "tokens", "spans" and "detailed" output of predict, predict_prompt and predict_prompt_batch through a fake fact checker, a triplet matched only by the single-word fallback (confidence 0.7), and the merge defect where a merged span's text is shorter than its offsets (rag_merge_overlap_text_shorter_than_offsets_*, for the fix PR to update). Co-Authored-By: Claude Sonnet 5.5 --- tests/fixtures/golden/rag_basic_detailed.json | 194 ++++++++++++ tests/fixtures/golden/rag_basic_spans.json | 86 ++++++ tests/fixtures/golden/rag_basic_tokens.json | 290 ++++++++++++++++++ .../golden/rag_batch_detailed_error.json | 3 + ...ap_text_shorter_than_offsets_detailed.json | 110 +++++++ ...erlap_text_shorter_than_offsets_spans.json | 47 +++ ...rlap_text_shorter_than_offsets_tokens.json | 74 +++++ .../rag_single_word_match_detailed.json | 104 +++++++ .../golden/rag_single_word_match_spans.json | 50 +++ .../golden/rag_single_word_match_tokens.json | 74 +++++ tests/test_golden_rag_fact_checker_pytest.py | 117 +++++++ 11 files changed, 1149 insertions(+) create mode 100644 tests/fixtures/golden/rag_basic_detailed.json create mode 100644 tests/fixtures/golden/rag_basic_spans.json create mode 100644 tests/fixtures/golden/rag_basic_tokens.json create mode 100644 tests/fixtures/golden/rag_batch_detailed_error.json create mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json create mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json create mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json create mode 100644 tests/fixtures/golden/rag_single_word_match_detailed.json create mode 100644 tests/fixtures/golden/rag_single_word_match_spans.json create mode 100644 tests/fixtures/golden/rag_single_word_match_tokens.json create mode 100644 tests/test_golden_rag_fact_checker_pytest.py diff --git a/tests/fixtures/golden/rag_basic_detailed.json b/tests/fixtures/golden/rag_basic_detailed.json new file mode 100644 index 0000000..799d091 --- /dev/null +++ b/tests/fixtures/golden/rag_basic_detailed.json @@ -0,0 +1,194 @@ +{ + "predict": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "population", + "69 million" + ] + ] + } + }, + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Lisbon", + "capital", + "Spain" + ] + ] + } + } + ], + "predict_prompt": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "population", + "69 million" + ] + ] + } + }, + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Lisbon", + "capital", + "Spain" + ] + ] + } + } + ] +} diff --git a/tests/fixtures/golden/rag_basic_spans.json b/tests/fixtures/golden/rag_basic_spans.json new file mode 100644 index 0000000..1ec6d7a --- /dev/null +++ b/tests/fixtures/golden/rag_basic_spans.json @@ -0,0 +1,86 @@ +{ + "predict": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_basic_tokens.json b/tests/fixtures/golden/rag_basic_tokens.json new file mode 100644 index 0000000..5f04941 --- /dev/null +++ b/tests/fixtures/golden/rag_basic_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 1, + "prob": 0.9, + "token": "Lisbon" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 1, + "prob": 0.9, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 1, + "prob": 0.9, + "token": "Lisbon" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 1, + "prob": 0.9, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 1, + "prob": 0.9, + "token": "Lisbon" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 1, + "prob": 0.9, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_batch_detailed_error.json b/tests/fixtures/golden/rag_batch_detailed_error.json new file mode 100644 index 0000000..af60366 --- /dev/null +++ b/tests/fixtures/golden/rag_batch_detailed_error.json @@ -0,0 +1,3 @@ +{ + "message": "Unknown output format: detailed" +} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json new file mode 100644 index 0000000..6eadfe1 --- /dev/null +++ b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json @@ -0,0 +1,110 @@ +{ + "predict": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "is", + "unknown" + ], + [ + "France", + "is", + "69 million" + ] + ] + } + } + ], + "predict_prompt": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "is", + "unknown" + ], + [ + "France", + "is", + "69 million" + ] + ] + } + } + ] +} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json new file mode 100644 index 0000000..f426b23 --- /dev/null +++ b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json @@ -0,0 +1,47 @@ +{ + "predict": [ + [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json new file mode 100644 index 0000000..eac2e5c --- /dev/null +++ b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json @@ -0,0 +1,74 @@ +{ + "predict": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million." + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_single_word_match_detailed.json b/tests/fixtures/golden/rag_single_word_match_detailed.json new file mode 100644 index 0000000..ccb4cf8 --- /dev/null +++ b/tests/fixtures/golden/rag_single_word_match_detailed.json @@ -0,0 +1,104 @@ +{ + "predict": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + ] + } + } + ], + "predict_prompt": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + ] + } + } + ] +} diff --git a/tests/fixtures/golden/rag_single_word_match_spans.json b/tests/fixtures/golden/rag_single_word_match_spans.json new file mode 100644 index 0000000..d250e1b --- /dev/null +++ b/tests/fixtures/golden/rag_single_word_match_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_single_word_match_tokens.json b/tests/fixtures/golden/rag_single_word_match_tokens.json new file mode 100644 index 0000000..21e7677 --- /dev/null +++ b/tests/fixtures/golden/rag_single_word_match_tokens.json @@ -0,0 +1,74 @@ +{ + "predict": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "Madrid" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "mentioned" + }, + { + "pred": 0, + "prob": 0.1, + "token": "here." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "Madrid" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "mentioned" + }, + { + "pred": 0, + "prob": 0.1, + "token": "here." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "Madrid" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "mentioned" + }, + { + "pred": 0, + "prob": 0.1, + "token": "here." + } + ] + ] +} diff --git a/tests/test_golden_rag_fact_checker_pytest.py b/tests/test_golden_rag_fact_checker_pytest.py new file mode 100644 index 0000000..7c9fa86 --- /dev/null +++ b/tests/test_golden_rag_fact_checker_pytest.py @@ -0,0 +1,117 @@ +"""Golden (characterization) tests pinning today's ``RAGFactCheckerDetector`` output. + +The detector is built without its constructor (which needs an OpenAI key) and given a fake fact +checker that returns fixed triplets and results, so the tests are network-free. Recordings live in +``tests/fixtures/golden/rag__.json``. + +``rag_merge_overlap_text_shorter_than_offsets_*`` records a defect: ``_merge_overlapping_spans`` +extends ``end`` but keeps the first span's ``text``, so ``text`` is shorter than ``end - start``. +The pull request that fixes it updates exactly those fixtures as an intended change. +""" + +from __future__ import annotations + +import pytest + +from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector +from tests.golden import assert_golden + +ANSWER = "The population of France is 69 million and Paris is its capital." +ANSWER_2 = "Lisbon is the capital of Spain." +ANSWER_3 = "Madrid is mentioned here." +ANSWER_4 = "France is 69 million." + + +def _result(hallucinated: list[list[str]]) -> dict: + return { + "answer_triplets": [["France", "population", "69 million"], ["Paris", "is", "capital"]], + "context_triplets": [["France", "population", "67 million"]], + "hallucinated_triplets": hallucinated, + "fact_check_results": {"0": "contradiction", "1": "entailment"}, + } + + +# case -> [(answer, fact checker result), ...] +CASES = { + "basic": [ + (ANSWER, _result([["France", "population", "69 million"]])), + (ANSWER_2, _result([["Lisbon", "capital", "Spain"]])), + ], + # The fourth element is only found by the single-word fallback, so confidence is 0.7. + "single_word_match": [(ANSWER_3, _result([["Barcelona", "north", "coast", "Madrid"]]))], + # Both triplets match at the same start; merging keeps the first, shorter, text. + "merge_overlap_text_shorter_than_offsets": [ + (ANSWER_4, _result([["France", "is", "unknown"], ["France", "is", "69 million"]])) + ], +} + + +class FakeFactChecker: + """Returns the fixed result recorded for each answer; never touches the network.""" + + def __init__(self, results: dict[str, dict]) -> None: + """Store results keyed by answer.""" + self.results = results + + def detect_hallucinations(self, context, answer, question=None) -> dict: + """Return the fixed result for ``answer``.""" + return self.results[answer] + + def detect_hallucinations_batch(self, contexts, answers) -> list[dict]: + """Return the fixed results for ``answers``, in order.""" + return [self.results[answer] for answer in answers] + + +def _detector(case: str) -> RAGFactCheckerDetector: + detector = RAGFactCheckerDetector.__new__(RAGFactCheckerDetector) # skip the API-key __init__ + detector.rag = FakeFactChecker(dict(CASES[case])) + return detector + + +def _record(case: str, output_format: str) -> dict: + detector = _detector(case) + answers = [answer for answer, _ in CASES[case]] + recording = { + "predict": [ + detector.predict(["context"], answer, "question", output_format=output_format) + for answer in answers + ], + "predict_prompt": [ + detector.predict_prompt("prompt", answer, output_format=output_format) + for answer in answers + ], + } + if output_format != "detailed": # the batch path does not support "detailed" + recording["predict_prompt_batch"] = detector.predict_prompt_batch( + ["prompt"] * len(answers), answers, output_format=output_format + ) + return recording + + +@pytest.mark.parametrize("output_format", ["tokens", "spans", "detailed"]) +@pytest.mark.parametrize("case", list(CASES)) +def test_rag_fact_checker_golden(case, output_format): + """Pin every entry point for one case and one output format.""" + assert_golden(f"rag_{case}_{output_format}", _record(case, output_format)) + + +def test_batch_detailed_is_rejected(): + """Today ``predict_prompt_batch`` raises for ``"detailed"``; the message is recorded.""" + with pytest.raises(ValueError) as exc_info: + _detector("basic").predict_prompt_batch(["p"], [ANSWER], output_format="detailed") + assert_golden("rag_batch_detailed_error", {"message": str(exc_info.value)}) + + +def test_single_word_match_has_lower_confidence(): + """The single-word fallback reports 0.7 instead of 0.9.""" + spans = _detector("single_word_match").predict(["c"], ANSWER_3, output_format="spans") + assert [span["confidence"] for span in spans] == [0.7] + + +def test_merge_leaves_text_shorter_than_offsets(): + """Documents the defect the recording pins: merged ``text`` is shorter than its offsets.""" + spans = _detector("merge_overlap_text_shorter_than_offsets").predict( + ["c"], ANSWER_4, output_format="spans" + ) + assert len(spans) == 1 + assert len(spans[0]["text"]) < spans[0]["end"] - spans[0]["start"] From 836165784b51f060f1de30fd25f33d4eb0bf4478 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:43:26 +0100 Subject: [PATCH 04/60] test: pin make_detector, HallucinationDetector and CacheManager behavior (#131) Record the class make_detector returns for "transformer", "llm" and "rag_fact_checker" and the error for an unknown method; assert and record that HallucinationDetector.predict, predict_prompt and predict_prompt_batch return what the detector alone returns (transformer, LLM, RAG); and pin the CacheManager file after set/delete calls, the _hash strings, and the judge, native and verify keys LLMDetector writes for fixed prompts. Co-Authored-By: Claude Sonnet 5.5 --- .../cache_file_after_set_and_delete.json | 3 + tests/fixtures/golden/cache_hash_strings.json | 5 + .../golden/cache_llm_detector_keys.json | 5 + tests/fixtures/golden/facade_llm.json | 256 +++++++++++++++++ .../golden/facade_rag_fact_checker.json | 235 ++++++++++++++++ tests/fixtures/golden/facade_transformer.json | 240 ++++++++++++++++ .../golden/facade_unknown_method_error.json | 3 + .../golden/factory_make_detector.json | 5 + .../golden/factory_unknown_method_error.json | 3 + tests/test_golden_factory_cache_pytest.py | 261 ++++++++++++++++++ 10 files changed, 1016 insertions(+) create mode 100644 tests/fixtures/golden/cache_file_after_set_and_delete.json create mode 100644 tests/fixtures/golden/cache_hash_strings.json create mode 100644 tests/fixtures/golden/cache_llm_detector_keys.json create mode 100644 tests/fixtures/golden/facade_llm.json create mode 100644 tests/fixtures/golden/facade_rag_fact_checker.json create mode 100644 tests/fixtures/golden/facade_transformer.json create mode 100644 tests/fixtures/golden/facade_unknown_method_error.json create mode 100644 tests/fixtures/golden/factory_make_detector.json create mode 100644 tests/fixtures/golden/factory_unknown_method_error.json create mode 100644 tests/test_golden_factory_cache_pytest.py diff --git a/tests/fixtures/golden/cache_file_after_set_and_delete.json b/tests/fixtures/golden/cache_file_after_set_and_delete.json new file mode 100644 index 0000000..fa650d3 --- /dev/null +++ b/tests/fixtures/golden/cache_file_after_set_and_delete.json @@ -0,0 +1,3 @@ +{ + "raw": "{\"b\": \"overwritten\", \"c\": null}" +} diff --git a/tests/fixtures/golden/cache_hash_strings.json b/tests/fixtures/golden/cache_hash_strings.json new file mode 100644 index 0000000..ef719c5 --- /dev/null +++ b/tests/fixtures/golden/cache_hash_strings.json @@ -0,0 +1,5 @@ +{ + "judge": "ec5ac4b1da6900ff9ebd8861dd2cf54e888198c637968b21f8c06823727ac345", + "native": "e0c18fa663979e29c55f3cc592151185e2be4450bb991470130461398abf2a11", + "verify": "bb75fbd052b29efd14c6378bbdbdf3dd18dc6597f898cc8fba01b5bec37f326a" +} diff --git a/tests/fixtures/golden/cache_llm_detector_keys.json b/tests/fixtures/golden/cache_llm_detector_keys.json new file mode 100644 index 0000000..a394236 --- /dev/null +++ b/tests/fixtures/golden/cache_llm_detector_keys.json @@ -0,0 +1,5 @@ +{ + "judge": "95ed92978e40a6929b505d9122f448e52ee2cc795db4f9c82bb6aa76b531d292", + "native": "fd6490df19ee0ae38277af6c46ddfd0eb53662aec83c364b47631b99ec38a726", + "verify": "251bc953856c96dd67d8f76f19d3e8f8292c0098610daf043bfd80f1a622469f" +} diff --git a/tests/fixtures/golden/facade_llm.json b/tests/fixtures/golden/facade_llm.json new file mode 100644 index 0000000..c620c98 --- /dev/null +++ b/tests/fixtures/golden/facade_llm.json @@ -0,0 +1,256 @@ +{ + "default": { + "predict": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] + }, + "spans": { + "predict": [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + "predict_prompt": [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] + } +} diff --git a/tests/fixtures/golden/facade_rag_fact_checker.json b/tests/fixtures/golden/facade_rag_fact_checker.json new file mode 100644 index 0000000..66a078d --- /dev/null +++ b/tests/fixtures/golden/facade_rag_fact_checker.json @@ -0,0 +1,235 @@ +{ + "spans": { + "predict": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "predict_prompt": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ] + ] + }, + "tokens": { + "predict": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ] + ] + } +} diff --git a/tests/fixtures/golden/facade_transformer.json b/tests/fixtures/golden/facade_transformer.json new file mode 100644 index 0000000..c097c47 --- /dev/null +++ b/tests/fixtures/golden/facade_transformer.json @@ -0,0 +1,240 @@ +{ + "default": { + "predict": [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + "predict_prompt": [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] + ] + }, + "spans": { + "predict": [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + } + ], + "predict_prompt": [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + } + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + } + ], + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + } + ] + ] + } +} diff --git a/tests/fixtures/golden/facade_unknown_method_error.json b/tests/fixtures/golden/facade_unknown_method_error.json new file mode 100644 index 0000000..53c152b --- /dev/null +++ b/tests/fixtures/golden/facade_unknown_method_error.json @@ -0,0 +1,3 @@ +{ + "message": "Unknown detector method: bogus. Use one of: transformer, llm, rag_fact_checker" +} diff --git a/tests/fixtures/golden/factory_make_detector.json b/tests/fixtures/golden/factory_make_detector.json new file mode 100644 index 0000000..771cf75 --- /dev/null +++ b/tests/fixtures/golden/factory_make_detector.json @@ -0,0 +1,5 @@ +{ + "llm": "lettucedetect.detectors.llm.LLMDetector", + "rag_fact_checker": "lettucedetect.detectors.rag_fact_checker.RAGFactCheckerDetector", + "transformer": "lettucedetect.detectors.transformer.TransformerDetector" +} diff --git a/tests/fixtures/golden/factory_unknown_method_error.json b/tests/fixtures/golden/factory_unknown_method_error.json new file mode 100644 index 0000000..53c152b --- /dev/null +++ b/tests/fixtures/golden/factory_unknown_method_error.json @@ -0,0 +1,3 @@ +{ + "message": "Unknown detector method: bogus. Use one of: transformer, llm, rag_fact_checker" +} diff --git a/tests/test_golden_factory_cache_pytest.py b/tests/test_golden_factory_cache_pytest.py new file mode 100644 index 0000000..ef673f2 --- /dev/null +++ b/tests/test_golden_factory_cache_pytest.py @@ -0,0 +1,261 @@ +"""Golden (characterization) tests for ``make_detector``, ``HallucinationDetector`` and the cache. + +Builds on the stubs of the transformer, LLM and RAG golden tests. Recordings live in +``tests/fixtures/golden/{factory,facade,cache}_*.json``. + +The cache keys must stay byte-identical when a later change adds ``model_version`` and it is +``None``. They are SHA-256 hashes of the full prompt, so they also change whenever a prompt +template or few-shot example file changes, which invalidates users' caches: re-record on purpose. +""" + +from __future__ import annotations + +import json +from unittest.mock import MagicMock, patch + +import pytest + +from lettucedetect.detectors.cache import CacheManager +from lettucedetect.detectors.factory import make_detector +from lettucedetect.detectors.llm import LLMDetector +from lettucedetect.models.inference import HallucinationDetector +from lettucedetect.prompts import generative as gen +from tests.golden import assert_golden +from tests.test_golden_llm_pytest import ( + ANSWERS, + CASES, + NATIVE_PLAIN, + PLAIN, + PROMPTS, + FakeClient, + _judge, + _verdicts, +) +from tests.test_golden_rag_fact_checker_pytest import ANSWER as RAG_ANSWER +from tests.test_golden_rag_fact_checker_pytest import FakeFactChecker, _result +from tests.test_golden_transformer_pytest import ( + ANSWERS as TRANSFORMER_ANSWERS, +) +from tests.test_golden_transformer_pytest import ( + PREDICT_INPUTS, + _build, + _stub_forward, +) +from tests.test_golden_transformer_pytest import ( + PROMPTS as TRANSFORMER_PROMPTS, +) + +TRANSFORMER_PATCH = "lettucedetect.detectors.transformer.{}.from_pretrained" +RAG_PATCH = "lettucedetect.ragfactchecker.RAGFactChecker" + + +def _type_name(obj: object) -> str: + return f"{type(obj).__module__}.{type(obj).__qualname__}" + + +class _Patched: + """Context manager replacing model/tokenizer loading with the local stubs.""" + + def __init__(self, tokenizer) -> None: + self.patches = [ + patch(TRANSFORMER_PATCH.format("AutoTokenizer"), return_value=tokenizer), + patch( + TRANSFORMER_PATCH.format("AutoModelForTokenClassification"), + return_value=MagicMock(side_effect=_stub_forward), + ), + ] + + def __enter__(self) -> None: + for p in self.patches: + p.start() + + def __exit__(self, *exc: object) -> None: + for p in reversed(self.patches): + p.stop() + + +class TestMakeDetector: + """The factory builds the right class per method and rejects unknown ones.""" + + def test_returns_the_right_class_per_method(self, local_wordpiece_tokenizer, tmp_path): + """Each method maps to its detector class (loading replaced by fakes).""" + with _Patched(local_wordpiece_tokenizer): + transformer = make_detector("transformer", model_path="dummy_path", max_length=64) + llm = make_detector( + "llm", client=FakeClient({}), cache_file=str(tmp_path / "cache.json"), native=False + ) + with patch(RAG_PATCH): + rag = make_detector("rag_fact_checker") + assert_golden( + "factory_make_detector", + { + "transformer": _type_name(transformer), + "llm": _type_name(llm), + "rag_fact_checker": _type_name(rag), + }, + ) + + def test_unknown_method_error(self): + """An unknown method raises ValueError with this exact message.""" + with pytest.raises(ValueError) as exc_info: + make_detector("bogus") + assert_golden("factory_unknown_method_error", {"message": str(exc_info.value)}) + + def test_facade_unknown_method_error(self): + """The facade surfaces the same error.""" + with pytest.raises(ValueError) as exc_info: + HallucinationDetector(method="bogus") + assert_golden("facade_unknown_method_error", {"message": str(exc_info.value)}) + + +def _facade_outputs(detector) -> dict: + """Run the three facade entry points with default format and with ``"spans"``.""" + context, answer, question = PREDICT_INPUTS[0] + out = {} + for label, kwargs in (("default", {}), ("spans", {"output_format": "spans"})): + out[label] = { + "predict": detector.predict(context, answer, question, **kwargs), + "predict_prompt": detector.predict_prompt(TRANSFORMER_PROMPTS[0], answer, **kwargs), + "predict_prompt_batch": detector.predict_prompt_batch( + TRANSFORMER_PROMPTS, TRANSFORMER_ANSWERS, **kwargs + ), + } + return out + + +class TestFacade: + """``HallucinationDetector`` returns exactly what the detector alone returns.""" + + def test_transformer(self, local_wordpiece_tokenizer): + """Facade over the stub transformer detector.""" + bare = _build(local_wordpiece_tokenizer, 512) + with _Patched(local_wordpiece_tokenizer): + facade = HallucinationDetector( + method="transformer", model_path="dummy_path", max_length=512 + ) + outputs = _facade_outputs(facade) + assert outputs == _facade_outputs(bare) + assert_golden("facade_transformer", outputs) + + def test_llm(self, tmp_path): + """Facade over the fake-client LLM detector.""" + + def build(name: str) -> LLMDetector: + return LLMDetector( + client=FakeClient(PLAIN), cache_file=str(tmp_path / name), native=False + ) + + facade = HallucinationDetector( + method="llm", + client=FakeClient(PLAIN), + cache_file=str(tmp_path / "f.json"), + native=False, + ) + context, answer, question = CASES[0] + results = {} + for label, kwargs in (("default", {}), ("spans", {"output_format": "spans"})): + args = (context, answer, question) + results[label] = { + "predict": facade.predict(*args, **kwargs), + "predict_prompt": facade.predict_prompt(PROMPTS[0], answer, **kwargs), + "predict_prompt_batch": facade.predict_prompt_batch(PROMPTS, ANSWERS, **kwargs), + } + # LLMDetector alone defaults to "spans", the facade to "tokens": pass the facade's. + bare_kwargs = {"output_format": "tokens", **kwargs} + bare = build(f"b_{label}.json") + assert results[label] == { + "predict": bare.predict(*args, **bare_kwargs), + "predict_prompt": bare.predict_prompt(PROMPTS[0], answer, **bare_kwargs), + "predict_prompt_batch": bare.predict_prompt_batch(PROMPTS, ANSWERS, **bare_kwargs), + } + assert_golden("facade_llm", results) + + def test_rag_fact_checker(self): + """Facade over the RAG detector with a fake fact checker.""" + fake = FakeFactChecker({RAG_ANSWER: _result([["France", "population", "69 million"]])}) + with patch(RAG_PATCH): + facade = HallucinationDetector(method="rag_fact_checker") + facade.detector.rag = fake + results = {} + for fmt in ("tokens", "spans"): + results[fmt] = { + "predict": facade.predict(["c"], RAG_ANSWER, "q", output_format=fmt), + "predict_prompt": facade.predict_prompt("p", RAG_ANSWER, output_format=fmt), + "predict_prompt_batch": facade.predict_prompt_batch( + ["p"], [RAG_ANSWER], output_format=fmt + ), + } + bare = facade.detector + assert results[fmt] == { + "predict": bare.predict(["c"], RAG_ANSWER, "q", output_format=fmt), + "predict_prompt": bare.predict_prompt("p", RAG_ANSWER, output_format=fmt), + "predict_prompt_batch": bare.predict_prompt_batch( + ["p"], [RAG_ANSWER], output_format=fmt + ), + } + assert_golden("facade_rag_fact_checker", results) + + +class TestCacheManager: + """The cache file format and the key strings the LLM detector builds.""" + + def test_file_after_set_and_delete(self, tmp_path): + """The JSON file after a few set and delete calls, byte for byte.""" + path = tmp_path / "nested" / "cache.json" + cache = CacheManager(path) + cache.set("a", {"x": 1, "y": [1, 2]}) + cache.set("b", "héllo ✓") + cache.set("c", None) + cache.delete("a") + cache.delete("missing") + cache.set("b", "overwritten") + raw = path.read_text(encoding="utf-8") + assert json.loads(raw) == {"b": "overwritten", "c": None} + assert CacheManager(path).get("b") == "overwritten" + assert_golden("cache_file_after_set_and_delete", {"raw": raw}) + + def test_hash_strings(self): + """``_hash`` is SHA-256 of the parts joined by ``||``.""" + assert_golden( + "cache_hash_strings", + { + "judge": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0)), + "native": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0), "native"), + "verify": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0), "verify"), + }, + ) + + def test_keys_written_by_llm_detector(self, tmp_path): + """The judge, native and verify keys the detector writes for fixed prompts.""" + answer, prompt = ANSWERS[0], PROMPTS[0] + + judge_file = tmp_path / "judge.json" + judge = LLMDetector( + client=FakeClient(_judge(["69 million", "Paris"], ["Spain"]), _verdicts(["Paris"], [])), + cache_file=str(judge_file), + native=False, + verify=True, + ) + judge.predict_prompt(prompt, answer) + judge_key, verify_key = list(json.loads(judge_file.read_text(encoding="utf-8"))) + assert judge_key == CacheManager._hash( + judge._build_prompt(prompt, answer), judge.model, str(judge.temperature) + ) + + native_file = tmp_path / "native.json" + native = LLMDetector( + client=FakeClient(NATIVE_PLAIN), cache_file=str(native_file), native=True + ) + native.predict_prompt(prompt, answer) + (native_key,) = list(json.loads(native_file.read_text(encoding="utf-8"))) + assert native_key == CacheManager._hash( + gen.SYSTEM_BASE + gen.build_user_message(prompt, answer), + native.model, + str(native.temperature), + "native", + ) + + assert_golden( + "cache_llm_detector_keys", + {"judge": judge_key, "native": native_key, "verify": verify_key}, + ) From 21ed8f3f73ae45d77674fb3dc7ebc305eae600f2 Mon Sep 17 00:00:00 2001 From: hslev Date: Thu, 5 Nov 2026 16:37:21 +0100 Subject: [PATCH 05/60] Revert "test: record golden fixtures for today's detector API (#127)" --- .../cache_file_after_set_and_delete.json | 3 - tests/fixtures/golden/cache_hash_strings.json | 5 - .../golden/cache_llm_detector_keys.json | 5 - tests/fixtures/golden/facade_llm.json | 256 ---------------- .../golden/facade_rag_fact_checker.json | 235 -------------- tests/fixtures/golden/facade_transformer.json | 240 --------------- .../golden/facade_unknown_method_error.json | 3 - .../golden/factory_make_detector.json | 5 - .../golden/factory_unknown_method_error.json | 3 - .../llm_defect_item_not_in_answer_spans.json | 50 --- .../llm_defect_item_not_in_answer_tokens.json | 290 ------------------ ...lm_defect_no_hallucination_list_spans.json | 14 - ...m_defect_no_hallucination_list_tokens.json | 290 ------------------ ..._defect_span_without_confidence_spans.json | 56 ---- ...defect_span_without_confidence_tokens.json | 290 ------------------ .../llm_defect_unparseable_reply_spans.json | 14 - .../llm_defect_unparseable_reply_tokens.json | 290 ------------------ .../golden/llm_include_reasoning_spans.json | 62 ---- .../golden/llm_include_reasoning_tokens.json | 290 ------------------ .../golden/llm_judge_defaults_spans.json | 50 --- .../golden/llm_judge_defaults_tokens.json | 290 ------------------ .../llm_native_include_reasoning_spans.json | 68 ---- .../llm_native_include_reasoning_tokens.json | 290 ------------------ tests/fixtures/golden/llm_native_spans.json | 62 ---- tests/fixtures/golden/llm_native_tokens.json | 290 ------------------ .../golden/llm_taxonomy_flat_dict_spans.json | 56 ---- .../golden/llm_taxonomy_flat_dict_tokens.json | 290 ------------------ .../golden/llm_taxonomy_list_spans.json | 56 ---- .../golden/llm_taxonomy_list_tokens.json | 290 ------------------ .../llm_taxonomy_nested_dict_spans.json | 62 ---- .../llm_taxonomy_nested_dict_tokens.json | 290 ------------------ .../golden/llm_taxonomy_true_spans.json | 62 ---- .../golden/llm_taxonomy_true_tokens.json | 290 ------------------ tests/fixtures/golden/llm_verify_spans.json | 50 --- tests/fixtures/golden/llm_verify_tokens.json | 290 ------------------ .../fixtures/golden/llm_zero_shot_spans.json | 50 --- .../fixtures/golden/llm_zero_shot_tokens.json | 290 ------------------ tests/fixtures/golden/rag_basic_detailed.json | 194 ------------ tests/fixtures/golden/rag_basic_spans.json | 86 ------ tests/fixtures/golden/rag_basic_tokens.json | 290 ------------------ .../golden/rag_batch_detailed_error.json | 3 - ...ap_text_shorter_than_offsets_detailed.json | 110 ------- ...erlap_text_shorter_than_offsets_spans.json | 47 --- ...rlap_text_shorter_than_offsets_tokens.json | 74 ----- .../rag_single_word_match_detailed.json | 104 ------- .../golden/rag_single_word_match_spans.json | 50 --- .../golden/rag_single_word_match_tokens.json | 74 ----- ...transformer_predict_multi_group_spans.json | 42 --- ...ransformer_predict_multi_group_tokens.json | 78 ----- ...ransformer_predict_prompt_batch_spans.json | 44 --- ...ansformer_predict_prompt_batch_tokens.json | 88 ------ .../transformer_predict_prompt_spans.json | 44 --- .../transformer_predict_prompt_tokens.json | 88 ------ .../golden/transformer_predict_spans.json | 44 --- .../golden/transformer_predict_tokens.json | 93 ------ .../golden/transformer_typed_spans.json | 170 ---------- tests/golden.py | 69 ----- tests/test_golden_factory_cache_pytest.py | 261 ---------------- tests/test_golden_llm_pytest.py | 229 -------------- tests/test_golden_rag_fact_checker_pytest.py | 117 ------- tests/test_golden_transformer_pytest.py | 157 ---------- 61 files changed, 8083 deletions(-) delete mode 100644 tests/fixtures/golden/cache_file_after_set_and_delete.json delete mode 100644 tests/fixtures/golden/cache_hash_strings.json delete mode 100644 tests/fixtures/golden/cache_llm_detector_keys.json delete mode 100644 tests/fixtures/golden/facade_llm.json delete mode 100644 tests/fixtures/golden/facade_rag_fact_checker.json delete mode 100644 tests/fixtures/golden/facade_transformer.json delete mode 100644 tests/fixtures/golden/facade_unknown_method_error.json delete mode 100644 tests/fixtures/golden/factory_make_detector.json delete mode 100644 tests/fixtures/golden/factory_unknown_method_error.json delete mode 100644 tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json delete mode 100644 tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json delete mode 100644 tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json delete mode 100644 tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json delete mode 100644 tests/fixtures/golden/llm_defect_span_without_confidence_spans.json delete mode 100644 tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json delete mode 100644 tests/fixtures/golden/llm_defect_unparseable_reply_spans.json delete mode 100644 tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json delete mode 100644 tests/fixtures/golden/llm_include_reasoning_spans.json delete mode 100644 tests/fixtures/golden/llm_include_reasoning_tokens.json delete mode 100644 tests/fixtures/golden/llm_judge_defaults_spans.json delete mode 100644 tests/fixtures/golden/llm_judge_defaults_tokens.json delete mode 100644 tests/fixtures/golden/llm_native_include_reasoning_spans.json delete mode 100644 tests/fixtures/golden/llm_native_include_reasoning_tokens.json delete mode 100644 tests/fixtures/golden/llm_native_spans.json delete mode 100644 tests/fixtures/golden/llm_native_tokens.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_list_spans.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_list_tokens.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_true_spans.json delete mode 100644 tests/fixtures/golden/llm_taxonomy_true_tokens.json delete mode 100644 tests/fixtures/golden/llm_verify_spans.json delete mode 100644 tests/fixtures/golden/llm_verify_tokens.json delete mode 100644 tests/fixtures/golden/llm_zero_shot_spans.json delete mode 100644 tests/fixtures/golden/llm_zero_shot_tokens.json delete mode 100644 tests/fixtures/golden/rag_basic_detailed.json delete mode 100644 tests/fixtures/golden/rag_basic_spans.json delete mode 100644 tests/fixtures/golden/rag_basic_tokens.json delete mode 100644 tests/fixtures/golden/rag_batch_detailed_error.json delete mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json delete mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json delete mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json delete mode 100644 tests/fixtures/golden/rag_single_word_match_detailed.json delete mode 100644 tests/fixtures/golden/rag_single_word_match_spans.json delete mode 100644 tests/fixtures/golden/rag_single_word_match_tokens.json delete mode 100644 tests/fixtures/golden/transformer_predict_multi_group_spans.json delete mode 100644 tests/fixtures/golden/transformer_predict_multi_group_tokens.json delete mode 100644 tests/fixtures/golden/transformer_predict_prompt_batch_spans.json delete mode 100644 tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json delete mode 100644 tests/fixtures/golden/transformer_predict_prompt_spans.json delete mode 100644 tests/fixtures/golden/transformer_predict_prompt_tokens.json delete mode 100644 tests/fixtures/golden/transformer_predict_spans.json delete mode 100644 tests/fixtures/golden/transformer_predict_tokens.json delete mode 100644 tests/fixtures/golden/transformer_typed_spans.json delete mode 100644 tests/golden.py delete mode 100644 tests/test_golden_factory_cache_pytest.py delete mode 100644 tests/test_golden_llm_pytest.py delete mode 100644 tests/test_golden_rag_fact_checker_pytest.py delete mode 100644 tests/test_golden_transformer_pytest.py diff --git a/tests/fixtures/golden/cache_file_after_set_and_delete.json b/tests/fixtures/golden/cache_file_after_set_and_delete.json deleted file mode 100644 index fa650d3..0000000 --- a/tests/fixtures/golden/cache_file_after_set_and_delete.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "raw": "{\"b\": \"overwritten\", \"c\": null}" -} diff --git a/tests/fixtures/golden/cache_hash_strings.json b/tests/fixtures/golden/cache_hash_strings.json deleted file mode 100644 index ef719c5..0000000 --- a/tests/fixtures/golden/cache_hash_strings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "judge": "ec5ac4b1da6900ff9ebd8861dd2cf54e888198c637968b21f8c06823727ac345", - "native": "e0c18fa663979e29c55f3cc592151185e2be4450bb991470130461398abf2a11", - "verify": "bb75fbd052b29efd14c6378bbdbdf3dd18dc6597f898cc8fba01b5bec37f326a" -} diff --git a/tests/fixtures/golden/cache_llm_detector_keys.json b/tests/fixtures/golden/cache_llm_detector_keys.json deleted file mode 100644 index a394236..0000000 --- a/tests/fixtures/golden/cache_llm_detector_keys.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "judge": "95ed92978e40a6929b505d9122f448e52ee2cc795db4f9c82bb6aa76b531d292", - "native": "fd6490df19ee0ae38277af6c46ddfd0eb53662aec83c364b47631b99ec38a726", - "verify": "251bc953856c96dd67d8f76f19d3e8f8292c0098610daf043bfd80f1a622469f" -} diff --git a/tests/fixtures/golden/facade_llm.json b/tests/fixtures/golden/facade_llm.json deleted file mode 100644 index c620c98..0000000 --- a/tests/fixtures/golden/facade_llm.json +++ /dev/null @@ -1,256 +0,0 @@ -{ - "default": { - "predict": [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - "predict_prompt": [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] - }, - "spans": { - "predict": [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - "predict_prompt": [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - "predict_prompt_batch": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] - } -} diff --git a/tests/fixtures/golden/facade_rag_fact_checker.json b/tests/fixtures/golden/facade_rag_fact_checker.json deleted file mode 100644 index 66a078d..0000000 --- a/tests/fixtures/golden/facade_rag_fact_checker.json +++ /dev/null @@ -1,235 +0,0 @@ -{ - "spans": { - "predict": [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - "predict_prompt": [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - "predict_prompt_batch": [ - [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ] - ] - }, - "tokens": { - "predict": [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 1, - "prob": 0.9, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - "predict_prompt": [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 1, - "prob": 0.9, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 1, - "prob": 0.9, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ] - ] - } -} diff --git a/tests/fixtures/golden/facade_transformer.json b/tests/fixtures/golden/facade_transformer.json deleted file mode 100644 index c097c47..0000000 --- a/tests/fixtures/golden/facade_transformer.json +++ /dev/null @@ -1,240 +0,0 @@ -{ - "default": { - "predict": [ - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - "predict_prompt": [ - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 1, - "prob": 0.993307, - "token": "word" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.880797, - "token": "[UNK]" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ] - ] - }, - "spans": { - "predict": [ - { - "confidence": 0.982014, - "end": 11, - "start": 4, - "text": "capital" - }, - { - "confidence": 0.952574, - "end": 24, - "start": 22, - "text": "is" - } - ], - "predict_prompt": [ - { - "confidence": 0.982014, - "end": 11, - "start": 4, - "text": "capital" - }, - { - "confidence": 0.952574, - "end": 24, - "start": 22, - "text": "is" - } - ], - "predict_prompt_batch": [ - [ - { - "confidence": 0.952574, - "end": 8, - "start": 6, - "text": "is" - }, - { - "confidence": 0.982014, - "end": 20, - "start": 13, - "text": "capital" - } - ], - [ - { - "confidence": 0.993307, - "end": 4, - "start": 0, - "text": "word" - } - ], - [ - { - "confidence": 0.982014, - "end": 11, - "start": 4, - "text": "capital" - }, - { - "confidence": 0.952574, - "end": 24, - "start": 22, - "text": "is" - }, - { - "confidence": 0.880797, - "end": 34, - "start": 31, - "text": "and" - } - ] - ] - } -} diff --git a/tests/fixtures/golden/facade_unknown_method_error.json b/tests/fixtures/golden/facade_unknown_method_error.json deleted file mode 100644 index 53c152b..0000000 --- a/tests/fixtures/golden/facade_unknown_method_error.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "message": "Unknown detector method: bogus. Use one of: transformer, llm, rag_fact_checker" -} diff --git a/tests/fixtures/golden/factory_make_detector.json b/tests/fixtures/golden/factory_make_detector.json deleted file mode 100644 index 771cf75..0000000 --- a/tests/fixtures/golden/factory_make_detector.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "llm": "lettucedetect.detectors.llm.LLMDetector", - "rag_fact_checker": "lettucedetect.detectors.rag_fact_checker.RAGFactCheckerDetector", - "transformer": "lettucedetect.detectors.transformer.TransformerDetector" -} diff --git a/tests/fixtures/golden/factory_unknown_method_error.json b/tests/fixtures/golden/factory_unknown_method_error.json deleted file mode 100644 index 53c152b..0000000 --- a/tests/fixtures/golden/factory_unknown_method_error.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "message": "Unknown detector method: bogus. Use one of: transformer, llm, rag_fact_checker" -} diff --git a/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json b/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json deleted file mode 100644 index b9a5255..0000000 --- a/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "predict": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json b/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json b/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json deleted file mode 100644 index 53801cd..0000000 --- a/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "predict": [ - [], - [] - ], - "predict_prompt": [ - [], - [] - ], - "predict_prompt_batch": [ - [], - [] - ] -} diff --git a/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json b/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json deleted file mode 100644 index fbeff16..0000000 --- a/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json b/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json deleted file mode 100644 index 69547a5..0000000 --- a/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "predict": [ - [ - { - "end": 38, - "reasoning": "no score given", - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "reasoning": "no score given", - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "end": 38, - "reasoning": "no score given", - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "reasoning": "no score given", - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "end": 38, - "reasoning": "no score given", - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "reasoning": "no score given", - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json b/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json b/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json deleted file mode 100644 index 53801cd..0000000 --- a/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "predict": [ - [], - [] - ], - "predict_prompt": [ - [], - [] - ], - "predict_prompt_batch": [ - [], - [] - ] -} diff --git a/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json b/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json deleted file mode 100644 index fbeff16..0000000 --- a/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_include_reasoning_spans.json b/tests/fixtures/golden/llm_include_reasoning_spans.json deleted file mode 100644 index 268b5be..0000000 --- a/tests/fixtures/golden/llm_include_reasoning_spans.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "predict": [ - [ - { - "confidence": 0.93, - "end": 38, - "reasoning": "source says 67 million", - "start": 28, - "text": "69 million" - } - ], - [ - { - "confidence": 0.88, - "end": 30, - "reasoning": "source says Portugal", - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "confidence": 0.93, - "end": 38, - "reasoning": "source says 67 million", - "start": 28, - "text": "69 million" - } - ], - [ - { - "confidence": 0.88, - "end": 30, - "reasoning": "source says Portugal", - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "confidence": 0.93, - "end": 38, - "reasoning": "source says 67 million", - "start": 28, - "text": "69 million" - } - ], - [ - { - "confidence": 0.88, - "end": 30, - "reasoning": "source says Portugal", - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_include_reasoning_tokens.json b/tests/fixtures/golden/llm_include_reasoning_tokens.json deleted file mode 100644 index 4205620..0000000 --- a/tests/fixtures/golden/llm_include_reasoning_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.93, - "token": "69" - }, - { - "pred": 1, - "prob": 0.93, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.88, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.93, - "token": "69" - }, - { - "pred": 1, - "prob": 0.93, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.88, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.93, - "token": "69" - }, - { - "pred": 1, - "prob": 0.93, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.88, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_judge_defaults_spans.json b/tests/fixtures/golden/llm_judge_defaults_spans.json deleted file mode 100644 index b9a5255..0000000 --- a/tests/fixtures/golden/llm_judge_defaults_spans.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "predict": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_judge_defaults_tokens.json b/tests/fixtures/golden/llm_judge_defaults_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_judge_defaults_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_native_include_reasoning_spans.json b/tests/fixtures/golden/llm_native_include_reasoning_spans.json deleted file mode 100644 index 06bd954..0000000 --- a/tests/fixtures/golden/llm_native_include_reasoning_spans.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "predict": [ - [ - { - "category": "contradiction", - "end": 38, - "reasoning": "source says 67 million", - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "reasoning": "source says Portugal", - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "contradiction", - "end": 38, - "reasoning": "source says 67 million", - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "reasoning": "source says Portugal", - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "contradiction", - "end": 38, - "reasoning": "source says 67 million", - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "reasoning": "source says Portugal", - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_native_include_reasoning_tokens.json b/tests/fixtures/golden/llm_native_include_reasoning_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_native_include_reasoning_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_native_spans.json b/tests/fixtures/golden/llm_native_spans.json deleted file mode 100644 index 0f9e745..0000000 --- a/tests/fixtures/golden/llm_native_spans.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "predict": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_native_tokens.json b/tests/fixtures/golden/llm_native_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_native_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json b/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json deleted file mode 100644 index 779f88e..0000000 --- a/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "predict": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json b/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_list_spans.json b/tests/fixtures/golden/llm_taxonomy_list_spans.json deleted file mode 100644 index 779f88e..0000000 --- a/tests/fixtures/golden/llm_taxonomy_list_spans.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "predict": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_list_tokens.json b/tests/fixtures/golden/llm_taxonomy_list_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_taxonomy_list_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json b/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json deleted file mode 100644 index 0f9e745..0000000 --- a/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "predict": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json b/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_true_spans.json b/tests/fixtures/golden/llm_taxonomy_true_spans.json deleted file mode 100644 index 0f9e745..0000000 --- a/tests/fixtures/golden/llm_taxonomy_true_spans.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "predict": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "contradiction", - "end": 38, - "start": 28, - "subcategory": "numerical", - "text": "69 million" - } - ], - [ - { - "category": "contradiction", - "end": 30, - "start": 25, - "subcategory": "entity", - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_taxonomy_true_tokens.json b/tests/fixtures/golden/llm_taxonomy_true_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_taxonomy_true_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_verify_spans.json b/tests/fixtures/golden/llm_verify_spans.json deleted file mode 100644 index b9a5255..0000000 --- a/tests/fixtures/golden/llm_verify_spans.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "predict": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_verify_tokens.json b/tests/fixtures/golden/llm_verify_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_verify_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_zero_shot_spans.json b/tests/fixtures/golden/llm_zero_shot_spans.json deleted file mode 100644 index b9a5255..0000000 --- a/tests/fixtures/golden/llm_zero_shot_spans.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "predict": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "end": 38, - "start": 28, - "text": "69 million" - } - ], - [ - { - "end": 30, - "start": 25, - "text": "Spain" - } - ] - ] -} diff --git a/tests/fixtures/golden/llm_zero_shot_tokens.json b/tests/fixtures/golden/llm_zero_shot_tokens.json deleted file mode 100644 index b0bcf54..0000000 --- a/tests/fixtures/golden/llm_zero_shot_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 0, - "prob": 0.1, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 0, - "prob": 0.1, - "token": "Lisbon" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/rag_basic_detailed.json b/tests/fixtures/golden/rag_basic_detailed.json deleted file mode 100644 index 799d091..0000000 --- a/tests/fixtures/golden/rag_basic_detailed.json +++ /dev/null @@ -1,194 +0,0 @@ -{ - "predict": [ - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "France", - "population", - "69 million" - ] - ] - } - }, - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.9, - "end": 30, - "start": 25, - "text": "Spain", - "triplet": [ - "Lisbon", - "capital", - "Spain" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "Lisbon", - "capital", - "Spain" - ] - ] - } - } - ], - "predict_prompt": [ - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "France", - "population", - "69 million" - ] - ] - } - }, - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.9, - "end": 30, - "start": 25, - "text": "Spain", - "triplet": [ - "Lisbon", - "capital", - "Spain" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "Lisbon", - "capital", - "Spain" - ] - ] - } - } - ] -} diff --git a/tests/fixtures/golden/rag_basic_spans.json b/tests/fixtures/golden/rag_basic_spans.json deleted file mode 100644 index 1ec6d7a..0000000 --- a/tests/fixtures/golden/rag_basic_spans.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "predict": [ - [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - [ - { - "confidence": 0.9, - "end": 30, - "start": 25, - "text": "Spain", - "triplet": [ - "Lisbon", - "capital", - "Spain" - ] - } - ] - ], - "predict_prompt": [ - [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - [ - { - "confidence": 0.9, - "end": 30, - "start": 25, - "text": "Spain", - "triplet": [ - "Lisbon", - "capital", - "Spain" - ] - } - ] - ], - "predict_prompt_batch": [ - [ - { - "confidence": 0.9, - "end": 38, - "start": 28, - "text": "69 million", - "triplet": [ - "France", - "population", - "69 million" - ] - } - ], - [ - { - "confidence": 0.9, - "end": 30, - "start": 25, - "text": "Spain", - "triplet": [ - "Lisbon", - "capital", - "Spain" - ] - } - ] - ] -} diff --git a/tests/fixtures/golden/rag_basic_tokens.json b/tests/fixtures/golden/rag_basic_tokens.json deleted file mode 100644 index 5f04941..0000000 --- a/tests/fixtures/golden/rag_basic_tokens.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 1, - "prob": 0.9, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 1, - "prob": 0.9, - "token": "Lisbon" - }, - { - "pred": 1, - "prob": 0.9, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 1, - "prob": 0.9, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 1, - "prob": 0.9, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 1, - "prob": 0.9, - "token": "Lisbon" - }, - { - "pred": 1, - "prob": 0.9, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 1, - "prob": 0.9, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 0, - "prob": 0.1, - "token": "The" - }, - { - "pred": 1, - "prob": 0.9, - "token": "population" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 1, - "prob": 0.9, - "token": "million" - }, - { - "pred": 0, - "prob": 0.1, - "token": "and" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Paris" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "its" - }, - { - "pred": 0, - "prob": 0.1, - "token": "capital." - } - ], - [ - { - "pred": 1, - "prob": 0.9, - "token": "Lisbon" - }, - { - "pred": 1, - "prob": 0.9, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "the" - }, - { - "pred": 1, - "prob": 0.9, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.1, - "token": "of" - }, - { - "pred": 0, - "prob": 0.1, - "token": "Spain." - } - ] - ] -} diff --git a/tests/fixtures/golden/rag_batch_detailed_error.json b/tests/fixtures/golden/rag_batch_detailed_error.json deleted file mode 100644 index af60366..0000000 --- a/tests/fixtures/golden/rag_batch_detailed_error.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "message": "Unknown output format: detailed" -} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json deleted file mode 100644 index 6eadfe1..0000000 --- a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "predict": [ - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.9, - "end": 20, - "start": 0, - "text": "France", - "triplet": [ - "France", - "is", - "unknown" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "France", - "is", - "unknown" - ], - [ - "France", - "is", - "69 million" - ] - ] - } - } - ], - "predict_prompt": [ - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.9, - "end": 20, - "start": 0, - "text": "France", - "triplet": [ - "France", - "is", - "unknown" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "France", - "is", - "unknown" - ], - [ - "France", - "is", - "69 million" - ] - ] - } - } - ] -} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json deleted file mode 100644 index f426b23..0000000 --- a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "predict": [ - [ - { - "confidence": 0.9, - "end": 20, - "start": 0, - "text": "France", - "triplet": [ - "France", - "is", - "unknown" - ] - } - ] - ], - "predict_prompt": [ - [ - { - "confidence": 0.9, - "end": 20, - "start": 0, - "text": "France", - "triplet": [ - "France", - "is", - "unknown" - ] - } - ] - ], - "predict_prompt_batch": [ - [ - { - "confidence": 0.9, - "end": 20, - "start": 0, - "text": "France", - "triplet": [ - "France", - "is", - "unknown" - ] - } - ] - ] -} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json deleted file mode 100644 index eac2e5c..0000000 --- a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 1, - "prob": 0.9, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 1, - "prob": 0.9, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 1, - "prob": 0.9, - "token": "France" - }, - { - "pred": 1, - "prob": 0.9, - "token": "is" - }, - { - "pred": 1, - "prob": 0.9, - "token": "69" - }, - { - "pred": 0, - "prob": 0.1, - "token": "million." - } - ] - ] -} diff --git a/tests/fixtures/golden/rag_single_word_match_detailed.json b/tests/fixtures/golden/rag_single_word_match_detailed.json deleted file mode 100644 index ccb4cf8..0000000 --- a/tests/fixtures/golden/rag_single_word_match_detailed.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "predict": [ - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.7, - "end": 6, - "start": 0, - "text": "Madrid", - "triplet": [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - ] - } - } - ], - "predict_prompt": [ - { - "fact_check_results": { - "0": "contradiction", - "1": "entailment" - }, - "spans": [ - { - "confidence": 0.7, - "end": 6, - "start": 0, - "text": "Madrid", - "triplet": [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - } - ], - "triplets": { - "answer": [ - [ - "France", - "population", - "69 million" - ], - [ - "Paris", - "is", - "capital" - ] - ], - "context": [ - [ - "France", - "population", - "67 million" - ] - ], - "hallucinated": [ - [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - ] - } - } - ] -} diff --git a/tests/fixtures/golden/rag_single_word_match_spans.json b/tests/fixtures/golden/rag_single_word_match_spans.json deleted file mode 100644 index d250e1b..0000000 --- a/tests/fixtures/golden/rag_single_word_match_spans.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "predict": [ - [ - { - "confidence": 0.7, - "end": 6, - "start": 0, - "text": "Madrid", - "triplet": [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - } - ] - ], - "predict_prompt": [ - [ - { - "confidence": 0.7, - "end": 6, - "start": 0, - "text": "Madrid", - "triplet": [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - } - ] - ], - "predict_prompt_batch": [ - [ - { - "confidence": 0.7, - "end": 6, - "start": 0, - "text": "Madrid", - "triplet": [ - "Barcelona", - "north", - "coast", - "Madrid" - ] - } - ] - ] -} diff --git a/tests/fixtures/golden/rag_single_word_match_tokens.json b/tests/fixtures/golden/rag_single_word_match_tokens.json deleted file mode 100644 index 21e7677..0000000 --- a/tests/fixtures/golden/rag_single_word_match_tokens.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "predict": [ - [ - { - "pred": 1, - "prob": 0.9, - "token": "Madrid" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "mentioned" - }, - { - "pred": 0, - "prob": 0.1, - "token": "here." - } - ] - ], - "predict_prompt": [ - [ - { - "pred": 1, - "prob": 0.9, - "token": "Madrid" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "mentioned" - }, - { - "pred": 0, - "prob": 0.1, - "token": "here." - } - ] - ], - "predict_prompt_batch": [ - [ - { - "pred": 1, - "prob": 0.9, - "token": "Madrid" - }, - { - "pred": 0, - "prob": 0.1, - "token": "is" - }, - { - "pred": 0, - "prob": 0.1, - "token": "mentioned" - }, - { - "pred": 0, - "prob": 0.1, - "token": "here." - } - ] - ] -} diff --git a/tests/fixtures/golden/transformer_predict_multi_group_spans.json b/tests/fixtures/golden/transformer_predict_multi_group_spans.json deleted file mode 100644 index 2d1339c..0000000 --- a/tests/fixtures/golden/transformer_predict_multi_group_spans.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "groups": [ - [ - "the capital of france is paris . the capital of france is paris ." - ], - [ - "short answer word . short answer word . short answer word ." - ], - [ - "the capital of france is paris . the capital of france is paris ." - ], - [ - "word word word word word word word word word word word word word word ." - ] - ], - "output": [ - { - "confidence": 0.952574, - "end": 8, - "start": 6, - "text": "is" - }, - { - "confidence": 0.982014, - "end": 23, - "start": 13, - "text": "capital of" - }, - { - "confidence": 0.880797, - "end": 34, - "start": 31, - "text": "and" - }, - { - "confidence": 0.993307, - "end": 53, - "start": 46, - "text": "is word" - } - ] -} diff --git a/tests/fixtures/golden/transformer_predict_multi_group_tokens.json b/tests/fixtures/golden/transformer_predict_multi_group_tokens.json deleted file mode 100644 index 863309d..0000000 --- a/tests/fixtures/golden/transformer_predict_multi_group_tokens.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "groups": [ - [ - "the capital of france is paris . the capital of france is paris ." - ], - [ - "short answer word . short answer word . short answer word ." - ], - [ - "the capital of france is paris . the capital of france is paris ." - ], - [ - "word word word word word word word word word word word word word word ." - ] - ], - "output": [ - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 1, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.880797, - "token": "[UNK]" - }, - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 0, - "prob": 0.119203, - "token": "answer" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "word" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ] -} diff --git a/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json b/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json deleted file mode 100644 index aad175b..0000000 --- a/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json +++ /dev/null @@ -1,44 +0,0 @@ -[ - [ - { - "confidence": 0.952574, - "end": 8, - "start": 6, - "text": "is" - }, - { - "confidence": 0.982014, - "end": 20, - "start": 13, - "text": "capital" - } - ], - [ - { - "confidence": 0.993307, - "end": 4, - "start": 0, - "text": "word" - } - ], - [ - { - "confidence": 0.982014, - "end": 11, - "start": 4, - "text": "capital" - }, - { - "confidence": 0.952574, - "end": 24, - "start": 22, - "text": "is" - }, - { - "confidence": 0.880797, - "end": 34, - "start": 31, - "text": "and" - } - ] -] diff --git a/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json b/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json deleted file mode 100644 index b2d95a5..0000000 --- a/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json +++ /dev/null @@ -1,88 +0,0 @@ -[ - [ - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 1, - "prob": 0.993307, - "token": "word" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.880797, - "token": "[UNK]" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ] -] diff --git a/tests/fixtures/golden/transformer_predict_prompt_spans.json b/tests/fixtures/golden/transformer_predict_prompt_spans.json deleted file mode 100644 index aad175b..0000000 --- a/tests/fixtures/golden/transformer_predict_prompt_spans.json +++ /dev/null @@ -1,44 +0,0 @@ -[ - [ - { - "confidence": 0.952574, - "end": 8, - "start": 6, - "text": "is" - }, - { - "confidence": 0.982014, - "end": 20, - "start": 13, - "text": "capital" - } - ], - [ - { - "confidence": 0.993307, - "end": 4, - "start": 0, - "text": "word" - } - ], - [ - { - "confidence": 0.982014, - "end": 11, - "start": 4, - "text": "capital" - }, - { - "confidence": 0.952574, - "end": 24, - "start": 22, - "text": "is" - }, - { - "confidence": 0.880797, - "end": 34, - "start": 31, - "text": "and" - } - ] -] diff --git a/tests/fixtures/golden/transformer_predict_prompt_tokens.json b/tests/fixtures/golden/transformer_predict_prompt_tokens.json deleted file mode 100644 index b2d95a5..0000000 --- a/tests/fixtures/golden/transformer_predict_prompt_tokens.json +++ /dev/null @@ -1,88 +0,0 @@ -[ - [ - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 1, - "prob": 0.993307, - "token": "word" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.880797, - "token": "[UNK]" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ] -] diff --git a/tests/fixtures/golden/transformer_predict_spans.json b/tests/fixtures/golden/transformer_predict_spans.json deleted file mode 100644 index 065dce4..0000000 --- a/tests/fixtures/golden/transformer_predict_spans.json +++ /dev/null @@ -1,44 +0,0 @@ -[ - [ - { - "confidence": 0.982014, - "end": 11, - "start": 4, - "text": "capital" - }, - { - "confidence": 0.952574, - "end": 24, - "start": 22, - "text": "is" - } - ], - [ - { - "confidence": 0.952574, - "end": 8, - "start": 6, - "text": "is" - }, - { - "confidence": 0.982014, - "end": 20, - "start": 13, - "text": "capital" - } - ], - [ - { - "confidence": 0.993307, - "end": 4, - "start": 0, - "text": "word" - }, - { - "confidence": 0.880797, - "end": 17, - "start": 12, - "text": "short" - } - ] -] diff --git a/tests/fixtures/golden/transformer_predict_tokens.json b/tests/fixtures/golden/transformer_predict_tokens.json deleted file mode 100644 index 6ceceb7..0000000 --- a/tests/fixtures/golden/transformer_predict_tokens.json +++ /dev/null @@ -1,93 +0,0 @@ -[ - [ - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.5, - "token": "of" - }, - { - "pred": 0, - "prob": 0.017986, - "token": "france" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 0, - "prob": 0.268941, - "token": "paris" - }, - { - "pred": 1, - "prob": 0.952574, - "token": "is" - }, - { - "pred": 0, - "prob": 0.047426, - "token": "the" - }, - { - "pred": 1, - "prob": 0.982014, - "token": "capital" - }, - { - "pred": 0, - "prob": 0.006693, - "token": "." - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ], - [ - { - "pred": 1, - "prob": 0.993307, - "token": "word" - }, - { - "pred": 0, - "prob": 0.119203, - "token": "answer" - }, - { - "pred": 1, - "prob": 0.880797, - "token": "short" - }, - { - "pred": 1, - "prob": 0.993307, - "token": "[SEP]" - } - ] -] diff --git a/tests/fixtures/golden/transformer_typed_spans.json b/tests/fixtures/golden/transformer_typed_spans.json deleted file mode 100644 index 52879c4..0000000 --- a/tests/fixtures/golden/transformer_typed_spans.json +++ /dev/null @@ -1,170 +0,0 @@ -{ - "predict": [ - [ - { - "category": "CAT[capital]", - "confidence": 0.982014, - "end": 11, - "start": 4, - "subcategory": "SUB[32]", - "text": "capital" - }, - { - "category": "CAT[is]", - "confidence": 0.952574, - "end": 24, - "start": 22, - "subcategory": "SUB[32]", - "text": "is" - } - ], - [ - { - "category": "CAT[is]", - "confidence": 0.952574, - "end": 8, - "start": 6, - "subcategory": "SUB[32]", - "text": "is" - }, - { - "category": "CAT[capital]", - "confidence": 0.982014, - "end": 20, - "start": 13, - "subcategory": "SUB[32]", - "text": "capital" - } - ], - [ - { - "category": "CAT[word]", - "confidence": 0.993307, - "end": 4, - "start": 0, - "subcategory": "SUB[19]", - "text": "word" - }, - { - "category": "CAT[short]", - "confidence": 0.880797, - "end": 17, - "start": 12, - "subcategory": "SUB[19]", - "text": "short" - } - ] - ], - "predict_prompt": [ - [ - { - "category": "CAT[is]", - "confidence": 0.952574, - "end": 8, - "start": 6, - "subcategory": "SUB[32]", - "text": "is" - }, - { - "category": "CAT[capital]", - "confidence": 0.982014, - "end": 20, - "start": 13, - "subcategory": "SUB[32]", - "text": "capital" - } - ], - [ - { - "category": "CAT[word]", - "confidence": 0.993307, - "end": 4, - "start": 0, - "subcategory": "SUB[17]", - "text": "word" - } - ], - [ - { - "category": "CAT[capital]", - "confidence": 0.982014, - "end": 11, - "start": 4, - "subcategory": "SUB[54]", - "text": "capital" - }, - { - "category": "CAT[is]", - "confidence": 0.952574, - "end": 24, - "start": 22, - "subcategory": "SUB[54]", - "text": "is" - }, - { - "category": "CAT[and]", - "confidence": 0.880797, - "end": 34, - "start": 31, - "subcategory": "SUB[54]", - "text": "and" - } - ] - ], - "predict_prompt_batch": [ - [ - { - "category": "CAT[is]", - "confidence": 0.952574, - "end": 8, - "start": 6, - "subcategory": "SUB[32]", - "text": "is" - }, - { - "category": "CAT[capital]", - "confidence": 0.982014, - "end": 20, - "start": 13, - "subcategory": "SUB[32]", - "text": "capital" - } - ], - [ - { - "category": "CAT[word]", - "confidence": 0.993307, - "end": 4, - "start": 0, - "subcategory": "SUB[17]", - "text": "word" - } - ], - [ - { - "category": "CAT[capital]", - "confidence": 0.982014, - "end": 11, - "start": 4, - "subcategory": "SUB[54]", - "text": "capital" - }, - { - "category": "CAT[is]", - "confidence": 0.952574, - "end": 24, - "start": 22, - "subcategory": "SUB[54]", - "text": "is" - }, - { - "category": "CAT[and]", - "confidence": 0.880797, - "end": 34, - "start": 31, - "subcategory": "SUB[54]", - "text": "and" - } - ] - ] -} diff --git a/tests/golden.py b/tests/golden.py deleted file mode 100644 index fc30bb2..0000000 --- a/tests/golden.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Golden-file helper for characterization tests. - -``assert_golden(name, data)`` compares ``data`` with ``tests/fixtures/golden/.json`` and -fails on any difference, printing a unified diff. Run with ``UPDATE_GOLDEN=1`` to rewrite the -file instead (review the resulting git diff: a changed fixture is an intended behaviour change). - -Floats are rounded to 6 places on both sides before comparing, so cross-platform softmax noise -does not flake the suite while any real change still fails. -""" - -from __future__ import annotations - -import difflib -import json -import os -from pathlib import Path -from typing import Any - -GOLDEN_DIR = Path(__file__).parent / "fixtures" / "golden" -_FLOAT_PLACES = 6 - - -def _normalize(value: Any) -> Any: # noqa: ANN401 - """Round floats and turn tuples into lists, recursively.""" - if isinstance(value, float): - return round(value, _FLOAT_PLACES) - if isinstance(value, dict): - return {str(k): _normalize(v) for k, v in value.items()} - if isinstance(value, (list, tuple)): - return [_normalize(v) for v in value] - return value - - -def _dump(data: Any) -> str: # noqa: ANN401 - return json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False) + "\n" - - -def assert_golden(name: str, data: Any) -> None: # noqa: ANN401 - """Assert that ``data`` equals the checked-in golden file ``.json``. - - :param name: Fixture name, without the ``.json`` suffix. - :param data: JSON-serializable value to compare. - """ - path = GOLDEN_DIR / f"{name}.json" - actual = _dump(_normalize(json.loads(json.dumps(data, ensure_ascii=False)))) - - if os.environ.get("UPDATE_GOLDEN") == "1": - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(actual, encoding="utf-8") - return - - if not path.exists(): - raise AssertionError( - f"Golden file {path} does not exist. Record it with UPDATE_GOLDEN=1 and review it." - ) - expected = _dump(_normalize(json.loads(path.read_text(encoding="utf-8")))) - if actual != expected: - diff = "".join( - difflib.unified_diff( - expected.splitlines(keepends=True), - actual.splitlines(keepends=True), - fromfile=f"golden/{name}.json (checked in)", - tofile=f"golden/{name}.json (actual)", - ) - ) - raise AssertionError( - f"Output differs from golden file {name}.json " - f"(UPDATE_GOLDEN=1 rewrites it if the change is intended):\n{diff}" - ) diff --git a/tests/test_golden_factory_cache_pytest.py b/tests/test_golden_factory_cache_pytest.py deleted file mode 100644 index ef673f2..0000000 --- a/tests/test_golden_factory_cache_pytest.py +++ /dev/null @@ -1,261 +0,0 @@ -"""Golden (characterization) tests for ``make_detector``, ``HallucinationDetector`` and the cache. - -Builds on the stubs of the transformer, LLM and RAG golden tests. Recordings live in -``tests/fixtures/golden/{factory,facade,cache}_*.json``. - -The cache keys must stay byte-identical when a later change adds ``model_version`` and it is -``None``. They are SHA-256 hashes of the full prompt, so they also change whenever a prompt -template or few-shot example file changes, which invalidates users' caches: re-record on purpose. -""" - -from __future__ import annotations - -import json -from unittest.mock import MagicMock, patch - -import pytest - -from lettucedetect.detectors.cache import CacheManager -from lettucedetect.detectors.factory import make_detector -from lettucedetect.detectors.llm import LLMDetector -from lettucedetect.models.inference import HallucinationDetector -from lettucedetect.prompts import generative as gen -from tests.golden import assert_golden -from tests.test_golden_llm_pytest import ( - ANSWERS, - CASES, - NATIVE_PLAIN, - PLAIN, - PROMPTS, - FakeClient, - _judge, - _verdicts, -) -from tests.test_golden_rag_fact_checker_pytest import ANSWER as RAG_ANSWER -from tests.test_golden_rag_fact_checker_pytest import FakeFactChecker, _result -from tests.test_golden_transformer_pytest import ( - ANSWERS as TRANSFORMER_ANSWERS, -) -from tests.test_golden_transformer_pytest import ( - PREDICT_INPUTS, - _build, - _stub_forward, -) -from tests.test_golden_transformer_pytest import ( - PROMPTS as TRANSFORMER_PROMPTS, -) - -TRANSFORMER_PATCH = "lettucedetect.detectors.transformer.{}.from_pretrained" -RAG_PATCH = "lettucedetect.ragfactchecker.RAGFactChecker" - - -def _type_name(obj: object) -> str: - return f"{type(obj).__module__}.{type(obj).__qualname__}" - - -class _Patched: - """Context manager replacing model/tokenizer loading with the local stubs.""" - - def __init__(self, tokenizer) -> None: - self.patches = [ - patch(TRANSFORMER_PATCH.format("AutoTokenizer"), return_value=tokenizer), - patch( - TRANSFORMER_PATCH.format("AutoModelForTokenClassification"), - return_value=MagicMock(side_effect=_stub_forward), - ), - ] - - def __enter__(self) -> None: - for p in self.patches: - p.start() - - def __exit__(self, *exc: object) -> None: - for p in reversed(self.patches): - p.stop() - - -class TestMakeDetector: - """The factory builds the right class per method and rejects unknown ones.""" - - def test_returns_the_right_class_per_method(self, local_wordpiece_tokenizer, tmp_path): - """Each method maps to its detector class (loading replaced by fakes).""" - with _Patched(local_wordpiece_tokenizer): - transformer = make_detector("transformer", model_path="dummy_path", max_length=64) - llm = make_detector( - "llm", client=FakeClient({}), cache_file=str(tmp_path / "cache.json"), native=False - ) - with patch(RAG_PATCH): - rag = make_detector("rag_fact_checker") - assert_golden( - "factory_make_detector", - { - "transformer": _type_name(transformer), - "llm": _type_name(llm), - "rag_fact_checker": _type_name(rag), - }, - ) - - def test_unknown_method_error(self): - """An unknown method raises ValueError with this exact message.""" - with pytest.raises(ValueError) as exc_info: - make_detector("bogus") - assert_golden("factory_unknown_method_error", {"message": str(exc_info.value)}) - - def test_facade_unknown_method_error(self): - """The facade surfaces the same error.""" - with pytest.raises(ValueError) as exc_info: - HallucinationDetector(method="bogus") - assert_golden("facade_unknown_method_error", {"message": str(exc_info.value)}) - - -def _facade_outputs(detector) -> dict: - """Run the three facade entry points with default format and with ``"spans"``.""" - context, answer, question = PREDICT_INPUTS[0] - out = {} - for label, kwargs in (("default", {}), ("spans", {"output_format": "spans"})): - out[label] = { - "predict": detector.predict(context, answer, question, **kwargs), - "predict_prompt": detector.predict_prompt(TRANSFORMER_PROMPTS[0], answer, **kwargs), - "predict_prompt_batch": detector.predict_prompt_batch( - TRANSFORMER_PROMPTS, TRANSFORMER_ANSWERS, **kwargs - ), - } - return out - - -class TestFacade: - """``HallucinationDetector`` returns exactly what the detector alone returns.""" - - def test_transformer(self, local_wordpiece_tokenizer): - """Facade over the stub transformer detector.""" - bare = _build(local_wordpiece_tokenizer, 512) - with _Patched(local_wordpiece_tokenizer): - facade = HallucinationDetector( - method="transformer", model_path="dummy_path", max_length=512 - ) - outputs = _facade_outputs(facade) - assert outputs == _facade_outputs(bare) - assert_golden("facade_transformer", outputs) - - def test_llm(self, tmp_path): - """Facade over the fake-client LLM detector.""" - - def build(name: str) -> LLMDetector: - return LLMDetector( - client=FakeClient(PLAIN), cache_file=str(tmp_path / name), native=False - ) - - facade = HallucinationDetector( - method="llm", - client=FakeClient(PLAIN), - cache_file=str(tmp_path / "f.json"), - native=False, - ) - context, answer, question = CASES[0] - results = {} - for label, kwargs in (("default", {}), ("spans", {"output_format": "spans"})): - args = (context, answer, question) - results[label] = { - "predict": facade.predict(*args, **kwargs), - "predict_prompt": facade.predict_prompt(PROMPTS[0], answer, **kwargs), - "predict_prompt_batch": facade.predict_prompt_batch(PROMPTS, ANSWERS, **kwargs), - } - # LLMDetector alone defaults to "spans", the facade to "tokens": pass the facade's. - bare_kwargs = {"output_format": "tokens", **kwargs} - bare = build(f"b_{label}.json") - assert results[label] == { - "predict": bare.predict(*args, **bare_kwargs), - "predict_prompt": bare.predict_prompt(PROMPTS[0], answer, **bare_kwargs), - "predict_prompt_batch": bare.predict_prompt_batch(PROMPTS, ANSWERS, **bare_kwargs), - } - assert_golden("facade_llm", results) - - def test_rag_fact_checker(self): - """Facade over the RAG detector with a fake fact checker.""" - fake = FakeFactChecker({RAG_ANSWER: _result([["France", "population", "69 million"]])}) - with patch(RAG_PATCH): - facade = HallucinationDetector(method="rag_fact_checker") - facade.detector.rag = fake - results = {} - for fmt in ("tokens", "spans"): - results[fmt] = { - "predict": facade.predict(["c"], RAG_ANSWER, "q", output_format=fmt), - "predict_prompt": facade.predict_prompt("p", RAG_ANSWER, output_format=fmt), - "predict_prompt_batch": facade.predict_prompt_batch( - ["p"], [RAG_ANSWER], output_format=fmt - ), - } - bare = facade.detector - assert results[fmt] == { - "predict": bare.predict(["c"], RAG_ANSWER, "q", output_format=fmt), - "predict_prompt": bare.predict_prompt("p", RAG_ANSWER, output_format=fmt), - "predict_prompt_batch": bare.predict_prompt_batch( - ["p"], [RAG_ANSWER], output_format=fmt - ), - } - assert_golden("facade_rag_fact_checker", results) - - -class TestCacheManager: - """The cache file format and the key strings the LLM detector builds.""" - - def test_file_after_set_and_delete(self, tmp_path): - """The JSON file after a few set and delete calls, byte for byte.""" - path = tmp_path / "nested" / "cache.json" - cache = CacheManager(path) - cache.set("a", {"x": 1, "y": [1, 2]}) - cache.set("b", "héllo ✓") - cache.set("c", None) - cache.delete("a") - cache.delete("missing") - cache.set("b", "overwritten") - raw = path.read_text(encoding="utf-8") - assert json.loads(raw) == {"b": "overwritten", "c": None} - assert CacheManager(path).get("b") == "overwritten" - assert_golden("cache_file_after_set_and_delete", {"raw": raw}) - - def test_hash_strings(self): - """``_hash`` is SHA-256 of the parts joined by ``||``.""" - assert_golden( - "cache_hash_strings", - { - "judge": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0)), - "native": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0), "native"), - "verify": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0), "verify"), - }, - ) - - def test_keys_written_by_llm_detector(self, tmp_path): - """The judge, native and verify keys the detector writes for fixed prompts.""" - answer, prompt = ANSWERS[0], PROMPTS[0] - - judge_file = tmp_path / "judge.json" - judge = LLMDetector( - client=FakeClient(_judge(["69 million", "Paris"], ["Spain"]), _verdicts(["Paris"], [])), - cache_file=str(judge_file), - native=False, - verify=True, - ) - judge.predict_prompt(prompt, answer) - judge_key, verify_key = list(json.loads(judge_file.read_text(encoding="utf-8"))) - assert judge_key == CacheManager._hash( - judge._build_prompt(prompt, answer), judge.model, str(judge.temperature) - ) - - native_file = tmp_path / "native.json" - native = LLMDetector( - client=FakeClient(NATIVE_PLAIN), cache_file=str(native_file), native=True - ) - native.predict_prompt(prompt, answer) - (native_key,) = list(json.loads(native_file.read_text(encoding="utf-8"))) - assert native_key == CacheManager._hash( - gen.SYSTEM_BASE + gen.build_user_message(prompt, answer), - native.model, - str(native.temperature), - "native", - ) - - assert_golden( - "cache_llm_detector_keys", - {"judge": judge_key, "native": native_key, "verify": verify_key}, - ) diff --git a/tests/test_golden_llm_pytest.py b/tests/test_golden_llm_pytest.py deleted file mode 100644 index 46d4893..0000000 --- a/tests/test_golden_llm_pytest.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Golden (characterization) tests pinning today's ``LLMDetector`` output. - -Every configuration runs through a fake ``LLMClient`` that returns fixed replies, so the tests are -network-free and need no API key. Each recording holds ``predict``, ``predict_prompt`` and -``predict_prompt_batch`` output for one configuration and one output format, in -``tests/fixtures/golden/llm__.json``. - -The ``llm_defect_*`` recordings are today's behaviour where the detectors epic changes it (spans -without ``confidence``, unparseable replies returning no spans, items missing from the answer); the -pull request that fixes one updates its fixture as an intended change. -""" - -from __future__ import annotations - -import json - -import pytest - -from lettucedetect.detectors.llm import LLMDetector -from lettucedetect.detectors.llm_client import LLMClient -from tests.golden import assert_golden - -FORMATS = ["tokens", "spans"] - -# (context passages, answer, question); the answers are not substrings of each other, so the fake -# client can tell which reply to give from the request text alone. -CASES = [ - ( - ["France has about 67 million people."], - "The population of France is 69 million and Paris is its capital.", - "What is the population of France?", - ), - (["Lisbon is the capital of Portugal."], "Lisbon is the capital of Spain.", None), -] -ANSWERS = [case[1] for case in CASES] -PROMPTS = ["Source: France has about 67 million people.", "Source: Lisbon is in Portugal."] - -VERIFY_SYSTEM_MARKER = "strict fact-checker" - - -class FakeClient(LLMClient): - """Returns a fixed reply per answer (judge/native) or per answer (verify), no network.""" - - def __init__(self, replies: dict[str, str], verify_replies: dict[str, str] | None = None): - """Store replies keyed by the answer they respond to.""" - self.replies = replies - self.verify_replies = verify_replies or {} - - def complete(self, system, user, model, temperature, schema) -> str: - """Pick the reply of the answer found in ``user``; verification has its own replies.""" - table = self.verify_replies if VERIFY_SYSTEM_MARKER in system else self.replies - for answer, reply in table.items(): - if answer in user: - return reply - raise AssertionError(f"no fixed reply for request: {user[:200]!r}") - - -def _judge(*items_per_answer: list) -> dict[str, str]: - return { - answer: json.dumps({"hallucination_list": items}) - for answer, items in zip(ANSWERS, items_per_answer) - } - - -def _native(*spans_per_answer: list) -> dict[str, str]: - return { - answer: json.dumps({"hallucinated_spans": spans}) - for answer, spans in zip(ANSWERS, spans_per_answer) - } - - -def _verdicts(*rejected_per_answer: list) -> dict[str, str]: - return { - answer: json.dumps( - {"verifications": [{"text": t, "reasoning": "r", "is_hallucination": False} for t in r]} - ) - for answer, r in zip(ANSWERS, rejected_per_answer) - } - - -PLAIN = _judge(["69 million"], ["Spain"]) -REASONED = _judge( - [ - { - "text": "69 million", - "reasoning": "source says 67 million", - "confidence": 0.93, - "is_hallucination": True, - }, - { - "text": "Paris", - "reasoning": "not stated, but harmless", - "confidence": 0.31, - "is_hallucination": False, - }, - ], - [ - { - "text": "Spain", - "reasoning": "source says Portugal", - "confidence": 0.88, - "is_hallucination": True, - } - ], -) -TYPED = _judge( - [{"text": "69 million", "category": "contradiction", "subcategory": "numerical"}], - [{"text": "Spain", "category": "contradiction", "subcategory": "entity"}], -) -TYPED_CATEGORY_ONLY = _judge( - [{"text": "69 million", "category": "contradiction"}], - [{"text": "Spain", "category": "contradiction"}], -) -CUSTOM_CATEGORIES = { - "wrong_number": "A number that differs from the source", - "other": "Anything else", -} -NATIVE_PLAIN = _native( - [{"text": "69 million", "category": "contradiction", "subcategory": "numerical"}], - [{"text": "Spain", "category": "contradiction", "subcategory": "entity"}], -) -NATIVE_EXPLAINED = _native( - [ - { - "text": "69 million", - "category": "contradiction", - "subcategory": "numerical", - "explanation": "source says 67 million", - } - ], - [ - { - "text": "Spain", - "category": "contradiction", - "subcategory": "entity", - "explanation": "source says Portugal", - } - ], -) - -# name -> (constructor kwargs, judge/native replies, verification replies) -CONFIGS = { - "judge_defaults": ({}, PLAIN, None), - "zero_shot": ({"zero_shot": True}, PLAIN, None), - "include_reasoning": ({"include_reasoning": True}, REASONED, None), - "taxonomy_true": ({"include_taxonomy": True}, TYPED, None), - "taxonomy_list": ( - {"include_taxonomy": ["contradiction", "fabricated_reference"]}, - TYPED_CATEGORY_ONLY, - None, - ), - "taxonomy_flat_dict": ({"include_taxonomy": CUSTOM_CATEGORIES}, TYPED_CATEGORY_ONLY, None), - "taxonomy_nested_dict": ( - { - "include_taxonomy": { - "categories": CUSTOM_CATEGORIES, - "subcategories": {"digits": "A wrong digit", "name": "A wrong name"}, - } - }, - TYPED, - None, - ), - "verify": ( - {"verify": True}, - _judge(["69 million", "Paris"], ["Spain"]), - _verdicts(["Paris"], []), - ), - "native": ({"native": True}, NATIVE_PLAIN, None), - "native_include_reasoning": ( - {"native": True, "include_reasoning": True}, - NATIVE_EXPLAINED, - None, - ), - # Defect cases: today's output where later tickets change the behaviour. - "defect_no_hallucination_list": ( - {}, - {answer: json.dumps({"analysis": "nothing to list"}) for answer in ANSWERS}, - None, - ), - "defect_unparseable_reply": ({}, {answer: "not json at all" for answer in ANSWERS}, None), - "defect_item_not_in_answer": ( - {}, - _judge(["Mars", "69 million"], ["Spain", "Madrid"]), - None, - ), - "defect_span_without_confidence": ( - {"include_reasoning": True}, - _judge( - [{"text": "69 million", "reasoning": "no score given"}], - [{"text": "Spain", "reasoning": "no score given"}], - ), - None, - ), -} - - -def _run(name: str, output_format: str, tmp_path) -> dict: - kwargs, replies, verify_replies = CONFIGS[name] - kwargs = {"native": False, **kwargs} - counter = iter(range(100)) - - def detector() -> LLMDetector: - # A fresh cache per entry point, so no entry point is answered from another's cache. - return LLMDetector( - client=FakeClient(replies, verify_replies), - cache_file=str(tmp_path / f"cache_{next(counter)}.json"), - **kwargs, - ) - - return { - "predict": [ - detector().predict(ctx, ans, question, output_format=output_format) - for ctx, ans, question in CASES - ], - "predict_prompt": [ - detector().predict_prompt(prompt, ans, output_format=output_format) - for prompt, ans in zip(PROMPTS, ANSWERS) - ], - "predict_prompt_batch": detector().predict_prompt_batch( - PROMPTS, ANSWERS, output_format=output_format - ), - } - - -@pytest.mark.parametrize("output_format", FORMATS) -@pytest.mark.parametrize("name", list(CONFIGS)) -def test_llm_golden(name, output_format, tmp_path): - """Pin every entry point for one configuration and one output format.""" - assert_golden(f"llm_{name}_{output_format}", _run(name, output_format, tmp_path)) diff --git a/tests/test_golden_rag_fact_checker_pytest.py b/tests/test_golden_rag_fact_checker_pytest.py deleted file mode 100644 index 7c9fa86..0000000 --- a/tests/test_golden_rag_fact_checker_pytest.py +++ /dev/null @@ -1,117 +0,0 @@ -"""Golden (characterization) tests pinning today's ``RAGFactCheckerDetector`` output. - -The detector is built without its constructor (which needs an OpenAI key) and given a fake fact -checker that returns fixed triplets and results, so the tests are network-free. Recordings live in -``tests/fixtures/golden/rag__.json``. - -``rag_merge_overlap_text_shorter_than_offsets_*`` records a defect: ``_merge_overlapping_spans`` -extends ``end`` but keeps the first span's ``text``, so ``text`` is shorter than ``end - start``. -The pull request that fixes it updates exactly those fixtures as an intended change. -""" - -from __future__ import annotations - -import pytest - -from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector -from tests.golden import assert_golden - -ANSWER = "The population of France is 69 million and Paris is its capital." -ANSWER_2 = "Lisbon is the capital of Spain." -ANSWER_3 = "Madrid is mentioned here." -ANSWER_4 = "France is 69 million." - - -def _result(hallucinated: list[list[str]]) -> dict: - return { - "answer_triplets": [["France", "population", "69 million"], ["Paris", "is", "capital"]], - "context_triplets": [["France", "population", "67 million"]], - "hallucinated_triplets": hallucinated, - "fact_check_results": {"0": "contradiction", "1": "entailment"}, - } - - -# case -> [(answer, fact checker result), ...] -CASES = { - "basic": [ - (ANSWER, _result([["France", "population", "69 million"]])), - (ANSWER_2, _result([["Lisbon", "capital", "Spain"]])), - ], - # The fourth element is only found by the single-word fallback, so confidence is 0.7. - "single_word_match": [(ANSWER_3, _result([["Barcelona", "north", "coast", "Madrid"]]))], - # Both triplets match at the same start; merging keeps the first, shorter, text. - "merge_overlap_text_shorter_than_offsets": [ - (ANSWER_4, _result([["France", "is", "unknown"], ["France", "is", "69 million"]])) - ], -} - - -class FakeFactChecker: - """Returns the fixed result recorded for each answer; never touches the network.""" - - def __init__(self, results: dict[str, dict]) -> None: - """Store results keyed by answer.""" - self.results = results - - def detect_hallucinations(self, context, answer, question=None) -> dict: - """Return the fixed result for ``answer``.""" - return self.results[answer] - - def detect_hallucinations_batch(self, contexts, answers) -> list[dict]: - """Return the fixed results for ``answers``, in order.""" - return [self.results[answer] for answer in answers] - - -def _detector(case: str) -> RAGFactCheckerDetector: - detector = RAGFactCheckerDetector.__new__(RAGFactCheckerDetector) # skip the API-key __init__ - detector.rag = FakeFactChecker(dict(CASES[case])) - return detector - - -def _record(case: str, output_format: str) -> dict: - detector = _detector(case) - answers = [answer for answer, _ in CASES[case]] - recording = { - "predict": [ - detector.predict(["context"], answer, "question", output_format=output_format) - for answer in answers - ], - "predict_prompt": [ - detector.predict_prompt("prompt", answer, output_format=output_format) - for answer in answers - ], - } - if output_format != "detailed": # the batch path does not support "detailed" - recording["predict_prompt_batch"] = detector.predict_prompt_batch( - ["prompt"] * len(answers), answers, output_format=output_format - ) - return recording - - -@pytest.mark.parametrize("output_format", ["tokens", "spans", "detailed"]) -@pytest.mark.parametrize("case", list(CASES)) -def test_rag_fact_checker_golden(case, output_format): - """Pin every entry point for one case and one output format.""" - assert_golden(f"rag_{case}_{output_format}", _record(case, output_format)) - - -def test_batch_detailed_is_rejected(): - """Today ``predict_prompt_batch`` raises for ``"detailed"``; the message is recorded.""" - with pytest.raises(ValueError) as exc_info: - _detector("basic").predict_prompt_batch(["p"], [ANSWER], output_format="detailed") - assert_golden("rag_batch_detailed_error", {"message": str(exc_info.value)}) - - -def test_single_word_match_has_lower_confidence(): - """The single-word fallback reports 0.7 instead of 0.9.""" - spans = _detector("single_word_match").predict(["c"], ANSWER_3, output_format="spans") - assert [span["confidence"] for span in spans] == [0.7] - - -def test_merge_leaves_text_shorter_than_offsets(): - """Documents the defect the recording pins: merged ``text`` is shorter than its offsets.""" - spans = _detector("merge_overlap_text_shorter_than_offsets").predict( - ["c"], ANSWER_4, output_format="spans" - ) - assert len(spans) == 1 - assert len(spans[0]["text"]) < spans[0]["end"] - spans[0]["start"] diff --git a/tests/test_golden_transformer_pytest.py b/tests/test_golden_transformer_pytest.py deleted file mode 100644 index 071cde0..0000000 --- a/tests/test_golden_transformer_pytest.py +++ /dev/null @@ -1,157 +0,0 @@ -"""Golden (characterization) tests pinning today's ``TransformerDetector`` output. - -The model is a stub whose logits are a closed-form function of the token id and the tokenizer is -the local WordPiece one from ``conftest.py``, so the tests are deterministic and network-free. -Recorded output lives in ``tests/fixtures/golden/transformer_*.json``. - -Today's quirks are recorded as-is: ``"tokens"`` output ends with the trailing ``[SEP]`` token, and -the multi-group path flags a token at ``prob >= 0.5`` while the single-group path uses argmax. -""" - -from __future__ import annotations - -from unittest.mock import MagicMock, patch - -import pytest -import torch - -from lettucedetect.detectors.transformer import TransformerDetector -from tests.golden import assert_golden - -FORMATS = ["tokens", "spans"] -MULTI_MAX_LENGTH = 90 - -# (context passages, answer, question); question None means summarisation. -PREDICT_INPUTS = [ - ( - ["the capital of france is paris ."], - "the capital of france is paris", - "the capital of france ?", - ), - (["the capital of france is paris ."], "paris is the capital .", None), - (["short answer word ."], "word answer short", "short ?"), -] -PROMPTS = [ - "the capital of france is paris .", - "short answer word", - "the capital of france is paris . the capital of france", -] -ANSWERS = ["paris is the capital", "word", "the capital of france is paris and paris"] - -MULTI_CONTEXT = [ - "the capital of france is paris . the capital of france is paris .", - "short answer word . short answer word . short answer word .", - "the capital of france is paris . the capital of france is paris .", - "word word word word word word word word word word word word word word .", -] -MULTI_QUESTION = "the capital of france ?" -MULTI_ANSWER = "paris is the capital of france and the answer is word" - - -def _stub_forward(input_ids=None, attention_mask=None, **kwargs): - """Logits depend only on the token id: P(hallucination) = sigmoid((id*7) % 11 - 5).""" - score = ((input_ids * 7) % 11 - 5).float() / 2 - logits = torch.stack([-score, score], dim=-1) - output = MagicMock() - output.logits = logits - return output - - -def _build(tokenizer, max_length: int) -> TransformerDetector: - model = MagicMock(side_effect=_stub_forward) - with ( - patch( - "lettucedetect.detectors.transformer.AutoTokenizer.from_pretrained", - return_value=tokenizer, - ), - patch( - "lettucedetect.detectors.transformer.AutoModelForTokenClassification.from_pretrained", - return_value=model, - ), - ): - return TransformerDetector(model_path="dummy_path", max_length=max_length) - - -class _StubTyper: - """Types every span from its own text and the context string it was handed.""" - - def type_spans(self, answer, context, spans): - for span in spans: - span["category"] = f"CAT[{span['text']}]" - span["subcategory"] = f"SUB[{len(context)}]" - return spans - - -@pytest.fixture -def detector(local_wordpiece_tokenizer): - return _build(local_wordpiece_tokenizer, 512) - - -@pytest.fixture -def multi_detector(local_wordpiece_tokenizer): - return _build(local_wordpiece_tokenizer, MULTI_MAX_LENGTH) - - -def _predict_all(det, output_format): - return [det.predict(c, a, q, output_format=output_format) for c, a, q in PREDICT_INPUTS] - - -def _predict_prompt_all(det, output_format): - return [det.predict_prompt(p, a, output_format=output_format) for p, a in zip(PROMPTS, ANSWERS)] - - -def _predict_prompt_batch(det, output_format): - return det.predict_prompt_batch(PROMPTS, ANSWERS, output_format=output_format) - - -@pytest.mark.parametrize("output_format", FORMATS) -class TestTransformerGolden: - """Every public entry point in both output formats.""" - - def test_predict(self, detector, output_format): - """predict() on the small inputs.""" - assert_golden(f"transformer_predict_{output_format}", _predict_all(detector, output_format)) - - def test_predict_prompt(self, detector, output_format): - """predict_prompt() on the small inputs.""" - assert_golden( - f"transformer_predict_prompt_{output_format}", - _predict_prompt_all(detector, output_format), - ) - - def test_predict_prompt_batch(self, detector, output_format): - """predict_prompt_batch() on the small inputs.""" - assert_golden( - f"transformer_predict_prompt_batch_{output_format}", - _predict_prompt_batch(detector, output_format), - ) - - def test_multi_group(self, multi_detector, output_format): - """A context needing several passage groups, aggregated with max().""" - groups = multi_detector._group_passages_into_chunks( - MULTI_CONTEXT, MULTI_QUESTION, MULTI_ANSWER - ) - assert len(groups) > 1, "the multi-group fixture must really need several groups" - output = multi_detector.predict( - MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION, output_format=output_format - ) - assert_golden( - f"transformer_predict_multi_group_{output_format}", - {"groups": groups, "output": output}, - ) - - -class TestTransformerTypedSpansGolden: - """Spans typed by a stub typer.""" - - def test_typed_spans(self, detector): - """The typer sees joined passages in predict and the full prompt elsewhere.""" - detector.typer = _StubTyper() - assert_golden( - "transformer_typed_spans", - { - "predict": _predict_all(detector, "spans"), - "predict_prompt": _predict_prompt_all(detector, "spans"), - "predict_prompt_batch": _predict_prompt_batch(detector, "spans"), - }, - ) From b3199c4f4740f297cc411716922163666df94d32 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:37:21 +0100 Subject: [PATCH 06/60] test: pin today's TransformerDetector output with golden fixtures (#128) Add tests/golden.py (assert_golden, UPDATE_GOLDEN=1 to rewrite, readable unified diff, floats rounded to 6 places) and record predict, predict_prompt and predict_prompt_batch in "tokens" and "spans" format on a stub model with the local tokenizer, plus a multi-group context and spans typed by a stub typer. Recorded as-is: "tokens" output ends with the trailing [SEP], and the multi-group path flags a token at prob >= 0.5 while the single-group path uses argmax. Co-Authored-By: Claude Sonnet 5.5 --- ...transformer_predict_multi_group_spans.json | 42 +++++ ...ransformer_predict_multi_group_tokens.json | 78 ++++++++ ...ransformer_predict_prompt_batch_spans.json | 44 +++++ ...ansformer_predict_prompt_batch_tokens.json | 88 +++++++++ .../transformer_predict_prompt_spans.json | 44 +++++ .../transformer_predict_prompt_tokens.json | 88 +++++++++ .../golden/transformer_predict_spans.json | 44 +++++ .../golden/transformer_predict_tokens.json | 93 ++++++++++ .../golden/transformer_typed_spans.json | 170 ++++++++++++++++++ tests/golden.py | 69 +++++++ tests/test_golden_transformer_pytest.py | 157 ++++++++++++++++ 11 files changed, 917 insertions(+) create mode 100644 tests/fixtures/golden/transformer_predict_multi_group_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_multi_group_tokens.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_batch_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_prompt_tokens.json create mode 100644 tests/fixtures/golden/transformer_predict_spans.json create mode 100644 tests/fixtures/golden/transformer_predict_tokens.json create mode 100644 tests/fixtures/golden/transformer_typed_spans.json create mode 100644 tests/golden.py create mode 100644 tests/test_golden_transformer_pytest.py diff --git a/tests/fixtures/golden/transformer_predict_multi_group_spans.json b/tests/fixtures/golden/transformer_predict_multi_group_spans.json new file mode 100644 index 0000000..2d1339c --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_multi_group_spans.json @@ -0,0 +1,42 @@ +{ + "groups": [ + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "short answer word . short answer word . short answer word ." + ], + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "word word word word word word word word word word word word word word ." + ] + ], + "output": [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 23, + "start": 13, + "text": "capital of" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + }, + { + "confidence": 0.993307, + "end": 53, + "start": 46, + "text": "is word" + } + ] +} diff --git a/tests/fixtures/golden/transformer_predict_multi_group_tokens.json b/tests/fixtures/golden/transformer_predict_multi_group_tokens.json new file mode 100644 index 0000000..863309d --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_multi_group_tokens.json @@ -0,0 +1,78 @@ +{ + "groups": [ + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "short answer word . short answer word . short answer word ." + ], + [ + "the capital of france is paris . the capital of france is paris ." + ], + [ + "word word word word word word word word word word word word word word ." + ] + ], + "output": [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 0, + "prob": 0.119203, + "token": "answer" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +} diff --git a/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json b/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json new file mode 100644 index 0000000..aad175b --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_batch_spans.json @@ -0,0 +1,44 @@ +[ + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + } + ], + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json b/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json new file mode 100644 index 0000000..b2d95a5 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_batch_tokens.json @@ -0,0 +1,88 @@ +[ + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_prompt_spans.json b/tests/fixtures/golden/transformer_predict_prompt_spans.json new file mode 100644 index 0000000..aad175b --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_spans.json @@ -0,0 +1,44 @@ +[ + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + } + ], + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_prompt_tokens.json b/tests/fixtures/golden/transformer_predict_prompt_tokens.json new file mode 100644 index 0000000..b2d95a5 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_prompt_tokens.json @@ -0,0 +1,88 @@ +[ + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_spans.json b/tests/fixtures/golden/transformer_predict_spans.json new file mode 100644 index 0000000..065dce4 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_spans.json @@ -0,0 +1,44 @@ +[ + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + } + ], + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + }, + { + "confidence": 0.880797, + "end": 17, + "start": 12, + "text": "short" + } + ] +] diff --git a/tests/fixtures/golden/transformer_predict_tokens.json b/tests/fixtures/golden/transformer_predict_tokens.json new file mode 100644 index 0000000..6ceceb7 --- /dev/null +++ b/tests/fixtures/golden/transformer_predict_tokens.json @@ -0,0 +1,93 @@ +[ + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.006693, + "token": "." + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 0, + "prob": 0.119203, + "token": "answer" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "short" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] +] diff --git a/tests/fixtures/golden/transformer_typed_spans.json b/tests/fixtures/golden/transformer_typed_spans.json new file mode 100644 index 0000000..52879c4 --- /dev/null +++ b/tests/fixtures/golden/transformer_typed_spans.json @@ -0,0 +1,170 @@ +{ + "predict": [ + [ + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 11, + "start": 4, + "subcategory": "SUB[32]", + "text": "capital" + }, + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 24, + "start": 22, + "subcategory": "SUB[32]", + "text": "is" + } + ], + [ + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 8, + "start": 6, + "subcategory": "SUB[32]", + "text": "is" + }, + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 20, + "start": 13, + "subcategory": "SUB[32]", + "text": "capital" + } + ], + [ + { + "category": "CAT[word]", + "confidence": 0.993307, + "end": 4, + "start": 0, + "subcategory": "SUB[19]", + "text": "word" + }, + { + "category": "CAT[short]", + "confidence": 0.880797, + "end": 17, + "start": 12, + "subcategory": "SUB[19]", + "text": "short" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 8, + "start": 6, + "subcategory": "SUB[32]", + "text": "is" + }, + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 20, + "start": 13, + "subcategory": "SUB[32]", + "text": "capital" + } + ], + [ + { + "category": "CAT[word]", + "confidence": 0.993307, + "end": 4, + "start": 0, + "subcategory": "SUB[17]", + "text": "word" + } + ], + [ + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 11, + "start": 4, + "subcategory": "SUB[54]", + "text": "capital" + }, + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 24, + "start": 22, + "subcategory": "SUB[54]", + "text": "is" + }, + { + "category": "CAT[and]", + "confidence": 0.880797, + "end": 34, + "start": 31, + "subcategory": "SUB[54]", + "text": "and" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 8, + "start": 6, + "subcategory": "SUB[32]", + "text": "is" + }, + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 20, + "start": 13, + "subcategory": "SUB[32]", + "text": "capital" + } + ], + [ + { + "category": "CAT[word]", + "confidence": 0.993307, + "end": 4, + "start": 0, + "subcategory": "SUB[17]", + "text": "word" + } + ], + [ + { + "category": "CAT[capital]", + "confidence": 0.982014, + "end": 11, + "start": 4, + "subcategory": "SUB[54]", + "text": "capital" + }, + { + "category": "CAT[is]", + "confidence": 0.952574, + "end": 24, + "start": 22, + "subcategory": "SUB[54]", + "text": "is" + }, + { + "category": "CAT[and]", + "confidence": 0.880797, + "end": 34, + "start": 31, + "subcategory": "SUB[54]", + "text": "and" + } + ] + ] +} diff --git a/tests/golden.py b/tests/golden.py new file mode 100644 index 0000000..fc30bb2 --- /dev/null +++ b/tests/golden.py @@ -0,0 +1,69 @@ +"""Golden-file helper for characterization tests. + +``assert_golden(name, data)`` compares ``data`` with ``tests/fixtures/golden/.json`` and +fails on any difference, printing a unified diff. Run with ``UPDATE_GOLDEN=1`` to rewrite the +file instead (review the resulting git diff: a changed fixture is an intended behaviour change). + +Floats are rounded to 6 places on both sides before comparing, so cross-platform softmax noise +does not flake the suite while any real change still fails. +""" + +from __future__ import annotations + +import difflib +import json +import os +from pathlib import Path +from typing import Any + +GOLDEN_DIR = Path(__file__).parent / "fixtures" / "golden" +_FLOAT_PLACES = 6 + + +def _normalize(value: Any) -> Any: # noqa: ANN401 + """Round floats and turn tuples into lists, recursively.""" + if isinstance(value, float): + return round(value, _FLOAT_PLACES) + if isinstance(value, dict): + return {str(k): _normalize(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_normalize(v) for v in value] + return value + + +def _dump(data: Any) -> str: # noqa: ANN401 + return json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False) + "\n" + + +def assert_golden(name: str, data: Any) -> None: # noqa: ANN401 + """Assert that ``data`` equals the checked-in golden file ``.json``. + + :param name: Fixture name, without the ``.json`` suffix. + :param data: JSON-serializable value to compare. + """ + path = GOLDEN_DIR / f"{name}.json" + actual = _dump(_normalize(json.loads(json.dumps(data, ensure_ascii=False)))) + + if os.environ.get("UPDATE_GOLDEN") == "1": + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(actual, encoding="utf-8") + return + + if not path.exists(): + raise AssertionError( + f"Golden file {path} does not exist. Record it with UPDATE_GOLDEN=1 and review it." + ) + expected = _dump(_normalize(json.loads(path.read_text(encoding="utf-8")))) + if actual != expected: + diff = "".join( + difflib.unified_diff( + expected.splitlines(keepends=True), + actual.splitlines(keepends=True), + fromfile=f"golden/{name}.json (checked in)", + tofile=f"golden/{name}.json (actual)", + ) + ) + raise AssertionError( + f"Output differs from golden file {name}.json " + f"(UPDATE_GOLDEN=1 rewrites it if the change is intended):\n{diff}" + ) diff --git a/tests/test_golden_transformer_pytest.py b/tests/test_golden_transformer_pytest.py new file mode 100644 index 0000000..071cde0 --- /dev/null +++ b/tests/test_golden_transformer_pytest.py @@ -0,0 +1,157 @@ +"""Golden (characterization) tests pinning today's ``TransformerDetector`` output. + +The model is a stub whose logits are a closed-form function of the token id and the tokenizer is +the local WordPiece one from ``conftest.py``, so the tests are deterministic and network-free. +Recorded output lives in ``tests/fixtures/golden/transformer_*.json``. + +Today's quirks are recorded as-is: ``"tokens"`` output ends with the trailing ``[SEP]`` token, and +the multi-group path flags a token at ``prob >= 0.5`` while the single-group path uses argmax. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors.transformer import TransformerDetector +from tests.golden import assert_golden + +FORMATS = ["tokens", "spans"] +MULTI_MAX_LENGTH = 90 + +# (context passages, answer, question); question None means summarisation. +PREDICT_INPUTS = [ + ( + ["the capital of france is paris ."], + "the capital of france is paris", + "the capital of france ?", + ), + (["the capital of france is paris ."], "paris is the capital .", None), + (["short answer word ."], "word answer short", "short ?"), +] +PROMPTS = [ + "the capital of france is paris .", + "short answer word", + "the capital of france is paris . the capital of france", +] +ANSWERS = ["paris is the capital", "word", "the capital of france is paris and paris"] + +MULTI_CONTEXT = [ + "the capital of france is paris . the capital of france is paris .", + "short answer word . short answer word . short answer word .", + "the capital of france is paris . the capital of france is paris .", + "word word word word word word word word word word word word word word .", +] +MULTI_QUESTION = "the capital of france ?" +MULTI_ANSWER = "paris is the capital of france and the answer is word" + + +def _stub_forward(input_ids=None, attention_mask=None, **kwargs): + """Logits depend only on the token id: P(hallucination) = sigmoid((id*7) % 11 - 5).""" + score = ((input_ids * 7) % 11 - 5).float() / 2 + logits = torch.stack([-score, score], dim=-1) + output = MagicMock() + output.logits = logits + return output + + +def _build(tokenizer, max_length: int) -> TransformerDetector: + model = MagicMock(side_effect=_stub_forward) + with ( + patch( + "lettucedetect.detectors.transformer.AutoTokenizer.from_pretrained", + return_value=tokenizer, + ), + patch( + "lettucedetect.detectors.transformer.AutoModelForTokenClassification.from_pretrained", + return_value=model, + ), + ): + return TransformerDetector(model_path="dummy_path", max_length=max_length) + + +class _StubTyper: + """Types every span from its own text and the context string it was handed.""" + + def type_spans(self, answer, context, spans): + for span in spans: + span["category"] = f"CAT[{span['text']}]" + span["subcategory"] = f"SUB[{len(context)}]" + return spans + + +@pytest.fixture +def detector(local_wordpiece_tokenizer): + return _build(local_wordpiece_tokenizer, 512) + + +@pytest.fixture +def multi_detector(local_wordpiece_tokenizer): + return _build(local_wordpiece_tokenizer, MULTI_MAX_LENGTH) + + +def _predict_all(det, output_format): + return [det.predict(c, a, q, output_format=output_format) for c, a, q in PREDICT_INPUTS] + + +def _predict_prompt_all(det, output_format): + return [det.predict_prompt(p, a, output_format=output_format) for p, a in zip(PROMPTS, ANSWERS)] + + +def _predict_prompt_batch(det, output_format): + return det.predict_prompt_batch(PROMPTS, ANSWERS, output_format=output_format) + + +@pytest.mark.parametrize("output_format", FORMATS) +class TestTransformerGolden: + """Every public entry point in both output formats.""" + + def test_predict(self, detector, output_format): + """predict() on the small inputs.""" + assert_golden(f"transformer_predict_{output_format}", _predict_all(detector, output_format)) + + def test_predict_prompt(self, detector, output_format): + """predict_prompt() on the small inputs.""" + assert_golden( + f"transformer_predict_prompt_{output_format}", + _predict_prompt_all(detector, output_format), + ) + + def test_predict_prompt_batch(self, detector, output_format): + """predict_prompt_batch() on the small inputs.""" + assert_golden( + f"transformer_predict_prompt_batch_{output_format}", + _predict_prompt_batch(detector, output_format), + ) + + def test_multi_group(self, multi_detector, output_format): + """A context needing several passage groups, aggregated with max().""" + groups = multi_detector._group_passages_into_chunks( + MULTI_CONTEXT, MULTI_QUESTION, MULTI_ANSWER + ) + assert len(groups) > 1, "the multi-group fixture must really need several groups" + output = multi_detector.predict( + MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION, output_format=output_format + ) + assert_golden( + f"transformer_predict_multi_group_{output_format}", + {"groups": groups, "output": output}, + ) + + +class TestTransformerTypedSpansGolden: + """Spans typed by a stub typer.""" + + def test_typed_spans(self, detector): + """The typer sees joined passages in predict and the full prompt elsewhere.""" + detector.typer = _StubTyper() + assert_golden( + "transformer_typed_spans", + { + "predict": _predict_all(detector, "spans"), + "predict_prompt": _predict_prompt_all(detector, "spans"), + "predict_prompt_batch": _predict_prompt_batch(detector, "spans"), + }, + ) From f4eb78a682eafead271d4124edb90beaa5f579d6 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:40:03 +0100 Subject: [PATCH 07/60] test: pin today's LLMDetector output with golden fixtures (#129) Record predict, predict_prompt and predict_prompt_batch in "tokens" and "spans" format through a fake LLMClient: the judge with defaults, zero_shot, include_reasoning, each include_taxonomy form (True, list, flat dict, nested dict), verify, and native mode with and without include_reasoning. Also record today's behaviour in the cases the epic changes (llm_defect_*): a reply without hallucination_list, an unparseable reply, an item that is not found in the answer, and spans without confidence. Co-Authored-By: Claude Sonnet 5.5 --- .../llm_defect_item_not_in_answer_spans.json | 50 +++ .../llm_defect_item_not_in_answer_tokens.json | 290 ++++++++++++++++++ ...lm_defect_no_hallucination_list_spans.json | 14 + ...m_defect_no_hallucination_list_tokens.json | 290 ++++++++++++++++++ ..._defect_span_without_confidence_spans.json | 56 ++++ ...defect_span_without_confidence_tokens.json | 290 ++++++++++++++++++ .../llm_defect_unparseable_reply_spans.json | 14 + .../llm_defect_unparseable_reply_tokens.json | 290 ++++++++++++++++++ .../golden/llm_include_reasoning_spans.json | 62 ++++ .../golden/llm_include_reasoning_tokens.json | 290 ++++++++++++++++++ .../golden/llm_judge_defaults_spans.json | 50 +++ .../golden/llm_judge_defaults_tokens.json | 290 ++++++++++++++++++ .../llm_native_include_reasoning_spans.json | 68 ++++ .../llm_native_include_reasoning_tokens.json | 290 ++++++++++++++++++ tests/fixtures/golden/llm_native_spans.json | 62 ++++ tests/fixtures/golden/llm_native_tokens.json | 290 ++++++++++++++++++ .../golden/llm_taxonomy_flat_dict_spans.json | 56 ++++ .../golden/llm_taxonomy_flat_dict_tokens.json | 290 ++++++++++++++++++ .../golden/llm_taxonomy_list_spans.json | 56 ++++ .../golden/llm_taxonomy_list_tokens.json | 290 ++++++++++++++++++ .../llm_taxonomy_nested_dict_spans.json | 62 ++++ .../llm_taxonomy_nested_dict_tokens.json | 290 ++++++++++++++++++ .../golden/llm_taxonomy_true_spans.json | 62 ++++ .../golden/llm_taxonomy_true_tokens.json | 290 ++++++++++++++++++ tests/fixtures/golden/llm_verify_spans.json | 50 +++ tests/fixtures/golden/llm_verify_tokens.json | 290 ++++++++++++++++++ .../fixtures/golden/llm_zero_shot_spans.json | 50 +++ .../fixtures/golden/llm_zero_shot_tokens.json | 290 ++++++++++++++++++ tests/test_golden_llm_pytest.py | 229 ++++++++++++++ 29 files changed, 5001 insertions(+) create mode 100644 tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json create mode 100644 tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json create mode 100644 tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json create mode 100644 tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json create mode 100644 tests/fixtures/golden/llm_defect_span_without_confidence_spans.json create mode 100644 tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json create mode 100644 tests/fixtures/golden/llm_defect_unparseable_reply_spans.json create mode 100644 tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json create mode 100644 tests/fixtures/golden/llm_include_reasoning_spans.json create mode 100644 tests/fixtures/golden/llm_include_reasoning_tokens.json create mode 100644 tests/fixtures/golden/llm_judge_defaults_spans.json create mode 100644 tests/fixtures/golden/llm_judge_defaults_tokens.json create mode 100644 tests/fixtures/golden/llm_native_include_reasoning_spans.json create mode 100644 tests/fixtures/golden/llm_native_include_reasoning_tokens.json create mode 100644 tests/fixtures/golden/llm_native_spans.json create mode 100644 tests/fixtures/golden/llm_native_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_list_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_list_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json create mode 100644 tests/fixtures/golden/llm_taxonomy_true_spans.json create mode 100644 tests/fixtures/golden/llm_taxonomy_true_tokens.json create mode 100644 tests/fixtures/golden/llm_verify_spans.json create mode 100644 tests/fixtures/golden/llm_verify_tokens.json create mode 100644 tests/fixtures/golden/llm_zero_shot_spans.json create mode 100644 tests/fixtures/golden/llm_zero_shot_tokens.json create mode 100644 tests/test_golden_llm_pytest.py diff --git a/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json b/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_item_not_in_answer_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json b/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_item_not_in_answer_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json b/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json new file mode 100644 index 0000000..53801cd --- /dev/null +++ b/tests/fixtures/golden/llm_defect_no_hallucination_list_spans.json @@ -0,0 +1,14 @@ +{ + "predict": [ + [], + [] + ], + "predict_prompt": [ + [], + [] + ], + "predict_prompt_batch": [ + [], + [] + ] +} diff --git a/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json b/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json new file mode 100644 index 0000000..fbeff16 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_no_hallucination_list_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json b/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json new file mode 100644 index 0000000..69547a5 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_span_without_confidence_spans.json @@ -0,0 +1,56 @@ +{ + "predict": [ + [ + { + "end": 38, + "reasoning": "no score given", + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "reasoning": "no score given", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "reasoning": "no score given", + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "reasoning": "no score given", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "reasoning": "no score given", + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "reasoning": "no score given", + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json b/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_span_without_confidence_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json b/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json new file mode 100644 index 0000000..53801cd --- /dev/null +++ b/tests/fixtures/golden/llm_defect_unparseable_reply_spans.json @@ -0,0 +1,14 @@ +{ + "predict": [ + [], + [] + ], + "predict_prompt": [ + [], + [] + ], + "predict_prompt_batch": [ + [], + [] + ] +} diff --git a/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json b/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json new file mode 100644 index 0000000..fbeff16 --- /dev/null +++ b/tests/fixtures/golden/llm_defect_unparseable_reply_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_include_reasoning_spans.json b/tests/fixtures/golden/llm_include_reasoning_spans.json new file mode 100644 index 0000000..268b5be --- /dev/null +++ b/tests/fixtures/golden/llm_include_reasoning_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "confidence": 0.93, + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "text": "69 million" + } + ], + [ + { + "confidence": 0.88, + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.93, + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "text": "69 million" + } + ], + [ + { + "confidence": 0.88, + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.93, + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "text": "69 million" + } + ], + [ + { + "confidence": 0.88, + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_include_reasoning_tokens.json b/tests/fixtures/golden/llm_include_reasoning_tokens.json new file mode 100644 index 0000000..4205620 --- /dev/null +++ b/tests/fixtures/golden/llm_include_reasoning_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.93, + "token": "69" + }, + { + "pred": 1, + "prob": 0.93, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.88, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.93, + "token": "69" + }, + { + "pred": 1, + "prob": 0.93, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.88, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.93, + "token": "69" + }, + { + "pred": 1, + "prob": 0.93, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.88, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_judge_defaults_spans.json b/tests/fixtures/golden/llm_judge_defaults_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_judge_defaults_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_judge_defaults_tokens.json b/tests/fixtures/golden/llm_judge_defaults_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_judge_defaults_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_include_reasoning_spans.json b/tests/fixtures/golden/llm_native_include_reasoning_spans.json new file mode 100644 index 0000000..06bd954 --- /dev/null +++ b/tests/fixtures/golden/llm_native_include_reasoning_spans.json @@ -0,0 +1,68 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "reasoning": "source says 67 million", + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "reasoning": "source says Portugal", + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_include_reasoning_tokens.json b/tests/fixtures/golden/llm_native_include_reasoning_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_native_include_reasoning_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_spans.json b/tests/fixtures/golden/llm_native_spans.json new file mode 100644 index 0000000..0f9e745 --- /dev/null +++ b/tests/fixtures/golden/llm_native_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_native_tokens.json b/tests/fixtures/golden/llm_native_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_native_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json b/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json new file mode 100644 index 0000000..779f88e --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_flat_dict_spans.json @@ -0,0 +1,56 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json b/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_flat_dict_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_list_spans.json b/tests/fixtures/golden/llm_taxonomy_list_spans.json new file mode 100644 index 0000000..779f88e --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_list_spans.json @@ -0,0 +1,56 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_list_tokens.json b/tests/fixtures/golden/llm_taxonomy_list_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_list_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json b/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json new file mode 100644 index 0000000..0f9e745 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_nested_dict_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json b/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_nested_dict_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_true_spans.json b/tests/fixtures/golden/llm_taxonomy_true_spans.json new file mode 100644 index 0000000..0f9e745 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_true_spans.json @@ -0,0 +1,62 @@ +{ + "predict": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "category": "contradiction", + "end": 38, + "start": 28, + "subcategory": "numerical", + "text": "69 million" + } + ], + [ + { + "category": "contradiction", + "end": 30, + "start": 25, + "subcategory": "entity", + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_taxonomy_true_tokens.json b/tests/fixtures/golden/llm_taxonomy_true_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_taxonomy_true_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_verify_spans.json b/tests/fixtures/golden/llm_verify_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_verify_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_verify_tokens.json b/tests/fixtures/golden/llm_verify_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_verify_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_zero_shot_spans.json b/tests/fixtures/golden/llm_zero_shot_spans.json new file mode 100644 index 0000000..b9a5255 --- /dev/null +++ b/tests/fixtures/golden/llm_zero_shot_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] +} diff --git a/tests/fixtures/golden/llm_zero_shot_tokens.json b/tests/fixtures/golden/llm_zero_shot_tokens.json new file mode 100644 index 0000000..b0bcf54 --- /dev/null +++ b/tests/fixtures/golden/llm_zero_shot_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] +} diff --git a/tests/test_golden_llm_pytest.py b/tests/test_golden_llm_pytest.py new file mode 100644 index 0000000..46d4893 --- /dev/null +++ b/tests/test_golden_llm_pytest.py @@ -0,0 +1,229 @@ +"""Golden (characterization) tests pinning today's ``LLMDetector`` output. + +Every configuration runs through a fake ``LLMClient`` that returns fixed replies, so the tests are +network-free and need no API key. Each recording holds ``predict``, ``predict_prompt`` and +``predict_prompt_batch`` output for one configuration and one output format, in +``tests/fixtures/golden/llm__.json``. + +The ``llm_defect_*`` recordings are today's behaviour where the detectors epic changes it (spans +without ``confidence``, unparseable replies returning no spans, items missing from the answer); the +pull request that fixes one updates its fixture as an intended change. +""" + +from __future__ import annotations + +import json + +import pytest + +from lettucedetect.detectors.llm import LLMDetector +from lettucedetect.detectors.llm_client import LLMClient +from tests.golden import assert_golden + +FORMATS = ["tokens", "spans"] + +# (context passages, answer, question); the answers are not substrings of each other, so the fake +# client can tell which reply to give from the request text alone. +CASES = [ + ( + ["France has about 67 million people."], + "The population of France is 69 million and Paris is its capital.", + "What is the population of France?", + ), + (["Lisbon is the capital of Portugal."], "Lisbon is the capital of Spain.", None), +] +ANSWERS = [case[1] for case in CASES] +PROMPTS = ["Source: France has about 67 million people.", "Source: Lisbon is in Portugal."] + +VERIFY_SYSTEM_MARKER = "strict fact-checker" + + +class FakeClient(LLMClient): + """Returns a fixed reply per answer (judge/native) or per answer (verify), no network.""" + + def __init__(self, replies: dict[str, str], verify_replies: dict[str, str] | None = None): + """Store replies keyed by the answer they respond to.""" + self.replies = replies + self.verify_replies = verify_replies or {} + + def complete(self, system, user, model, temperature, schema) -> str: + """Pick the reply of the answer found in ``user``; verification has its own replies.""" + table = self.verify_replies if VERIFY_SYSTEM_MARKER in system else self.replies + for answer, reply in table.items(): + if answer in user: + return reply + raise AssertionError(f"no fixed reply for request: {user[:200]!r}") + + +def _judge(*items_per_answer: list) -> dict[str, str]: + return { + answer: json.dumps({"hallucination_list": items}) + for answer, items in zip(ANSWERS, items_per_answer) + } + + +def _native(*spans_per_answer: list) -> dict[str, str]: + return { + answer: json.dumps({"hallucinated_spans": spans}) + for answer, spans in zip(ANSWERS, spans_per_answer) + } + + +def _verdicts(*rejected_per_answer: list) -> dict[str, str]: + return { + answer: json.dumps( + {"verifications": [{"text": t, "reasoning": "r", "is_hallucination": False} for t in r]} + ) + for answer, r in zip(ANSWERS, rejected_per_answer) + } + + +PLAIN = _judge(["69 million"], ["Spain"]) +REASONED = _judge( + [ + { + "text": "69 million", + "reasoning": "source says 67 million", + "confidence": 0.93, + "is_hallucination": True, + }, + { + "text": "Paris", + "reasoning": "not stated, but harmless", + "confidence": 0.31, + "is_hallucination": False, + }, + ], + [ + { + "text": "Spain", + "reasoning": "source says Portugal", + "confidence": 0.88, + "is_hallucination": True, + } + ], +) +TYPED = _judge( + [{"text": "69 million", "category": "contradiction", "subcategory": "numerical"}], + [{"text": "Spain", "category": "contradiction", "subcategory": "entity"}], +) +TYPED_CATEGORY_ONLY = _judge( + [{"text": "69 million", "category": "contradiction"}], + [{"text": "Spain", "category": "contradiction"}], +) +CUSTOM_CATEGORIES = { + "wrong_number": "A number that differs from the source", + "other": "Anything else", +} +NATIVE_PLAIN = _native( + [{"text": "69 million", "category": "contradiction", "subcategory": "numerical"}], + [{"text": "Spain", "category": "contradiction", "subcategory": "entity"}], +) +NATIVE_EXPLAINED = _native( + [ + { + "text": "69 million", + "category": "contradiction", + "subcategory": "numerical", + "explanation": "source says 67 million", + } + ], + [ + { + "text": "Spain", + "category": "contradiction", + "subcategory": "entity", + "explanation": "source says Portugal", + } + ], +) + +# name -> (constructor kwargs, judge/native replies, verification replies) +CONFIGS = { + "judge_defaults": ({}, PLAIN, None), + "zero_shot": ({"zero_shot": True}, PLAIN, None), + "include_reasoning": ({"include_reasoning": True}, REASONED, None), + "taxonomy_true": ({"include_taxonomy": True}, TYPED, None), + "taxonomy_list": ( + {"include_taxonomy": ["contradiction", "fabricated_reference"]}, + TYPED_CATEGORY_ONLY, + None, + ), + "taxonomy_flat_dict": ({"include_taxonomy": CUSTOM_CATEGORIES}, TYPED_CATEGORY_ONLY, None), + "taxonomy_nested_dict": ( + { + "include_taxonomy": { + "categories": CUSTOM_CATEGORIES, + "subcategories": {"digits": "A wrong digit", "name": "A wrong name"}, + } + }, + TYPED, + None, + ), + "verify": ( + {"verify": True}, + _judge(["69 million", "Paris"], ["Spain"]), + _verdicts(["Paris"], []), + ), + "native": ({"native": True}, NATIVE_PLAIN, None), + "native_include_reasoning": ( + {"native": True, "include_reasoning": True}, + NATIVE_EXPLAINED, + None, + ), + # Defect cases: today's output where later tickets change the behaviour. + "defect_no_hallucination_list": ( + {}, + {answer: json.dumps({"analysis": "nothing to list"}) for answer in ANSWERS}, + None, + ), + "defect_unparseable_reply": ({}, {answer: "not json at all" for answer in ANSWERS}, None), + "defect_item_not_in_answer": ( + {}, + _judge(["Mars", "69 million"], ["Spain", "Madrid"]), + None, + ), + "defect_span_without_confidence": ( + {"include_reasoning": True}, + _judge( + [{"text": "69 million", "reasoning": "no score given"}], + [{"text": "Spain", "reasoning": "no score given"}], + ), + None, + ), +} + + +def _run(name: str, output_format: str, tmp_path) -> dict: + kwargs, replies, verify_replies = CONFIGS[name] + kwargs = {"native": False, **kwargs} + counter = iter(range(100)) + + def detector() -> LLMDetector: + # A fresh cache per entry point, so no entry point is answered from another's cache. + return LLMDetector( + client=FakeClient(replies, verify_replies), + cache_file=str(tmp_path / f"cache_{next(counter)}.json"), + **kwargs, + ) + + return { + "predict": [ + detector().predict(ctx, ans, question, output_format=output_format) + for ctx, ans, question in CASES + ], + "predict_prompt": [ + detector().predict_prompt(prompt, ans, output_format=output_format) + for prompt, ans in zip(PROMPTS, ANSWERS) + ], + "predict_prompt_batch": detector().predict_prompt_batch( + PROMPTS, ANSWERS, output_format=output_format + ), + } + + +@pytest.mark.parametrize("output_format", FORMATS) +@pytest.mark.parametrize("name", list(CONFIGS)) +def test_llm_golden(name, output_format, tmp_path): + """Pin every entry point for one configuration and one output format.""" + assert_golden(f"llm_{name}_{output_format}", _run(name, output_format, tmp_path)) From 9e72c66b1632387835e9e21d96fd5e9e97fffcb8 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:41:47 +0100 Subject: [PATCH 08/60] test: pin today's RAGFactCheckerDetector output with golden fixtures (#130) Record "tokens", "spans" and "detailed" output of predict, predict_prompt and predict_prompt_batch through a fake fact checker, a triplet matched only by the single-word fallback (confidence 0.7), and the merge defect where a merged span's text is shorter than its offsets (rag_merge_overlap_text_shorter_than_offsets_*, for the fix PR to update). Co-Authored-By: Claude Sonnet 5.5 --- tests/fixtures/golden/rag_basic_detailed.json | 194 ++++++++++++ tests/fixtures/golden/rag_basic_spans.json | 86 ++++++ tests/fixtures/golden/rag_basic_tokens.json | 290 ++++++++++++++++++ .../golden/rag_batch_detailed_error.json | 3 + ...ap_text_shorter_than_offsets_detailed.json | 110 +++++++ ...erlap_text_shorter_than_offsets_spans.json | 47 +++ ...rlap_text_shorter_than_offsets_tokens.json | 74 +++++ .../rag_single_word_match_detailed.json | 104 +++++++ .../golden/rag_single_word_match_spans.json | 50 +++ .../golden/rag_single_word_match_tokens.json | 74 +++++ tests/test_golden_rag_fact_checker_pytest.py | 117 +++++++ 11 files changed, 1149 insertions(+) create mode 100644 tests/fixtures/golden/rag_basic_detailed.json create mode 100644 tests/fixtures/golden/rag_basic_spans.json create mode 100644 tests/fixtures/golden/rag_basic_tokens.json create mode 100644 tests/fixtures/golden/rag_batch_detailed_error.json create mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json create mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json create mode 100644 tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json create mode 100644 tests/fixtures/golden/rag_single_word_match_detailed.json create mode 100644 tests/fixtures/golden/rag_single_word_match_spans.json create mode 100644 tests/fixtures/golden/rag_single_word_match_tokens.json create mode 100644 tests/test_golden_rag_fact_checker_pytest.py diff --git a/tests/fixtures/golden/rag_basic_detailed.json b/tests/fixtures/golden/rag_basic_detailed.json new file mode 100644 index 0000000..799d091 --- /dev/null +++ b/tests/fixtures/golden/rag_basic_detailed.json @@ -0,0 +1,194 @@ +{ + "predict": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "population", + "69 million" + ] + ] + } + }, + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Lisbon", + "capital", + "Spain" + ] + ] + } + } + ], + "predict_prompt": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "population", + "69 million" + ] + ] + } + }, + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Lisbon", + "capital", + "Spain" + ] + ] + } + } + ] +} diff --git a/tests/fixtures/golden/rag_basic_spans.json b/tests/fixtures/golden/rag_basic_spans.json new file mode 100644 index 0000000..1ec6d7a --- /dev/null +++ b/tests/fixtures/golden/rag_basic_spans.json @@ -0,0 +1,86 @@ +{ + "predict": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + [ + { + "confidence": 0.9, + "end": 30, + "start": 25, + "text": "Spain", + "triplet": [ + "Lisbon", + "capital", + "Spain" + ] + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_basic_tokens.json b/tests/fixtures/golden/rag_basic_tokens.json new file mode 100644 index 0000000..5f04941 --- /dev/null +++ b/tests/fixtures/golden/rag_basic_tokens.json @@ -0,0 +1,290 @@ +{ + "predict": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 1, + "prob": 0.9, + "token": "Lisbon" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 1, + "prob": 0.9, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 1, + "prob": 0.9, + "token": "Lisbon" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 1, + "prob": 0.9, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 1, + "prob": 0.9, + "token": "Lisbon" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 1, + "prob": 0.9, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Spain." + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_batch_detailed_error.json b/tests/fixtures/golden/rag_batch_detailed_error.json new file mode 100644 index 0000000..af60366 --- /dev/null +++ b/tests/fixtures/golden/rag_batch_detailed_error.json @@ -0,0 +1,3 @@ +{ + "message": "Unknown output format: detailed" +} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json new file mode 100644 index 0000000..6eadfe1 --- /dev/null +++ b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json @@ -0,0 +1,110 @@ +{ + "predict": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "is", + "unknown" + ], + [ + "France", + "is", + "69 million" + ] + ] + } + } + ], + "predict_prompt": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "France", + "is", + "unknown" + ], + [ + "France", + "is", + "69 million" + ] + ] + } + } + ] +} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json new file mode 100644 index 0000000..f426b23 --- /dev/null +++ b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json @@ -0,0 +1,47 @@ +{ + "predict": [ + [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.9, + "end": 20, + "start": 0, + "text": "France", + "triplet": [ + "France", + "is", + "unknown" + ] + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json new file mode 100644 index 0000000..eac2e5c --- /dev/null +++ b/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json @@ -0,0 +1,74 @@ +{ + "predict": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 1, + "prob": 0.9, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 0, + "prob": 0.1, + "token": "million." + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_single_word_match_detailed.json b/tests/fixtures/golden/rag_single_word_match_detailed.json new file mode 100644 index 0000000..ccb4cf8 --- /dev/null +++ b/tests/fixtures/golden/rag_single_word_match_detailed.json @@ -0,0 +1,104 @@ +{ + "predict": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + ] + } + } + ], + "predict_prompt": [ + { + "fact_check_results": { + "0": "contradiction", + "1": "entailment" + }, + "spans": [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ], + "triplets": { + "answer": [ + [ + "France", + "population", + "69 million" + ], + [ + "Paris", + "is", + "capital" + ] + ], + "context": [ + [ + "France", + "population", + "67 million" + ] + ], + "hallucinated": [ + [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + ] + } + } + ] +} diff --git a/tests/fixtures/golden/rag_single_word_match_spans.json b/tests/fixtures/golden/rag_single_word_match_spans.json new file mode 100644 index 0000000..d250e1b --- /dev/null +++ b/tests/fixtures/golden/rag_single_word_match_spans.json @@ -0,0 +1,50 @@ +{ + "predict": [ + [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ] + ], + "predict_prompt": [ + [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ] + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.7, + "end": 6, + "start": 0, + "text": "Madrid", + "triplet": [ + "Barcelona", + "north", + "coast", + "Madrid" + ] + } + ] + ] +} diff --git a/tests/fixtures/golden/rag_single_word_match_tokens.json b/tests/fixtures/golden/rag_single_word_match_tokens.json new file mode 100644 index 0000000..21e7677 --- /dev/null +++ b/tests/fixtures/golden/rag_single_word_match_tokens.json @@ -0,0 +1,74 @@ +{ + "predict": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "Madrid" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "mentioned" + }, + { + "pred": 0, + "prob": 0.1, + "token": "here." + } + ] + ], + "predict_prompt": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "Madrid" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "mentioned" + }, + { + "pred": 0, + "prob": 0.1, + "token": "here." + } + ] + ], + "predict_prompt_batch": [ + [ + { + "pred": 1, + "prob": 0.9, + "token": "Madrid" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "mentioned" + }, + { + "pred": 0, + "prob": 0.1, + "token": "here." + } + ] + ] +} diff --git a/tests/test_golden_rag_fact_checker_pytest.py b/tests/test_golden_rag_fact_checker_pytest.py new file mode 100644 index 0000000..7c9fa86 --- /dev/null +++ b/tests/test_golden_rag_fact_checker_pytest.py @@ -0,0 +1,117 @@ +"""Golden (characterization) tests pinning today's ``RAGFactCheckerDetector`` output. + +The detector is built without its constructor (which needs an OpenAI key) and given a fake fact +checker that returns fixed triplets and results, so the tests are network-free. Recordings live in +``tests/fixtures/golden/rag__.json``. + +``rag_merge_overlap_text_shorter_than_offsets_*`` records a defect: ``_merge_overlapping_spans`` +extends ``end`` but keeps the first span's ``text``, so ``text`` is shorter than ``end - start``. +The pull request that fixes it updates exactly those fixtures as an intended change. +""" + +from __future__ import annotations + +import pytest + +from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector +from tests.golden import assert_golden + +ANSWER = "The population of France is 69 million and Paris is its capital." +ANSWER_2 = "Lisbon is the capital of Spain." +ANSWER_3 = "Madrid is mentioned here." +ANSWER_4 = "France is 69 million." + + +def _result(hallucinated: list[list[str]]) -> dict: + return { + "answer_triplets": [["France", "population", "69 million"], ["Paris", "is", "capital"]], + "context_triplets": [["France", "population", "67 million"]], + "hallucinated_triplets": hallucinated, + "fact_check_results": {"0": "contradiction", "1": "entailment"}, + } + + +# case -> [(answer, fact checker result), ...] +CASES = { + "basic": [ + (ANSWER, _result([["France", "population", "69 million"]])), + (ANSWER_2, _result([["Lisbon", "capital", "Spain"]])), + ], + # The fourth element is only found by the single-word fallback, so confidence is 0.7. + "single_word_match": [(ANSWER_3, _result([["Barcelona", "north", "coast", "Madrid"]]))], + # Both triplets match at the same start; merging keeps the first, shorter, text. + "merge_overlap_text_shorter_than_offsets": [ + (ANSWER_4, _result([["France", "is", "unknown"], ["France", "is", "69 million"]])) + ], +} + + +class FakeFactChecker: + """Returns the fixed result recorded for each answer; never touches the network.""" + + def __init__(self, results: dict[str, dict]) -> None: + """Store results keyed by answer.""" + self.results = results + + def detect_hallucinations(self, context, answer, question=None) -> dict: + """Return the fixed result for ``answer``.""" + return self.results[answer] + + def detect_hallucinations_batch(self, contexts, answers) -> list[dict]: + """Return the fixed results for ``answers``, in order.""" + return [self.results[answer] for answer in answers] + + +def _detector(case: str) -> RAGFactCheckerDetector: + detector = RAGFactCheckerDetector.__new__(RAGFactCheckerDetector) # skip the API-key __init__ + detector.rag = FakeFactChecker(dict(CASES[case])) + return detector + + +def _record(case: str, output_format: str) -> dict: + detector = _detector(case) + answers = [answer for answer, _ in CASES[case]] + recording = { + "predict": [ + detector.predict(["context"], answer, "question", output_format=output_format) + for answer in answers + ], + "predict_prompt": [ + detector.predict_prompt("prompt", answer, output_format=output_format) + for answer in answers + ], + } + if output_format != "detailed": # the batch path does not support "detailed" + recording["predict_prompt_batch"] = detector.predict_prompt_batch( + ["prompt"] * len(answers), answers, output_format=output_format + ) + return recording + + +@pytest.mark.parametrize("output_format", ["tokens", "spans", "detailed"]) +@pytest.mark.parametrize("case", list(CASES)) +def test_rag_fact_checker_golden(case, output_format): + """Pin every entry point for one case and one output format.""" + assert_golden(f"rag_{case}_{output_format}", _record(case, output_format)) + + +def test_batch_detailed_is_rejected(): + """Today ``predict_prompt_batch`` raises for ``"detailed"``; the message is recorded.""" + with pytest.raises(ValueError) as exc_info: + _detector("basic").predict_prompt_batch(["p"], [ANSWER], output_format="detailed") + assert_golden("rag_batch_detailed_error", {"message": str(exc_info.value)}) + + +def test_single_word_match_has_lower_confidence(): + """The single-word fallback reports 0.7 instead of 0.9.""" + spans = _detector("single_word_match").predict(["c"], ANSWER_3, output_format="spans") + assert [span["confidence"] for span in spans] == [0.7] + + +def test_merge_leaves_text_shorter_than_offsets(): + """Documents the defect the recording pins: merged ``text`` is shorter than its offsets.""" + spans = _detector("merge_overlap_text_shorter_than_offsets").predict( + ["c"], ANSWER_4, output_format="spans" + ) + assert len(spans) == 1 + assert len(spans[0]["text"]) < spans[0]["end"] - spans[0]["start"] From ca5c2a63708486277660c7825b9804e461286d6e Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 15:43:26 +0100 Subject: [PATCH 09/60] test: pin make_detector, HallucinationDetector and CacheManager behavior (#131) Record the class make_detector returns for "transformer", "llm" and "rag_fact_checker" and the error for an unknown method; assert and record that HallucinationDetector.predict, predict_prompt and predict_prompt_batch return what the detector alone returns (transformer, LLM, RAG); and pin the CacheManager file after set/delete calls, the _hash strings, and the judge, native and verify keys LLMDetector writes for fixed prompts. Co-Authored-By: Claude Sonnet 5.5 --- .../cache_file_after_set_and_delete.json | 3 + tests/fixtures/golden/cache_hash_strings.json | 5 + .../golden/cache_llm_detector_keys.json | 5 + tests/fixtures/golden/facade_llm.json | 256 +++++++++++++++++ .../golden/facade_rag_fact_checker.json | 235 ++++++++++++++++ tests/fixtures/golden/facade_transformer.json | 240 ++++++++++++++++ .../golden/facade_unknown_method_error.json | 3 + .../golden/factory_make_detector.json | 5 + .../golden/factory_unknown_method_error.json | 3 + tests/test_golden_factory_cache_pytest.py | 261 ++++++++++++++++++ 10 files changed, 1016 insertions(+) create mode 100644 tests/fixtures/golden/cache_file_after_set_and_delete.json create mode 100644 tests/fixtures/golden/cache_hash_strings.json create mode 100644 tests/fixtures/golden/cache_llm_detector_keys.json create mode 100644 tests/fixtures/golden/facade_llm.json create mode 100644 tests/fixtures/golden/facade_rag_fact_checker.json create mode 100644 tests/fixtures/golden/facade_transformer.json create mode 100644 tests/fixtures/golden/facade_unknown_method_error.json create mode 100644 tests/fixtures/golden/factory_make_detector.json create mode 100644 tests/fixtures/golden/factory_unknown_method_error.json create mode 100644 tests/test_golden_factory_cache_pytest.py diff --git a/tests/fixtures/golden/cache_file_after_set_and_delete.json b/tests/fixtures/golden/cache_file_after_set_and_delete.json new file mode 100644 index 0000000..fa650d3 --- /dev/null +++ b/tests/fixtures/golden/cache_file_after_set_and_delete.json @@ -0,0 +1,3 @@ +{ + "raw": "{\"b\": \"overwritten\", \"c\": null}" +} diff --git a/tests/fixtures/golden/cache_hash_strings.json b/tests/fixtures/golden/cache_hash_strings.json new file mode 100644 index 0000000..ef719c5 --- /dev/null +++ b/tests/fixtures/golden/cache_hash_strings.json @@ -0,0 +1,5 @@ +{ + "judge": "ec5ac4b1da6900ff9ebd8861dd2cf54e888198c637968b21f8c06823727ac345", + "native": "e0c18fa663979e29c55f3cc592151185e2be4450bb991470130461398abf2a11", + "verify": "bb75fbd052b29efd14c6378bbdbdf3dd18dc6597f898cc8fba01b5bec37f326a" +} diff --git a/tests/fixtures/golden/cache_llm_detector_keys.json b/tests/fixtures/golden/cache_llm_detector_keys.json new file mode 100644 index 0000000..a394236 --- /dev/null +++ b/tests/fixtures/golden/cache_llm_detector_keys.json @@ -0,0 +1,5 @@ +{ + "judge": "95ed92978e40a6929b505d9122f448e52ee2cc795db4f9c82bb6aa76b531d292", + "native": "fd6490df19ee0ae38277af6c46ddfd0eb53662aec83c364b47631b99ec38a726", + "verify": "251bc953856c96dd67d8f76f19d3e8f8292c0098610daf043bfd80f1a622469f" +} diff --git a/tests/fixtures/golden/facade_llm.json b/tests/fixtures/golden/facade_llm.json new file mode 100644 index 0000000..c620c98 --- /dev/null +++ b/tests/fixtures/golden/facade_llm.json @@ -0,0 +1,256 @@ +{ + "default": { + "predict": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 0, + "prob": 0.1, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 0, + "prob": 0.1, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + [ + { + "pred": 0, + "prob": 0.1, + "token": "Lisbon" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "the" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "Spain." + } + ] + ] + }, + "spans": { + "predict": [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + "predict_prompt": [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + "predict_prompt_batch": [ + [ + { + "end": 38, + "start": 28, + "text": "69 million" + } + ], + [ + { + "end": 30, + "start": 25, + "text": "Spain" + } + ] + ] + } +} diff --git a/tests/fixtures/golden/facade_rag_fact_checker.json b/tests/fixtures/golden/facade_rag_fact_checker.json new file mode 100644 index 0000000..66a078d --- /dev/null +++ b/tests/fixtures/golden/facade_rag_fact_checker.json @@ -0,0 +1,235 @@ +{ + "spans": { + "predict": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "predict_prompt": [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.9, + "end": 38, + "start": 28, + "text": "69 million", + "triplet": [ + "France", + "population", + "69 million" + ] + } + ] + ] + }, + "tokens": { + "predict": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt": [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.1, + "token": "The" + }, + { + "pred": 1, + "prob": 0.9, + "token": "population" + }, + { + "pred": 0, + "prob": 0.1, + "token": "of" + }, + { + "pred": 1, + "prob": 0.9, + "token": "France" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 1, + "prob": 0.9, + "token": "69" + }, + { + "pred": 1, + "prob": 0.9, + "token": "million" + }, + { + "pred": 0, + "prob": 0.1, + "token": "and" + }, + { + "pred": 0, + "prob": 0.1, + "token": "Paris" + }, + { + "pred": 0, + "prob": 0.1, + "token": "is" + }, + { + "pred": 0, + "prob": 0.1, + "token": "its" + }, + { + "pred": 0, + "prob": 0.1, + "token": "capital." + } + ] + ] + } +} diff --git a/tests/fixtures/golden/facade_transformer.json b/tests/fixtures/golden/facade_transformer.json new file mode 100644 index 0000000..c097c47 --- /dev/null +++ b/tests/fixtures/golden/facade_transformer.json @@ -0,0 +1,240 @@ +{ + "default": { + "predict": [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + "predict_prompt": [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + "predict_prompt_batch": [ + [ + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 1, + "prob": 0.993307, + "token": "word" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ], + [ + { + "pred": 0, + "prob": 0.047426, + "token": "the" + }, + { + "pred": 1, + "prob": 0.982014, + "token": "capital" + }, + { + "pred": 0, + "prob": 0.5, + "token": "of" + }, + { + "pred": 0, + "prob": 0.017986, + "token": "france" + }, + { + "pred": 1, + "prob": 0.952574, + "token": "is" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.880797, + "token": "[UNK]" + }, + { + "pred": 0, + "prob": 0.268941, + "token": "paris" + }, + { + "pred": 1, + "prob": 0.993307, + "token": "[SEP]" + } + ] + ] + }, + "spans": { + "predict": [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + } + ], + "predict_prompt": [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + } + ], + "predict_prompt_batch": [ + [ + { + "confidence": 0.952574, + "end": 8, + "start": 6, + "text": "is" + }, + { + "confidence": 0.982014, + "end": 20, + "start": 13, + "text": "capital" + } + ], + [ + { + "confidence": 0.993307, + "end": 4, + "start": 0, + "text": "word" + } + ], + [ + { + "confidence": 0.982014, + "end": 11, + "start": 4, + "text": "capital" + }, + { + "confidence": 0.952574, + "end": 24, + "start": 22, + "text": "is" + }, + { + "confidence": 0.880797, + "end": 34, + "start": 31, + "text": "and" + } + ] + ] + } +} diff --git a/tests/fixtures/golden/facade_unknown_method_error.json b/tests/fixtures/golden/facade_unknown_method_error.json new file mode 100644 index 0000000..53c152b --- /dev/null +++ b/tests/fixtures/golden/facade_unknown_method_error.json @@ -0,0 +1,3 @@ +{ + "message": "Unknown detector method: bogus. Use one of: transformer, llm, rag_fact_checker" +} diff --git a/tests/fixtures/golden/factory_make_detector.json b/tests/fixtures/golden/factory_make_detector.json new file mode 100644 index 0000000..771cf75 --- /dev/null +++ b/tests/fixtures/golden/factory_make_detector.json @@ -0,0 +1,5 @@ +{ + "llm": "lettucedetect.detectors.llm.LLMDetector", + "rag_fact_checker": "lettucedetect.detectors.rag_fact_checker.RAGFactCheckerDetector", + "transformer": "lettucedetect.detectors.transformer.TransformerDetector" +} diff --git a/tests/fixtures/golden/factory_unknown_method_error.json b/tests/fixtures/golden/factory_unknown_method_error.json new file mode 100644 index 0000000..53c152b --- /dev/null +++ b/tests/fixtures/golden/factory_unknown_method_error.json @@ -0,0 +1,3 @@ +{ + "message": "Unknown detector method: bogus. Use one of: transformer, llm, rag_fact_checker" +} diff --git a/tests/test_golden_factory_cache_pytest.py b/tests/test_golden_factory_cache_pytest.py new file mode 100644 index 0000000..ef673f2 --- /dev/null +++ b/tests/test_golden_factory_cache_pytest.py @@ -0,0 +1,261 @@ +"""Golden (characterization) tests for ``make_detector``, ``HallucinationDetector`` and the cache. + +Builds on the stubs of the transformer, LLM and RAG golden tests. Recordings live in +``tests/fixtures/golden/{factory,facade,cache}_*.json``. + +The cache keys must stay byte-identical when a later change adds ``model_version`` and it is +``None``. They are SHA-256 hashes of the full prompt, so they also change whenever a prompt +template or few-shot example file changes, which invalidates users' caches: re-record on purpose. +""" + +from __future__ import annotations + +import json +from unittest.mock import MagicMock, patch + +import pytest + +from lettucedetect.detectors.cache import CacheManager +from lettucedetect.detectors.factory import make_detector +from lettucedetect.detectors.llm import LLMDetector +from lettucedetect.models.inference import HallucinationDetector +from lettucedetect.prompts import generative as gen +from tests.golden import assert_golden +from tests.test_golden_llm_pytest import ( + ANSWERS, + CASES, + NATIVE_PLAIN, + PLAIN, + PROMPTS, + FakeClient, + _judge, + _verdicts, +) +from tests.test_golden_rag_fact_checker_pytest import ANSWER as RAG_ANSWER +from tests.test_golden_rag_fact_checker_pytest import FakeFactChecker, _result +from tests.test_golden_transformer_pytest import ( + ANSWERS as TRANSFORMER_ANSWERS, +) +from tests.test_golden_transformer_pytest import ( + PREDICT_INPUTS, + _build, + _stub_forward, +) +from tests.test_golden_transformer_pytest import ( + PROMPTS as TRANSFORMER_PROMPTS, +) + +TRANSFORMER_PATCH = "lettucedetect.detectors.transformer.{}.from_pretrained" +RAG_PATCH = "lettucedetect.ragfactchecker.RAGFactChecker" + + +def _type_name(obj: object) -> str: + return f"{type(obj).__module__}.{type(obj).__qualname__}" + + +class _Patched: + """Context manager replacing model/tokenizer loading with the local stubs.""" + + def __init__(self, tokenizer) -> None: + self.patches = [ + patch(TRANSFORMER_PATCH.format("AutoTokenizer"), return_value=tokenizer), + patch( + TRANSFORMER_PATCH.format("AutoModelForTokenClassification"), + return_value=MagicMock(side_effect=_stub_forward), + ), + ] + + def __enter__(self) -> None: + for p in self.patches: + p.start() + + def __exit__(self, *exc: object) -> None: + for p in reversed(self.patches): + p.stop() + + +class TestMakeDetector: + """The factory builds the right class per method and rejects unknown ones.""" + + def test_returns_the_right_class_per_method(self, local_wordpiece_tokenizer, tmp_path): + """Each method maps to its detector class (loading replaced by fakes).""" + with _Patched(local_wordpiece_tokenizer): + transformer = make_detector("transformer", model_path="dummy_path", max_length=64) + llm = make_detector( + "llm", client=FakeClient({}), cache_file=str(tmp_path / "cache.json"), native=False + ) + with patch(RAG_PATCH): + rag = make_detector("rag_fact_checker") + assert_golden( + "factory_make_detector", + { + "transformer": _type_name(transformer), + "llm": _type_name(llm), + "rag_fact_checker": _type_name(rag), + }, + ) + + def test_unknown_method_error(self): + """An unknown method raises ValueError with this exact message.""" + with pytest.raises(ValueError) as exc_info: + make_detector("bogus") + assert_golden("factory_unknown_method_error", {"message": str(exc_info.value)}) + + def test_facade_unknown_method_error(self): + """The facade surfaces the same error.""" + with pytest.raises(ValueError) as exc_info: + HallucinationDetector(method="bogus") + assert_golden("facade_unknown_method_error", {"message": str(exc_info.value)}) + + +def _facade_outputs(detector) -> dict: + """Run the three facade entry points with default format and with ``"spans"``.""" + context, answer, question = PREDICT_INPUTS[0] + out = {} + for label, kwargs in (("default", {}), ("spans", {"output_format": "spans"})): + out[label] = { + "predict": detector.predict(context, answer, question, **kwargs), + "predict_prompt": detector.predict_prompt(TRANSFORMER_PROMPTS[0], answer, **kwargs), + "predict_prompt_batch": detector.predict_prompt_batch( + TRANSFORMER_PROMPTS, TRANSFORMER_ANSWERS, **kwargs + ), + } + return out + + +class TestFacade: + """``HallucinationDetector`` returns exactly what the detector alone returns.""" + + def test_transformer(self, local_wordpiece_tokenizer): + """Facade over the stub transformer detector.""" + bare = _build(local_wordpiece_tokenizer, 512) + with _Patched(local_wordpiece_tokenizer): + facade = HallucinationDetector( + method="transformer", model_path="dummy_path", max_length=512 + ) + outputs = _facade_outputs(facade) + assert outputs == _facade_outputs(bare) + assert_golden("facade_transformer", outputs) + + def test_llm(self, tmp_path): + """Facade over the fake-client LLM detector.""" + + def build(name: str) -> LLMDetector: + return LLMDetector( + client=FakeClient(PLAIN), cache_file=str(tmp_path / name), native=False + ) + + facade = HallucinationDetector( + method="llm", + client=FakeClient(PLAIN), + cache_file=str(tmp_path / "f.json"), + native=False, + ) + context, answer, question = CASES[0] + results = {} + for label, kwargs in (("default", {}), ("spans", {"output_format": "spans"})): + args = (context, answer, question) + results[label] = { + "predict": facade.predict(*args, **kwargs), + "predict_prompt": facade.predict_prompt(PROMPTS[0], answer, **kwargs), + "predict_prompt_batch": facade.predict_prompt_batch(PROMPTS, ANSWERS, **kwargs), + } + # LLMDetector alone defaults to "spans", the facade to "tokens": pass the facade's. + bare_kwargs = {"output_format": "tokens", **kwargs} + bare = build(f"b_{label}.json") + assert results[label] == { + "predict": bare.predict(*args, **bare_kwargs), + "predict_prompt": bare.predict_prompt(PROMPTS[0], answer, **bare_kwargs), + "predict_prompt_batch": bare.predict_prompt_batch(PROMPTS, ANSWERS, **bare_kwargs), + } + assert_golden("facade_llm", results) + + def test_rag_fact_checker(self): + """Facade over the RAG detector with a fake fact checker.""" + fake = FakeFactChecker({RAG_ANSWER: _result([["France", "population", "69 million"]])}) + with patch(RAG_PATCH): + facade = HallucinationDetector(method="rag_fact_checker") + facade.detector.rag = fake + results = {} + for fmt in ("tokens", "spans"): + results[fmt] = { + "predict": facade.predict(["c"], RAG_ANSWER, "q", output_format=fmt), + "predict_prompt": facade.predict_prompt("p", RAG_ANSWER, output_format=fmt), + "predict_prompt_batch": facade.predict_prompt_batch( + ["p"], [RAG_ANSWER], output_format=fmt + ), + } + bare = facade.detector + assert results[fmt] == { + "predict": bare.predict(["c"], RAG_ANSWER, "q", output_format=fmt), + "predict_prompt": bare.predict_prompt("p", RAG_ANSWER, output_format=fmt), + "predict_prompt_batch": bare.predict_prompt_batch( + ["p"], [RAG_ANSWER], output_format=fmt + ), + } + assert_golden("facade_rag_fact_checker", results) + + +class TestCacheManager: + """The cache file format and the key strings the LLM detector builds.""" + + def test_file_after_set_and_delete(self, tmp_path): + """The JSON file after a few set and delete calls, byte for byte.""" + path = tmp_path / "nested" / "cache.json" + cache = CacheManager(path) + cache.set("a", {"x": 1, "y": [1, 2]}) + cache.set("b", "héllo ✓") + cache.set("c", None) + cache.delete("a") + cache.delete("missing") + cache.set("b", "overwritten") + raw = path.read_text(encoding="utf-8") + assert json.loads(raw) == {"b": "overwritten", "c": None} + assert CacheManager(path).get("b") == "overwritten" + assert_golden("cache_file_after_set_and_delete", {"raw": raw}) + + def test_hash_strings(self): + """``_hash`` is SHA-256 of the parts joined by ``||``.""" + assert_golden( + "cache_hash_strings", + { + "judge": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0)), + "native": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0), "native"), + "verify": CacheManager._hash("prompt", "gpt-4.1-mini", str(0.0), "verify"), + }, + ) + + def test_keys_written_by_llm_detector(self, tmp_path): + """The judge, native and verify keys the detector writes for fixed prompts.""" + answer, prompt = ANSWERS[0], PROMPTS[0] + + judge_file = tmp_path / "judge.json" + judge = LLMDetector( + client=FakeClient(_judge(["69 million", "Paris"], ["Spain"]), _verdicts(["Paris"], [])), + cache_file=str(judge_file), + native=False, + verify=True, + ) + judge.predict_prompt(prompt, answer) + judge_key, verify_key = list(json.loads(judge_file.read_text(encoding="utf-8"))) + assert judge_key == CacheManager._hash( + judge._build_prompt(prompt, answer), judge.model, str(judge.temperature) + ) + + native_file = tmp_path / "native.json" + native = LLMDetector( + client=FakeClient(NATIVE_PLAIN), cache_file=str(native_file), native=True + ) + native.predict_prompt(prompt, answer) + (native_key,) = list(json.loads(native_file.read_text(encoding="utf-8"))) + assert native_key == CacheManager._hash( + gen.SYSTEM_BASE + gen.build_user_message(prompt, answer), + native.model, + str(native.temperature), + "native", + ) + + assert_golden( + "cache_llm_detector_keys", + {"judge": judge_key, "native": native_key, "verify": verify_key}, + ) From d3cf892483a332c0101c520008b9d4bf35f11d7c Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Thu, 5 Nov 2026 17:18:40 +0100 Subject: [PATCH 10/60] docs: state the error handling and logging rules --- CONTRIBUTING.md | 68 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef36a0a..3c0b544 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -45,14 +45,72 @@ ruff check --fix lettucedetect/ lettucedetect_api/ tests/ Key conventions: - Use modern type hints (`list[str]`, `dict[str, Any]`, `str | None`) with `from __future__ import annotations` - Add docstrings to public classes and methods (Sphinx `:param:` / `:return:` style) -- Use `logging` instead of `print()` for runtime messages +- Use `logging` instead of `print()` for runtime messages in library code (see [Errors and logging](#errors-and-logging) for what counts as library code) - Use `pathlib.Path` instead of `os.path` +## Errors and logging + +This convention is adapted from the one in +[VerbatimRAG's contributor guide](https://github.com/KRLabsOrg/verbatim-rag/tree/stateless_core?tab=contributing-ov-file), +so both projects behave the same way. + +### Where it applies + +Library code in `lettucedetect/` follows every rule below. The command-line entry point +(`lettucedetect/cli.py`), `lettucedetect_api/`, `scripts/`, `demo/`, and training and evaluation code +are applications: they configure logging themselves and may print. + +### Errors + +- **Correct result or raise.** A call either returns a correct result or raises. If a result is + correct but degraded (for example, a fallback was used), it says so in its `warnings`. A result that + looks complete while part of the work failed is a bug. +- **Error class depends on where the bad value came from:** + - `InvalidInputError` for an argument of a call. Set `param` to the argument's name. + - `ConfigurationError` for a constructor argument, a setting, an environment problem or a missing + package. + - `UpstreamError` for a failed or missing reply from a service (an LLM API, a model download). + - Bugs in our own code (`KeyError`, `TypeError`, ...) propagate unwrapped. +- **Stable codes.** Every error and every result warning has a snake_case `code` + (for example `empty_context`). Codes are public API: don't rename or reuse them. +- **Messages** name the problem and the fix. They never contain secrets or customer text (context, + question, answer, model replies). Refer to items by position, such as `spans[3]`. +- **Log or raise, never both.** Whoever handles the error decides whether to log it. +- **Translate foreign errors** into one of the classes above and chain them with `raise ... from exc`. +- **No bare `except Exception`** outside application boundaries or code we don't control. Where it is + needed, add a comment saying why. +- **Fallbacks** catch only `UpstreamError` and add a documented warning code to the result. They never + mask `ConfigurationError`, `InvalidInputError` or bugs. +- **`warnings.warn` is only for deprecations**, and uses `LettuceDetectDeprecationWarning`. The test + suite treats that class as an error, so add each new deprecation to the catalogue in + `tests/test_deprecation.py`. + +### Logging + +- **One logger per module:** `logger = logging.getLogger(__name__)`. +- **Library code never prints, shows progress bars, adds handlers or calls `logging.basicConfig`.** + Applications do that. +- **Use %-style arguments**, not f-strings: `logger.info("loaded %s in %.1fs", name, secs)`. Keep each + message on one line. +- **Events.** Key events carry `extra={"event": ""}`. The names are `model_loaded`, + `fallback_used` and `item_failed`. +- **Levels:** + + | Level | Use for | + |---|---| + | DEBUG | the steps of a call | + | INFO | events of healthy operation (`model_loaded`) | + | WARNING | a degraded result (`fallback_used`, `item_failed`) | + | ERROR | only where the exception can't reach a caller | + +- **Customer text** (context, question, answer, model replies) is logged only on the + `lettucedetect.content` logger, and only at DEBUG. Module loggers record counts and positions instead. + ## Running tests ```bash # Run the complete network-free unit suite -python -m pytest +python -m pytest # or: uv run pytest ``` Test files must follow the naming pattern `test_*_pytest.py`. @@ -87,14 +145,16 @@ scripts/ # Training, evaluation, and utility scripts 2. **Make your changes.** Keep PRs focused — one feature or fix per PR. -3. **Run lint and tests** before committing: +3. **Follow [Errors and logging](#errors-and-logging)** for every error you raise and every message you log. + +4. **Run lint and tests** before committing: ```bash ruff format lettucedetect/ lettucedetect_api/ tests/ ruff check lettucedetect/ lettucedetect_api/ tests/ python -m pytest ``` -4. **Open a pull request** against `main`. CI will run lint and tests automatically. +5. **Open a pull request** against `main`. CI will run lint and tests automatically. ## What to work on From 7bb73826f057a01a326dd9083dc87a7fdfaa8064 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 10:14:31 +0100 Subject: [PATCH 11/60] chore: add LettuceDetectDeprecationWarning and a deprecation helper (#135) --- lettucedetect/detectors/__init__.py | 2 + lettucedetect/detectors/_deprecation.py | 135 +++++++++++++++++++++ pyproject.toml | 1 + tests/test_deprecation_pytest.py | 149 ++++++++++++++++++++++++ 4 files changed, 287 insertions(+) create mode 100644 lettucedetect/detectors/_deprecation.py create mode 100644 tests/test_deprecation_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index 86e1189..a419663 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -1,5 +1,6 @@ from __future__ import annotations +from lettucedetect.detectors._deprecation import LettuceDetectDeprecationWarning from lettucedetect.detectors.base import BaseDetector from lettucedetect.detectors.factory import make_detector as _make_detector from lettucedetect.detectors.llm import LLMDetector @@ -9,6 +10,7 @@ __all__ = [ "BaseDetector", "LLMDetector", + "LettuceDetectDeprecationWarning", "RAGFactCheckerDetector", "TransformerDetector", "_make_detector", diff --git a/lettucedetect/detectors/_deprecation.py b/lettucedetect/detectors/_deprecation.py new file mode 100644 index 0000000..b162a25 --- /dev/null +++ b/lettucedetect/detectors/_deprecation.py @@ -0,0 +1,135 @@ +"""One consistent deprecation mechanism for the public API. + +Deprecated names warn with :class:`LettuceDetectDeprecationWarning`, carry a +``__deprecated__`` attribute (PEP 702). +Calls made from inside ``lettucedetect`` itself stay silent. + +Type checkers (ty, pyright, editors) only mark a name as deprecated when its +decorator resolves to ``typing_extensions.deprecated``. So ``deprecated`` is that +class as far as they can tell (see the ``TYPE_CHECKING`` block below) and our own +implementation at runtime. Use it as one decorator; the argument is the +replacement, which checkers show as the deprecation message:: + + @deprecated("HallucinationDetector") + def make_detector(...): ... + +Convention for whoever deprecates a name: also add a ``.. deprecated::`` note +(replacement and removal version) to its docstring. +""" + +# ruff: noqa: ANN401 +from __future__ import annotations + +import functools +import inspect +import sys +import warnings +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, LiteralString, TypeVar, cast + +from typing_extensions import deprecated as _deprecated + +DEPRECATED_SINCE = "0.3.0" +# The release that removes the deprecated API: the 0.3.x and 0.4.x releases warn first. +# Every warning reads both versions from here. +REMOVED_IN = "0.5.0" + +_T = TypeVar("_T") + + +class _Unset: + """Sentinel for a deprecated argument the caller did not pass.""" + + def __repr__(self) -> str: + return "" + + +_UNSET: Any = _Unset() + + +class LettuceDetectDeprecationWarning(DeprecationWarning): + """Emitted when a deprecated LettuceDetect name or argument is used.""" + + +def _message(name: str, replacement: str) -> str: + return ( + f"{name} is deprecated since {DEPRECATED_SINCE} and will be removed in " + f"{REMOVED_IN}. Use {replacement}." + ) + + +def _is_internal(module_name: str | None) -> bool: + return module_name == "lettucedetect" or (module_name or "").startswith("lettucedetect.") + + +def _warn(message: str, frame_depth: int) -> None: + """Warn unless the frame ``frame_depth`` levels above this function is internal. + + ``frame_depth=1`` means this function's caller; the warning is attributed to + that same frame, so ``stacklevel`` equals ``frame_depth``. + """ + caller_module = sys._getframe(frame_depth).f_globals.get("__name__") + if _is_internal(caller_module): + return + warnings.warn(message, LettuceDetectDeprecationWarning, stacklevel=frame_depth + 1) + + +def _deprecated_with_convention(replacement: str) -> Callable[[_T], _T]: + """Apply the standard ``deprecated`` decorator with our message and category. + + It adds the one thing the standard decorator lacks: calls from inside + ``lettucedetect`` stay silent. + """ + + def decorate(target: _T) -> _T: + obj: Any = target + message = _message(getattr(obj, "__qualname__", repr(obj)), replacement) + # stacklevel=2: one extra frame, our guard, sits between the caller and the warning. + mark = _deprecated( + cast(LiteralString, message), category=LettuceDetectDeprecationWarning, stacklevel=2 + ) + + if inspect.isclass(obj): + original_new = obj.__new__ + marked = mark(obj) + warning_new = marked.__new__ + + def new(cls: Any, *args: Any, **kwargs: Any) -> Any: + if _is_internal(sys._getframe(1).f_globals.get("__name__")): + if original_new is object.__new__: + return original_new(cls) + return original_new(cls, *args, **kwargs) + return warning_new(cls, *args, **kwargs) + + marked.__new__ = staticmethod(new) + return cast(_T, marked) + + marked = mark(obj) + + @functools.wraps(obj) + def guard(*args: Any, **kwargs: Any) -> Any: + if _is_internal(sys._getframe(1).f_globals.get("__name__")): + return obj(*args, **kwargs) + return marked(*args, **kwargs) + + setattr(guard, "__deprecated__", message) + return cast(_T, guard) + + return decorate + + +if TYPE_CHECKING: + from typing_extensions import deprecated +else: + deprecated = _deprecated_with_convention + + +def warn_if_passed(value: object, name: str, replacement: str) -> None: + """Warn that argument ``name`` is deprecated if the caller passed it. + + Give the argument a default of ``_UNSET`` and call this from the function + body; the warning is attributed to the line that called that function. + """ + if value is _UNSET: + return + _warn(_message(f"The {name!r} argument", replacement), 3) diff --git a/pyproject.toml b/pyproject.toml index 196cefc..396be46 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ dependencies = [ "numpy>=2.2.2", "openai>=1.66.3", "rag-fact-checker", + "typing_extensions>=4.5.0", ] [project.scripts] diff --git a/tests/test_deprecation_pytest.py b/tests/test_deprecation_pytest.py new file mode 100644 index 0000000..7b31574 --- /dev/null +++ b/tests/test_deprecation_pytest.py @@ -0,0 +1,149 @@ +"""Tests for the deprecation helper, using stand-ins defined here.""" + +from __future__ import annotations + +import subprocess +import sys +import warnings + +import pytest + +from lettucedetect.detectors import LettuceDetectDeprecationWarning +from lettucedetect.detectors import _deprecation as dep +from lettucedetect.detectors._deprecation import _UNSET, deprecated, warn_if_passed + + +def expected(name: str, replacement: str) -> str: + """Build the exact warning message from the module constants.""" + return ( + f"{name} is deprecated since {dep.DEPRECATED_SINCE} and will be removed in " + f"{dep.REMOVED_IN}. Use {replacement}." + ) + + +@deprecated("new_func") +def old_func(x: int = 1) -> int: + """Do a thing.""" + return x + + +@deprecated("NewClass") +class OldClass: + """A class.""" + + def __init__(self, v: int = 0) -> None: # noqa: D107 + self.v = v + + +class Holder: + """Stand-in.""" + + @deprecated("Holder.new") + def old(self) -> str: + """Old.""" + return "ok" + + +def with_arg(a: int, legacy: object = _UNSET) -> int: + """Stand-in function with a deprecated ``legacy`` argument.""" + warn_if_passed(legacy, "legacy", "modern") + return a + + +def test_is_deprecation_warning_subclass(): + """The warning subclasses DeprecationWarning, and filters on either do not affect the other.""" + assert issubclass(LettuceDetectDeprecationWarning, DeprecationWarning) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + warnings.filterwarnings("ignore", category=LettuceDetectDeprecationWarning) + old_func() # ty: ignore[deprecated] + warnings.warn("other", DeprecationWarning) + assert [str(w.message) for w in caught] == ["other"] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + warnings.filterwarnings("ignore", message="other") + old_func() # ty: ignore[deprecated] + warnings.warn("other", DeprecationWarning) + assert len(caught) == 1 and caught[0].category is LettuceDetectDeprecationWarning + + +def test_function_warns_with_exact_message_and_caller_line(): + """A deprecated function warns with the exact message, attributed to the caller's line.""" + with pytest.warns(LettuceDetectDeprecationWarning) as rec: + line = sys._getframe().f_lineno + 1 + assert old_func(3) == 3 # ty: ignore[deprecated] + assert str(rec[0].message) == expected("old_func", "new_func") + assert rec[0].filename == __file__ and rec[0].lineno == line + + +def test_class_and_method_warn(): + """Instantiating a deprecated class and calling a deprecated method both warn.""" + with pytest.warns(LettuceDetectDeprecationWarning) as rec: + assert OldClass(2).v == 2 # ty: ignore[deprecated] + assert Holder().old() == "ok" # ty: ignore[deprecated] + assert str(rec[0].message) == expected("OldClass", "NewClass") + assert str(rec[1].message) == expected("Holder.old", "Holder.new") + assert all(r.filename == __file__ for r in rec) + + +def test_warns_once_per_call_site_under_default_filter(): + """Under the default filter, repeated calls from one call site warn only once.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + for _ in range(3): + old_func() # ty: ignore[deprecated] + assert len(caught) == 1 + + +def test_metadata(): + """Deprecated names carry the PEP 702 ``__deprecated__`` message and keep their name.""" + assert getattr(old_func, "__deprecated__") == expected("old_func", "new_func") # ty: ignore[deprecated] + assert getattr(OldClass, "__deprecated__") == expected("OldClass", "NewClass") # ty: ignore[deprecated] + assert old_func.__name__ == "old_func" # ty: ignore[deprecated] + + +def test_argument_warns_only_when_passed(): + """A deprecated argument warns only when the caller passes it.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert with_arg(1) == 1 + with pytest.warns(LettuceDetectDeprecationWarning) as rec: + line = sys._getframe().f_lineno + 1 + with_arg(1, legacy=None) + assert str(rec[0].message) == expected("The 'legacy' argument", "modern") + assert rec[0].filename == __file__ and rec[0].lineno == line + + +def test_internal_caller_is_silent_but_external_warns(): + """Calls from a ``lettucedetect.*`` module stay silent; the same calls elsewhere warn.""" + namespace = { + "__name__": "lettucedetect.fake_internal", + "f": old_func, # ty: ignore[deprecated] + "g": with_arg, + "C": OldClass, # ty: ignore[deprecated] + } + code = "f()\ng(1, legacy=1)\nC(1)" + with warnings.catch_warnings(): + warnings.simplefilter("error") + exec(code, namespace) # noqa: S102 + with pytest.warns(LettuceDetectDeprecationWarning): + exec(code, {**namespace, "__name__": "somewhere_else"}) # noqa: S102 + + +def test_importing_detectors_emits_no_warning(): + """Importing ``lettucedetect.detectors`` in a fresh interpreter emits no deprecation warning.""" + result = subprocess.run( + [ + sys.executable, + "-c", + "import warnings\n" + "with warnings.catch_warnings(record=True) as w:\n" + " warnings.simplefilter('always')\n" + " import lettucedetect.detectors as d\n" + "bad=[x for x in w if issubclass(x.category, d.LettuceDetectDeprecationWarning)]\n" + "raise SystemExit(len(bad))", + ], + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr From b7b39408a3e1f1ae24db9f18d0d67e568efa240d Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 10:28:49 +0100 Subject: [PATCH 12/60] test: turn LettuceDetectDeprecationWarning into a test error (#136) --- pyproject.toml | 1 + tests/test_custom_taxonomy_pytest.py | 4 ++++ tests/test_deprecation_pytest.py | 8 ++++++++ tests/test_factory_pytest.py | 4 ++++ tests/test_inference_pytest.py | 4 ++++ tests/test_llm_client_pytest.py | 4 ++++ tests/test_llm_detector_pytest.py | 4 ++++ 7 files changed, 29 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 396be46..82af98a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,6 +69,7 @@ lettucedetect = ["prompts/*.txt", "prompts/*.json"] testpaths = ["tests"] python_files = "test_*_pytest.py" addopts = "-v --tb=short --strict-markers" +filterwarnings = ["error::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning"] [tool.ruff] line-length = 100 diff --git a/tests/test_custom_taxonomy_pytest.py b/tests/test_custom_taxonomy_pytest.py index d39d566..0c148e3 100644 --- a/tests/test_custom_taxonomy_pytest.py +++ b/tests/test_custom_taxonomy_pytest.py @@ -10,6 +10,10 @@ from lettucedetect.detectors.taxonomy_head import resolve_taxonomy from lettucedetect.prompts.generative import build_system_prompt +pytestmark = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + CUSTOM_CATS = {"pricing_claim": "any statement about price not supported by the context"} CUSTOM_SUBS = {"currency": "a currency amount not present in the context"} diff --git a/tests/test_deprecation_pytest.py b/tests/test_deprecation_pytest.py index 7b31574..162df42 100644 --- a/tests/test_deprecation_pytest.py +++ b/tests/test_deprecation_pytest.py @@ -147,3 +147,11 @@ def test_importing_detectors_emits_no_warning(): text=True, ) assert result.returncode == 0, result.stderr + + +def test_unmarked_use_of_deprecated_name_is_an_error(): + """The pytest config turns the warning into an error; ``pytest.warns`` still records it.""" + with pytest.raises(LettuceDetectDeprecationWarning): + old_func() # ty: ignore[deprecated] + with pytest.warns(LettuceDetectDeprecationWarning): + old_func() # ty: ignore[deprecated] diff --git a/tests/test_factory_pytest.py b/tests/test_factory_pytest.py index 4e572ee..88227dc 100644 --- a/tests/test_factory_pytest.py +++ b/tests/test_factory_pytest.py @@ -6,6 +6,10 @@ from lettucedetect.detectors.factory import make_detector +pytestmark = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + class TestMakeDetector: """Tests for the ``make_detector`` factory function.""" diff --git a/tests/test_inference_pytest.py b/tests/test_inference_pytest.py index f16eb6e..adf397e 100644 --- a/tests/test_inference_pytest.py +++ b/tests/test_inference_pytest.py @@ -11,6 +11,10 @@ from lettucedetect.detectors.transformer import TransformerDetector from lettucedetect.models.inference import HallucinationDetector +pytestmark = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + @pytest.fixture def mock_tokenizer(): diff --git a/tests/test_llm_client_pytest.py b/tests/test_llm_client_pytest.py index 3f127ce..3e4a315 100644 --- a/tests/test_llm_client_pytest.py +++ b/tests/test_llm_client_pytest.py @@ -26,6 +26,10 @@ make_llm_client, ) +pytestmark = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + PLAIN_SCHEMA = build_hallucination_schema() diff --git a/tests/test_llm_detector_pytest.py b/tests/test_llm_detector_pytest.py index e031fa1..388651b 100644 --- a/tests/test_llm_detector_pytest.py +++ b/tests/test_llm_detector_pytest.py @@ -14,6 +14,10 @@ from lettucedetect.detectors.llm import LLMDetector from lettucedetect.detectors.llm_client import LLMClient +pytestmark = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + TOKEN_KEYS = {"token", "pred", "prob"} From 8bb64beb9c024951ed567bdf1cdecb96fc40bd29 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 12:04:37 +0100 Subject: [PATCH 13/60] chore: add LettuceDetectError, its three subclasses and the result warning (#138) --- lettucedetect/detectors/__init__.py | 12 ++++ lettucedetect/detectors/errors.py | 93 +++++++++++++++++++++++++++ lettucedetect/detectors/types.py | 18 ++++++ pyproject.toml | 1 + tests/test_errors_pytest.py | 97 +++++++++++++++++++++++++++++ 5 files changed, 221 insertions(+) create mode 100644 lettucedetect/detectors/errors.py create mode 100644 lettucedetect/detectors/types.py create mode 100644 tests/test_errors_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index 86e1189..d84ef17 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -1,15 +1,27 @@ from __future__ import annotations from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import ( + ConfigurationError, + InvalidInputError, + LettuceDetectError, + UpstreamError, +) from lettucedetect.detectors.factory import make_detector as _make_detector from lettucedetect.detectors.llm import LLMDetector from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector from lettucedetect.detectors.transformer import TransformerDetector +from lettucedetect.detectors.types import ResultWarning __all__ = [ "BaseDetector", + "ConfigurationError", + "InvalidInputError", "LLMDetector", + "LettuceDetectError", "RAGFactCheckerDetector", + "ResultWarning", "TransformerDetector", + "UpstreamError", "_make_detector", ] diff --git a/lettucedetect/detectors/errors.py b/lettucedetect/detectors/errors.py new file mode 100644 index 0000000..4ae6fc4 --- /dev/null +++ b/lettucedetect/detectors/errors.py @@ -0,0 +1,93 @@ +"""Typed errors raised by the detectors. + +Every error carries a stable snake_case ``code`` so a caller can handle it +without parsing the message. Each class has a default code; a raise site may +pass a more specific one. Messages never hold secrets or customer text and +refer to items by position (for example ``sources[2]``). Chain foreign errors +with ``raise ... from``; ``__cause__`` is kept as Python sets it. +""" + +from __future__ import annotations + + +class LettuceDetectError(Exception): + """Base class of every error the library raises on purpose.""" + + code = "lettucedetect_error" + + def __init__(self, message: str, *, code: str | None = None) -> None: + """Create the error. + + :param message: What the problem is and how to fix it, without secrets or customer text. + :param code: A stable snake_case code, in place of the default code of the class. + """ + super().__init__(message) + self.message = message + if code is not None: + self.code = code + + +class InvalidInputError(LettuceDetectError, ValueError): + """An argument of a call is invalid. + + Also a :class:`ValueError`, so code that catches ``ValueError`` keeps working. + """ + + code = "invalid_input" + + def __init__(self, message: str, *, code: str | None = None, param: str | None = None) -> None: + """Create the error. + + :param message: What the problem is and how to fix it. + :param code: A stable snake_case code, in place of the default code of the class. + :param param: Name of the offending argument. + """ + super().__init__(message, code=code) + self.param = param + + +class ConfigurationError(LettuceDetectError): + """A constructor argument, a setting or a package is wrong or missing. + + Only the operator of the deployment can fix it, so it is not a ``ValueError``. + """ + + code = "configuration_error" + + def __init__(self, message: str, *, code: str | None = None, param: str | None = None) -> None: + """Create the error. + + :param message: What the problem is and how to fix it. + :param code: A stable snake_case code, in place of the default code of the class. + :param param: Name of the offending argument or setting, if there is one. + """ + super().__init__(message, code=code) + self.param = param + + +class UpstreamError(LettuceDetectError): + """A service the library calls failed or did not answer in time.""" + + code = "upstream_error" + + def __init__( + self, + message: str, + *, + code: str | None = None, + service: str = "unknown", + retryable: bool = False, + retry_after: float | None = None, + ) -> None: + """Create the error. + + :param message: What the problem is and how to fix it. + :param code: A stable snake_case code, in place of the default code of the class. + :param service: The service that failed, for example `llm`. + :param retryable: Whether the same call may succeed when retried. + :param retry_after: Seconds to wait before retrying, when the service said so. + """ + super().__init__(message, code=code) + self.service = service + self.retryable = retryable + self.retry_after = retry_after diff --git a/lettucedetect/detectors/types.py b/lettucedetect/detectors/types.py new file mode 100644 index 0000000..293f1ae --- /dev/null +++ b/lettucedetect/detectors/types.py @@ -0,0 +1,18 @@ +"""Result types shared by the detectors.""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict + + +class ResultWarning(BaseModel): + """A note that a result is correct but degraded. + + :param code: stable snake_case identifier, for example ``input_truncated``. + :param message: optional human-readable text without customer text. + """ + + model_config = ConfigDict(frozen=True) + + code: str + message: str | None = None diff --git a/pyproject.toml b/pyproject.toml index 196cefc..4310161 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dependencies = [ "scikit-learn>=1.6.1", "numpy>=2.2.2", "openai>=1.66.3", + "pydantic>=2.0", "rag-fact-checker", ] diff --git a/tests/test_errors_pytest.py b/tests/test_errors_pytest.py new file mode 100644 index 0000000..fe76cdd --- /dev/null +++ b/tests/test_errors_pytest.py @@ -0,0 +1,97 @@ +"""Tests for the typed errors and the result warning.""" + +import pytest +from pydantic import ValidationError + +from lettucedetect.detectors import ( + ConfigurationError, + InvalidInputError, + LettuceDetectError, + ResultWarning, + UpstreamError, +) + + +def _make(cls): + # Build an instance of any error class with the minimal valid arguments. + if cls is InvalidInputError: + return cls("bad value", param="answer") + return cls("some message") + + +@pytest.mark.parametrize("cls", [InvalidInputError, ConfigurationError, UpstreamError]) +def test_subclasses_are_caught_by_base(cls): + # One `except LettuceDetectError` catches every subclass, and each carries a code and message. + with pytest.raises(LettuceDetectError) as exc: + raise _make(cls) + assert exc.value.code + assert exc.value.message == str(exc.value) + + +def test_value_error_only_for_invalid_input(): + # Only InvalidInputError is also a ValueError; deployment and upstream failures are not. + assert issubclass(InvalidInputError, ValueError) + assert not issubclass(ConfigurationError, ValueError) + assert not issubclass(UpstreamError, ValueError) + + +def test_param_attributes(): + # `code` and `param` are readable attributes; `param` is optional (default None) + # on both InvalidInputError and ConfigurationError. + err = InvalidInputError("min_score out of range", param="min_score", code="invalid_min_score") + assert (err.code, err.param) == ("invalid_min_score", "min_score") + assert ConfigurationError("m").param is None + assert ConfigurationError("m", param="config.lang").param == "config.lang" + assert InvalidInputError("m").param is None + + +@pytest.mark.parametrize("cls", [InvalidInputError, ConfigurationError, UpstreamError]) +def test_cause_is_kept(cls): + # Chaining with `raise ... from` keeps the original error as __cause__. + original = KeyError("x") + with pytest.raises(cls) as exc: + try: + raise original + except KeyError as e: + raise _make(cls) from e + assert exc.value.__cause__ is original + + +def test_message_built_from_request_has_no_customer_text(): + # A message that refers to an item by position never contains the request text. + answer_text = "The capital of Atlantis is Poseidonis." + request = {"sources": ["a", "b"], "answer": answer_text} + position = len(request["sources"]) - 1 + err = InvalidInputError(f"sources[{position}] is empty", param="request.sources") + assert answer_text not in err.message + assert answer_text not in str(err) + + +def test_result_warning(): + # The warning exposes a stable code, is frozen, and survives a JSON round trip unchanged. + w = ResultWarning(code="input_truncated") + assert w.code == "input_truncated" + assert w.message is None + with pytest.raises(ValidationError): + w.code = "other" # ty: ignore[invalid-assignment] + again = ResultWarning.model_validate_json(w.model_dump_json()) + assert again == w + + +def test_default_and_custom_codes(): + # Each class has a default code; a raise site may override it for one instance. + assert LettuceDetectError("m").code == "lettucedetect_error" + assert InvalidInputError("m", param="p").code == "invalid_input" + assert ConfigurationError("m").code == "configuration_error" + assert UpstreamError("m").code == "upstream_error" + assert UpstreamError("m", code="empty_response").code == "empty_response" + # a custom code is per instance and leaves the class default alone + assert UpstreamError.code == "upstream_error" + + +def test_upstream_fields(): + # UpstreamError defaults to an unknown, non-retryable service and takes retry hints. + err = UpstreamError("m") + assert (err.service, err.retryable, err.retry_after) == ("unknown", False, None) + err = UpstreamError("m", service="llm", retryable=True, retry_after=2.5) + assert (err.service, err.retryable, err.retry_after) == ("llm", True, 2.5) From e211ea7fb02dbc85d8dd1d67bc81eb4eaf098015 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 13:20:12 +0100 Subject: [PATCH 14/60] chore: add the detect request and result types --- lettucedetect/detectors/__init__.py | 24 +++- lettucedetect/detectors/types.py | 203 +++++++++++++++++++++++++++- tests/test_types_pytest.py | 141 +++++++++++++++++++ 3 files changed, 363 insertions(+), 5 deletions(-) create mode 100644 tests/test_types_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index d84ef17..c72e1a2 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -11,17 +11,39 @@ from lettucedetect.detectors.llm import LLMDetector from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector from lettucedetect.detectors.transformer import TransformerDetector -from lettucedetect.detectors.types import ResultWarning +from lettucedetect.detectors.types import ( + Chunk, + DetailedResult, + DetectedSpan, + Detection, + DetectRequest, + PromptInput, + ResultWarning, + SourcesInput, + Span, + TokenScore, + Usage, +) __all__ = [ "BaseDetector", + "Chunk", "ConfigurationError", + "DetailedResult", + "DetectRequest", + "DetectedSpan", + "Detection", "InvalidInputError", "LLMDetector", "LettuceDetectError", + "PromptInput", "RAGFactCheckerDetector", "ResultWarning", + "SourcesInput", + "Span", + "TokenScore", "TransformerDetector", "UpstreamError", + "Usage", "_make_detector", ] diff --git a/lettucedetect/detectors/types.py b/lettucedetect/detectors/types.py index 293f1ae..020456a 100644 --- a/lettucedetect/detectors/types.py +++ b/lettucedetect/detectors/types.py @@ -1,8 +1,17 @@ -"""Result types shared by the detectors.""" +"""Request and result types shared by the detectors. + +All models are frozen and hide the input in validation errors, so a validation error never +contains customer text (sources, question, answer or prompt). +""" from __future__ import annotations -from pydantic import BaseModel, ConfigDict +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, model_validator + +Triplet = list[str] +"""A (subject, predicate, object) triplet produced by the RAG fact checker.""" class ResultWarning(BaseModel): @@ -12,7 +21,193 @@ class ResultWarning(BaseModel): :param message: optional human-readable text without customer text. """ - model_config = ConfigDict(frozen=True) + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) - code: str + code: str = Field(min_length=1) message: str | None = None + + +class Chunk(BaseModel): + """A piece of source text with an id. + + :param id: non-empty identifier of the source. + :param text: the source text. + :param metadata: free-form data about the source. + :param source_start: position of the chunk in its source document, if known. + :param source_end: end position of the chunk in its source document, if known. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + id: str = Field(min_length=1) + text: str + metadata: dict[str, Any] = Field(default_factory=dict) + source_start: int | None = Field(default=None, ge=0) + source_end: int | None = Field(default=None, ge=0) + + @model_validator(mode="after") + def _validate_source_offsets_in_order(self) -> Chunk: + if ( + self.source_start is not None + and self.source_end is not None + and self.source_end < self.source_start + ): + raise ValueError("source_end must not precede source_start") + return self + + +class Span(BaseModel): + """A part of a text, given by offsets in Unicode code points. + + :param start: first code point, inclusive. + :param end: last code point, exclusive. + :param text: the text between ``start`` and ``end``. + :param score: score in [0, 1]. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + start: int = Field(ge=0) + end: int + text: str + score: float = Field(ge=0.0, le=1.0) + + @model_validator(mode="after") + def _validate_text_fits_offsets(self) -> Span: + if self.end <= self.start: + raise ValueError("end must be greater than start") + if len(self.text) != self.end - self.start: + raise ValueError("text must be exactly as long as the span from start to end") + return self + + +class DetectedSpan(Span): + """A hallucinated span of the answer. + + :param category: taxonomy category, ``None`` when not produced. + :param subcategory: taxonomy subcategory, ``None`` when not produced. + :param reasoning: the model's explanation, ``None`` when not produced. + """ + + category: str | None = None + subcategory: str | None = None + reasoning: str | None = None + + +class TokenScore(BaseModel): + """The score of one answer token. + + :param token: the token text. + :param start: first code point of the token in the answer, inclusive. + :param end: last code point of the token in the answer, exclusive. + :param score: probability that the token is hallucinated. + :param flagged: whether the detector marks the token as hallucinated. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + token: str + start: int = Field(ge=0) + end: int + score: float = Field(ge=0.0, le=1.0) + flagged: bool + + +class Usage(BaseModel): + """What one model or service did during a call. + + :param model_id: id of the model, ``None`` for work without a model. + :param model_version: version of the model, ``None`` when unknown. + :param units: counts of work done, for example ``{"input_tokens": 3410}``. + """ + + # Older pydantic 2 releases reserve the "model_" prefix for their own methods. + model_config = ConfigDict(frozen=True, hide_input_in_errors=True, protected_namespaces=()) + + model_id: str | None + model_version: str | None + units: dict[str, NonNegativeInt] + + +class Triplets(BaseModel): + """The triplets the RAG fact checker worked with. + + :param answer: triplets of the answer. + :param context: triplets of the sources. + :param hallucinated: answer triplets that the sources do not support. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + answer: list[Triplet] = Field(default_factory=list) + context: list[Triplet] = Field(default_factory=list) + hallucinated: list[Triplet] = Field(default_factory=list) + + +class DetailedResult(BaseModel): + """The evidence the RAG fact checker produced. + + :param triplets: the answer, context and hallucinated triplets. + :param fact_check_results: for each answer triplet index, whether the sources support it. + :param span_triplets: the source triplet of each span, parallel to ``Detection.spans``. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + kind: Literal["detailed"] = "detailed" + triplets: Triplets + fact_check_results: dict[int, bool] = Field(default_factory=dict) + span_triplets: list[Triplet | None] = Field(default_factory=list) + + +class SourcesInput(BaseModel): + """A request made of sources and an answer. + + :param sources: the sources the answer is checked against. + :param answer: the answer to check. + :param question: the question the answer responds to, ``None`` for summarisation. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + kind: Literal["sources"] = "sources" + sources: list[Chunk] + answer: str + question: str | None = None + + +class PromptInput(BaseModel): + """A request made of a full prompt and an answer. + + :param prompt: the full prompt the answer responds to. + :param answer: the answer to check. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + kind: Literal["prompt"] = "prompt" + prompt: str + answer: str + + +DetectRequest = Annotated[SourcesInput | PromptInput, Field(discriminator="kind")] +"""A request to a detector, discriminated on ``kind``.""" + + +class Detection(BaseModel): + """The result of one detector call. + + :param spans: the hallucinated spans of the answer. + :param tokens: token scores, ``None`` unless requested. + :param detail: fact checker evidence, ``None`` unless requested. + :param usage: what each model that took part did. + :param warnings: notes that the result is degraded. + """ + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + + spans: list[DetectedSpan] = Field(default_factory=list) + tokens: list[TokenScore] | None = None + detail: DetailedResult | None = None + usage: list[Usage] = Field(default_factory=list) + warnings: list[ResultWarning] = Field(default_factory=list) diff --git a/tests/test_types_pytest.py b/tests/test_types_pytest.py new file mode 100644 index 0000000..1a95b5a --- /dev/null +++ b/tests/test_types_pytest.py @@ -0,0 +1,141 @@ +"""Tests for the detect request and result types.""" + +import pytest +from pydantic import TypeAdapter, ValidationError + +from lettucedetect.detectors import ( + Chunk, + DetailedResult, + DetectedSpan, + Detection, + DetectRequest, + PromptInput, + ResultWarning, + SourcesInput, + Span, + TokenScore, + Usage, +) +from lettucedetect.detectors.types import Triplets + +ANSWER = "The capital of Atlantis is Poseidonis." +SOURCE = "Atlantis is a legendary island." + +REQUEST_ADAPTER = TypeAdapter(DetectRequest) + + +def _detail() -> DetailedResult: + return DetailedResult( + triplets=Triplets( + answer=[["Atlantis", "capital", "Poseidonis"]], + context=[["Barcelona", "north", "coast", "Madrid"]], # triplets may have 4 items + hallucinated=[["Atlantis", "capital", "Poseidonis"]], + ), + fact_check_results={0: False}, + span_triplets=[["Atlantis", "capital", "Poseidonis"], None], + ) + + +def _detection() -> Detection: + return Detection( + spans=[ + DetectedSpan( + start=28, end=38, text="Poseidonis", score=0.8, category="fabricated", reasoning="r" + ) + ], + tokens=[TokenScore(token="Poseidonis", start=28, end=38, score=0.8, flagged=True)], # noqa: S106 + detail=_detail(), + usage=[Usage(model_id="m", model_version=None, units={"sources": 1})], + warnings=[ResultWarning(code="input_truncated")], + ) + + +INSTANCES = [ + Chunk(id="a", text=SOURCE, metadata={"k": 1}, source_start=0, source_end=10), + Span(start=0, end=3, text="The", score=0.5), + DetectedSpan(start=0, end=3, text="The", score=0.5), + TokenScore(token="The", start=0, end=3, score=0.5, flagged=False), # noqa: S106 + Usage(model_id=None, model_version=None, units={}), + _detail(), + SourcesInput(sources=[Chunk(id="a", text=SOURCE)], answer=ANSWER, question="q"), + PromptInput(prompt="p", answer=ANSWER), + ResultWarning(code="x", message="m"), + _detection(), +] + + +@pytest.mark.parametrize("obj", INSTANCES, ids=lambda o: type(o).__name__) +def test_json_round_trip(obj): + # Every type survives model_dump_json -> model_validate_json unchanged. + assert type(obj).model_validate_json(obj.model_dump_json()) == obj + + +def test_detect_request_validates_by_kind(): + # A DetectRequest becomes a SourcesInput or a PromptInput according to `kind`. + sources = SourcesInput(sources=[Chunk(id="a", text=SOURCE)], answer=ANSWER) + prompt = PromptInput(prompt="p", answer=ANSWER) + assert REQUEST_ADAPTER.validate_json(sources.model_dump_json()) == sources + assert isinstance(REQUEST_ADAPTER.validate_json(prompt.model_dump_json()), PromptInput) + with pytest.raises(ValidationError): + REQUEST_ADAPTER.validate_python({"kind": "other", "answer": "a"}) + + +@pytest.mark.parametrize("obj", INSTANCES, ids=lambda o: type(o).__name__) +def test_types_are_frozen(obj): + # Assigning to a field raises. + field = next(iter(type(obj).model_fields)) + with pytest.raises(ValidationError): + setattr(obj, field, getattr(obj, field)) + + +def test_validation_error_hides_customer_text(): + # A bad SourcesInput reports the problem without echoing the answer or a source text. + with pytest.raises(ValidationError) as exc: + SourcesInput.model_validate( + {"sources": [{"id": "", "text": SOURCE}, {"id": "b", "text": 5}], "answer": 7} + ) + message = str(exc.value) + assert ANSWER not in message + assert SOURCE not in message + with pytest.raises(ValidationError) as exc: + Chunk(id="a", text=SOURCE, source_start=5, source_end=1) + assert SOURCE not in str(exc.value) + + +def test_detection_defaults(): + # tokens and detail default to None; usage and warnings to separate empty lists. + first, second = Detection(), Detection() + assert first.spans == [] + assert first.tokens is None + assert first.detail is None + assert first.usage == [] + assert first.warnings == [] + assert first.usage is not second.usage + assert first.warnings is not second.warnings + + +def test_span_validation(): + # Offsets are ordered, the text fits the offsets and the score is in [0, 1]. + with pytest.raises(ValidationError): + Span(start=3, end=3, text="", score=0.5) + with pytest.raises(ValidationError): + Span(start=0, end=5, text="abc", score=0.5) + with pytest.raises(ValidationError): + Span(start=0, end=3, text="abc", score=1.5) + with pytest.raises(ValidationError): + Span(start=-1, end=2, text="abc", score=0.5) + + +def test_chunk_validation(): + # The id is non-empty and the source offsets are ordered. + with pytest.raises(ValidationError): + Chunk(id="", text="t") + with pytest.raises(ValidationError): + Chunk(id="a", text="t", source_start=5, source_end=1) + + +def test_detailed_result_accepts_json_string_keys(): + # fact_check_results has int keys, which JSON turns into strings. + restored = DetailedResult.model_validate_json(_detail().model_dump_json()) + assert restored.fact_check_results == {0: False} + assert restored.triplets.context == [["Barcelona", "north", "coast", "Madrid"]] From fef39aa405f41a9f705e4430f24a570a4b84e54a Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 14:58:52 +0100 Subject: [PATCH 15/60] feat: add BaseDetector.detect and adetect with min_score and support flags (#141) --- lettucedetect/detectors/base.py | 110 ++++++++++++++- pyproject.toml | 1 + tests/test_base_detector_pytest.py | 206 +++++++++++++++++++++++++++++ 3 files changed, 316 insertions(+), 1 deletion(-) create mode 100644 tests/test_base_detector_pytest.py diff --git a/lettucedetect/detectors/base.py b/lettucedetect/detectors/base.py index 2fee358..f4d018f 100644 --- a/lettucedetect/detectors/base.py +++ b/lettucedetect/detectors/base.py @@ -2,11 +2,119 @@ from __future__ import annotations +import asyncio from abc import ABC, abstractmethod +from lettucedetect.detectors.errors import InvalidInputError +from lettucedetect.detectors.types import Detection, DetectRequest + class BaseDetector(ABC): - """All hallucination detectors implement a common interface.""" + """All hallucination detectors implement a common interface. + + :cvar supports_tokens: whether ``include_tokens=True`` is supported. + :cvar supports_detail: whether ``include_detail=True`` is supported. + :cvar model_id: id of the model behind the detector, ``None`` if there is none. + """ + + supports_tokens: bool = False + supports_detail: bool = False + model_id: str | None = None + + def detect( + self, + request: DetectRequest, + *, + min_score: float = 0.0, + include_tokens: bool = False, + include_detail: bool = False, + ) -> Detection: + """Detect hallucinated spans in the answer of a request. + + :param request: the sources (or prompt) and the answer to check. + :param min_score: drop spans scored below this value, in ``[0, 1]``. Tokens are kept. + :param include_tokens: also return token scores (needs ``supports_tokens``). + :param include_detail: also return fact checker evidence (needs ``supports_detail``). + :returns: the detection result. + :raises InvalidInputError: if ``min_score`` is outside ``[0, 1]``, or a flag is set that + the detector does not support. + """ + if not 0.0 <= min_score <= 1.0: + raise InvalidInputError( + "min_score must be in [0, 1]; pass a value between 0.0 and 1.0.", + code="invalid_min_score", + param="min_score", + ) + if include_tokens and not self.supports_tokens: + raise InvalidInputError( + "This detector does not return token scores; call with include_tokens=False.", + code="tokens_not_supported", + param="include_tokens", + ) + if include_detail and not self.supports_detail: + raise InvalidInputError( + "This detector does not return detail; call with include_detail=False.", + code="detail_not_supported", + param="include_detail", + ) + result = self._detect(request, include_tokens=include_tokens, include_detail=include_detail) + if min_score > 0.0: + result = result.model_copy( + update={"spans": [s for s in result.spans if s.score >= min_score]} + ) + return result + + async def adetect( + self, + request: DetectRequest, + *, + min_score: float = 0.0, + include_tokens: bool = False, + include_detail: bool = False, + ) -> Detection: + """Async version of :meth:`detect`; it runs ``detect`` in a worker thread. + + The event loop is never blocked. Validation, ``min_score`` filtering and the support + checks are those of :meth:`detect`, and its errors are raised from the awaited call. + + Things to know: + + * It uses the event loop's default executor, which has ``min(32, cpu + 4)`` workers. + A service with many concurrent calls should size it. + * That executor is shared with the rest of the service (``loop.getaddrinfo`` uses it + too), so a burst of long LLM calls can delay DNS lookups and other + ``asyncio.to_thread`` users. + * Cancelling ``adetect`` stops the wait, not the thread. + + There is no ``executor`` argument. + + :param request: the sources (or prompt) and the answer to check. + :param min_score: drop spans scored below this value, in ``[0, 1]``. + :param include_tokens: also return token scores. + :param include_detail: also return fact checker evidence. + :returns: the detection result, equal to what :meth:`detect` returns. + """ + return await asyncio.to_thread( + self.detect, + request, + min_score=min_score, + include_tokens=include_tokens, + include_detail=include_detail, + ) + + def _detect( + self, request: DetectRequest, *, include_tokens: bool, include_detail: bool + ) -> Detection: + """Detect hallucinated spans; detectors implement this. + + Arguments are already validated, and ``min_score`` is applied by :meth:`detect`. + + :param request: the sources (or prompt) and the answer to check. + :param include_tokens: whether to fill ``Detection.tokens``. + :param include_detail: whether to fill ``Detection.detail``. + :returns: the detection result. + """ + raise NotImplementedError(f"{type(self).__name__} does not implement _detect") @abstractmethod def predict( diff --git a/pyproject.toml b/pyproject.toml index 3114430..470fe60 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,6 +69,7 @@ lettucedetect = ["prompts/*.txt", "prompts/*.json"] [tool.pytest.ini_options] testpaths = ["tests"] python_files = "test_*_pytest.py" +asyncio_mode = "auto" addopts = "-v --tb=short --strict-markers" filterwarnings = ["error::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning"] diff --git a/tests/test_base_detector_pytest.py b/tests/test_base_detector_pytest.py new file mode 100644 index 0000000..b42c19f --- /dev/null +++ b/tests/test_base_detector_pytest.py @@ -0,0 +1,206 @@ +"""Tests for BaseDetector.detect and BaseDetector.adetect.""" + +from __future__ import annotations + +import asyncio +import inspect +import threading +import time + +import pytest + +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import InvalidInputError +from lettucedetect.detectors.types import ( + DetectedSpan, + Detection, + SourcesInput, + TokenScore, +) + +REQUEST = SourcesInput(sources=[], answer="abcdefghij") + + +def _result() -> Detection: + return Detection( + spans=[ + DetectedSpan(start=0, end=2, text="ab", score=0.2), + DetectedSpan(start=3, end=5, text="de", score=0.5), + DetectedSpan(start=6, end=8, text="gh", score=0.9), + ], + tokens=[TokenScore(token="ab", start=0, end=2, score=0.2, flagged=False)], # noqa: S106 + ) + + +class FakeDetector(BaseDetector): + """Detector with a recording, configurable hook.""" + + supports_tokens = True + supports_detail = True + + def __init__(self, result=None, delay=0.0, error=None) -> None: + """Create the fake.""" + self.result = result or _result() + self.delay = delay + self.error = error + self.calls = [] + self.thread_ids = [] + + def predict(self, *a: object, **k: object) -> list: # noqa: D102 + return [] + + def predict_prompt(self, *a: object, **k: object) -> list: # noqa: D102 + return [] + + def predict_prompt_batch(self, *a: object, **k: object) -> list: # noqa: D102 + return [] + + def _detect(self, request, *, include_tokens, include_detail): + self.calls.append((request, include_tokens, include_detail)) + self.thread_ids.append(threading.get_ident()) + if self.delay: + time.sleep(self.delay) + if self.error: + raise self.error + return self.result + + +class PlainDetector(FakeDetector): + """Detector without token or detail support.""" + + supports_tokens = False + supports_detail = False + + +def test_detect_returns_hook_result_and_defaults(): + """The detect method returns what the hook returns; defaults pass no flags to the hook; model_id is None.""" + d = FakeDetector() + assert d.detect(REQUEST) == _result() + assert d.calls == [(REQUEST, False, False)] + assert d.model_id is None + + +def test_flags_are_passed_to_hook_when_supported(): + """include_tokens / include_detail reach the hook when the detector supports them.""" + d = FakeDetector() + d.detect(REQUEST, include_tokens=True, include_detail=True) + assert d.calls == [(REQUEST, True, True)] + + +def test_min_score_filters_spans_not_tokens(): + """Spans scoring below min_score are dropped (equal is kept); tokens are not filtered.""" + out = FakeDetector().detect(REQUEST, min_score=0.5) + assert [s.score for s in out.spans] == [0.5, 0.9] + assert out.tokens == _result().tokens + + +@pytest.mark.parametrize("value", [-0.1, 1.1, float("nan")]) +@pytest.mark.parametrize("is_async", [False, True]) +async def test_invalid_min_score(value, is_async): + """min_score outside [0, 1] (or NaN) raises invalid_min_score before the hook runs, from detect and from await adetect.""" + d = FakeDetector() + with pytest.raises(InvalidInputError) as exc: + if is_async: + await d.adetect(REQUEST, min_score=value) + else: + d.detect(REQUEST, min_score=value) + assert exc.value.code == "invalid_min_score" + assert exc.value.param == "min_score" + assert d.calls == [] + + +@pytest.mark.parametrize("value", [0.0, 1.0]) +def test_min_score_boundaries_accepted(value): + """The bounds 0.0 and 1.0 are valid min_score values.""" + FakeDetector().detect(REQUEST, min_score=value) + + +@pytest.mark.parametrize( + ("kwargs", "code", "param"), + [ + ({"include_tokens": True}, "tokens_not_supported", "include_tokens"), + ({"include_detail": True}, "detail_not_supported", "include_detail"), + ], +) +@pytest.mark.parametrize("is_async", [False, True]) +async def test_unsupported_flags(kwargs, code, param, is_async): + """Unsupported include_tokens / include_detail raise their own code and param before the hook runs, sync and async.""" + d = PlainDetector() + with pytest.raises(InvalidInputError) as exc: + if is_async: + await d.adetect(REQUEST, **kwargs) + else: + d.detect(REQUEST, **kwargs) + assert exc.value.code == code + assert exc.value.param == param + assert d.calls == [] + + +async def test_adetect_is_coroutine_function_and_equal_result(): + """The adetect method is a coroutine function and returns a result equal to detect.""" + assert inspect.iscoroutinefunction(BaseDetector.adetect) + d = FakeDetector() + assert await d.adetect(REQUEST, min_score=0.5) == d.detect(REQUEST, min_score=0.5) + + +async def test_hook_runs_off_the_loop_thread_and_loop_stays_responsive(): + """The hook runs on a thread other than the event loop's, and the loop keeps ticking while a slow hook sleeps.""" + d = FakeDetector(delay=0.3) + ticks = 0 + + async def ticker(): + nonlocal ticks + while True: + await asyncio.sleep(0.02) + ticks += 1 + + task = asyncio.create_task(ticker()) + await d.adetect(REQUEST) + task.cancel() + assert d.thread_ids[0] != threading.get_ident() + assert ticks >= 5 + + +async def test_gather_keeps_call_order(): + """Concurrent adetect calls finish out of order (different delays) but gather returns them in call order, each equal to its detect result.""" + detectors = [FakeDetector(delay=0.05 * (3 - i)) for i in range(3)] + scores = [0.1, 0.4, 0.7] + results = await asyncio.gather( + *(d.adetect(REQUEST, min_score=s) for d, s in zip(detectors, scores, strict=True)) + ) + for d, s, r in zip(detectors, scores, results, strict=True): + assert r == d.detect(REQUEST, min_score=s) + + +@pytest.mark.parametrize("is_async", [False, True]) +async def test_hook_exception_propagates_unwrapped(is_async): + """An exception from the hook is raised as the very same object, with __cause__ intact, from detect and await adetect.""" + cause = RuntimeError("root") + err = KeyError("boom") + err.__cause__ = cause + d = FakeDetector(error=err) + with pytest.raises(KeyError) as exc: + if is_async: + await d.adetect(REQUEST) + else: + d.detect(REQUEST) + assert exc.value is err + assert exc.value.__cause__ is cause + + +def test_adetect_docstring_states_the_caveats(): + """The adetect docstring states the default executor and its size, that it is shared, that cancelling stops the wait only, and that there is no executor argument.""" + doc = BaseDetector.adetect.__doc__ + for text in ("default executor", "min(32", "shared", "Cancelling", "no ``executor`` argument"): + assert doc is not None + assert text in doc + + +def test_default_hook_raises_not_implemented(): + """A detector that does not override _detect raises NotImplementedError when detect is called.""" + + class Bare(PlainDetector): + _detect = BaseDetector._detect + + with pytest.raises(NotImplementedError): + Bare().detect(REQUEST) From bef046d69de319772d39f5855006bc49171724d2 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 15:32:43 +0100 Subject: [PATCH 16/60] feat: bridge old and new BaseDetector interfaces (#142) --- lettucedetect/detectors/base.py | 220 +++++++++++++- tests/test_base_detector_bridge_pytest.py | 352 ++++++++++++++++++++++ tests/test_base_detector_pytest.py | 8 +- 3 files changed, 563 insertions(+), 17 deletions(-) create mode 100644 tests/test_base_detector_bridge_pytest.py diff --git a/lettucedetect/detectors/base.py b/lettucedetect/detectors/base.py index f4d018f..436a43c 100644 --- a/lettucedetect/detectors/base.py +++ b/lettucedetect/detectors/base.py @@ -3,15 +3,49 @@ from __future__ import annotations import asyncio -from abc import ABC, abstractmethod +import threading +import warnings +from abc import ABC +from lettucedetect.detectors._deprecation import LettuceDetectDeprecationWarning, _message from lettucedetect.detectors.errors import InvalidInputError -from lettucedetect.detectors.types import Detection, DetectRequest +from lettucedetect.detectors.types import ( + Chunk, + DetectedSpan, + Detection, + DetectRequest, + PromptInput, + ResultWarning, + SourcesInput, + Usage, +) + +_OUTPUT_FORMATS = ("tokens", "spans") + +# Name of the class attribute that marks a legacy class as already warned about. It is read from +# the class's own ``__dict__``, so a subclass of a warned class warns once more on its own. +_WARNED_FLAG = "_legacy_warning_emitted" +_warned_lock = threading.Lock() + + +def _reset_legacy_warnings() -> None: + """Forget which legacy classes were warned about, so each warns again. For tests.""" + pending: list[type[BaseDetector]] = [BaseDetector] + while pending: + cls = pending.pop() + if _WARNED_FLAG in cls.__dict__: + delattr(cls, _WARNED_FLAG) + pending.extend(cls.__subclasses__()) class BaseDetector(ABC): """All hallucination detectors implement a common interface. + A new detector implements ``_detect`` and gets ``detect``, ``adetect`` and the ``predict*`` + methods for free. A detector that implements only the legacy ``predict`` and + ``predict_prompt`` still works through ``detect``, with one deprecation warning per class. + A subclass that overrides none of ``detect``, ``_detect`` and ``predict`` cannot be defined. + :cvar supports_tokens: whether ``include_tokens=True`` is supported. :cvar supports_detail: whether ``include_detail=True`` is supported. :cvar model_id: id of the model behind the detector, ``None`` if there is none. @@ -21,6 +55,23 @@ class BaseDetector(ABC): supports_detail: bool = False model_id: str | None = None + def __init_subclass__(cls, **kwargs: object) -> None: + """Reject a subclass that implements no detection method. + + ``detect`` and ``predict`` call each other, so a class that overrides none of + ``detect``, ``_detect`` and ``predict`` would recurse forever when called. + + :raises TypeError: if the class overrides none of ``detect``, ``_detect``, ``predict``. + """ + super().__init_subclass__(**kwargs) + if not any( + getattr(cls, name) is not getattr(BaseDetector, name) + for name in ("detect", "_detect", "predict") + ): + raise TypeError( + f"{cls.__name__} must override _detect (or detect, or the legacy predict)." + ) + def detect( self, request: DetectRequest, @@ -108,15 +159,138 @@ def _detect( """Detect hallucinated spans; detectors implement this. Arguments are already validated, and ``min_score`` is applied by :meth:`detect`. + The default serves a subclass that overrides only the legacy ``predict`` methods. :param request: the sources (or prompt) and the answer to check. :param include_tokens: whether to fill ``Detection.tokens``. :param include_detail: whether to fill ``Detection.detail``. :returns: the detection result. """ - raise NotImplementedError(f"{type(self).__name__} does not implement _detect") + if type(self).predict is BaseDetector.predict: + raise NotImplementedError(f"{type(self).__name__} does not implement _detect") + return self._detect_via_predict(request, include_tokens, include_detail) + + def _detect_via_predict( + self, request: DetectRequest, include_tokens: bool, include_detail: bool + ) -> Detection: + """Answer ``detect`` with the legacy ``predict`` / ``predict_prompt`` of a subclass.""" + if include_tokens: + raise InvalidInputError( + "This detector does not return token scores; call with include_tokens=False.", + code="tokens_not_supported", + param="include_tokens", + ) + if include_detail: + raise InvalidInputError( + "This detector does not return detail; call with include_detail=False.", + code="detail_not_supported", + param="include_detail", + ) + cls = type(self) + first_call = False + if not cls.__dict__.get(_WARNED_FLAG): + with _warned_lock: + if not cls.__dict__.get(_WARNED_FLAG): + setattr(cls, _WARNED_FLAG, True) + first_call = True + if first_call: + warnings.warn( + _message(f"{cls.__qualname__}.predict (without _detect)", "_detect"), + LettuceDetectDeprecationWarning, + stacklevel=4, + ) + if isinstance(request, SourcesInput): + raw = self.predict( + [chunk.text for chunk in request.sources], + request.answer, + request.question, + "spans", + min_confidence=0.0, + ) + elif type(self).predict_prompt is BaseDetector.predict_prompt: + raise InvalidInputError( + "This detector does not accept a prompt request; pass sources instead.", + code="prompt_input_not_supported", + param="request", + ) + else: + raw = self.predict_prompt(request.prompt, request.answer, "spans", min_confidence=0.0) + spans = [] + synthetic = False + for item in raw: + confidence = item.get("confidence") + if confidence is None: + synthetic = True + confidence = 1.0 + spans.append( + DetectedSpan( + start=item["start"], + end=item["end"], + text=item["text"], + score=confidence, + category=item.get("category"), + subcategory=item.get("subcategory"), + reasoning=item.get("reasoning"), + ) + ) + warnings_ = ( + [ + ResultWarning( + code="synthetic_score", + message="The detector gave no confidence; spans without one score 1.0.", + ) + ] + if synthetic + else [] + ) + usage = [Usage(model_id=getattr(self, "model_id", None), model_version=None, units={})] + return Detection(spans=spans, usage=usage, warnings=warnings_) + + @staticmethod + def _check_legacy_arguments(output_format: str, min_confidence: float) -> None: + """Validate the arguments the ``predict*`` methods share.""" + if output_format not in _OUTPUT_FORMATS: + raise InvalidInputError( + 'output_format must be "tokens" or "spans".', + code="unsupported_output_format", + param="output_format", + ) + if not 0.0 <= min_confidence <= 1.0: + raise InvalidInputError( + "min_confidence must be in [0, 1]; pass a value between 0.0 and 1.0.", + code="invalid_min_score", + param="min_confidence", + ) + + def _predict_via_detect( + self, request: DetectRequest, output_format: str, min_confidence: float + ) -> list: + """Answer a ``predict*`` call with :meth:`detect`, in the legacy dict format.""" + self._check_legacy_arguments(output_format, min_confidence) + detection = self.detect( + request, min_score=min_confidence, include_tokens=output_format == "tokens" + ) + if output_format == "tokens": + assert detection.tokens is not None # noqa: S101 - detect fills it when asked + return [ + {"token": t.token, "pred": 1 if t.flagged else 0, "prob": t.score} + for t in detection.tokens + ] + result = [] + for span in detection.spans: + item = { + "start": span.start, + "end": span.end, + "text": span.text, + "confidence": span.score, + } + for key in ("category", "subcategory", "reasoning"): + value = getattr(span, key) + if value is not None: + item[key] = value + result.append(item) + return result - @abstractmethod def predict( self, context: list[str], @@ -127,31 +301,43 @@ def predict( ) -> list: """Predict hallucination tokens or spans given passages and an answer. + The default builds a request and calls :meth:`detect`; a legacy detector overrides it. + :param context: List of passages that were supplied to the LLM / user. :param answer: Model-generated answer to inspect. :param question: Original question (``None`` for summarisation). :param output_format: ``"tokens"`` for token-level dicts, ``"spans"`` for character spans. :param min_confidence: Drop ``"spans"`` whose ``confidence`` is below this threshold - (in ``[0, 1]``; ``0.0`` keeps every span). Ignored for ``"tokens"`` output. + (in ``[0, 1]``; ``0.0`` keeps every span). :returns: List of predictions in requested format. + :raises InvalidInputError: for an unsupported ``output_format`` or a ``min_confidence`` + outside ``[0, 1]``. """ - pass + request = SourcesInput( + sources=[Chunk(id=str(i), text=text) for i, text in enumerate(context)], + answer=answer, + question=question, + ) + return self._predict_via_detect(request, output_format, min_confidence) - @abstractmethod def predict_prompt( self, prompt: str, answer: str, output_format: str = "tokens", min_confidence: float = 0.0 ) -> list: """Predict hallucinations from a pre-built prompt string. + The default builds a request and calls :meth:`detect`; a legacy detector overrides it. + :param prompt: Full prompt (context + question already concatenated). :param answer: Model-generated answer to inspect. :param output_format: ``"tokens"`` or ``"spans"``. :param min_confidence: Drop ``"spans"`` below this confidence threshold (``[0, 1]``). :returns: List of predictions in requested format. + :raises InvalidInputError: for an unsupported ``output_format`` or a ``min_confidence`` + outside ``[0, 1]``. """ - pass + request = PromptInput(prompt=prompt, answer=answer) + return self._predict_via_detect(request, output_format, min_confidence) - @abstractmethod def predict_prompt_batch( self, prompts: list[str], @@ -159,15 +345,27 @@ def predict_prompt_batch( output_format: str = "tokens", min_confidence: float = 0.0, ) -> list: - """Batch version of :meth:`predict_prompt`. + """Batch version of :meth:`predict_prompt`; for now one pair at a time. :param prompts: List of full prompt strings. :param answers: List of answers to inspect. :param output_format: ``"tokens"`` or ``"spans"``. :param min_confidence: Drop ``"spans"`` below this confidence threshold (``[0, 1]``). :returns: List of prediction lists, one per input pair. + :raises InvalidInputError: for an unsupported ``output_format``, a ``min_confidence`` + outside ``[0, 1]`` or lists of different lengths. """ - pass + self._check_legacy_arguments(output_format, min_confidence) + if len(prompts) != len(answers): + raise InvalidInputError( + "prompts and answers must have the same length.", + code="length_mismatch", + param="answers", + ) + return [ + self.predict_prompt(prompt, answer, output_format, min_confidence) + for prompt, answer in zip(prompts, answers, strict=True) + ] @staticmethod def _validate_min_confidence(min_confidence: float) -> None: diff --git a/tests/test_base_detector_bridge_pytest.py b/tests/test_base_detector_bridge_pytest.py new file mode 100644 index 0000000..da35af2 --- /dev/null +++ b/tests/test_base_detector_bridge_pytest.py @@ -0,0 +1,352 @@ +"""Tests for the bridge between the old predict* and the new detect interfaces.""" + +from __future__ import annotations + +import asyncio +import threading +import warnings +from typing import ClassVar + +import pytest + +from lettucedetect.detectors import LettuceDetectDeprecationWarning +from lettucedetect.detectors import base as base_module +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import InvalidInputError +from lettucedetect.detectors.types import ( + Chunk, + DetectedSpan, + Detection, + PromptInput, + SourcesInput, + TokenScore, +) + +SOURCES = SourcesInput( + sources=[Chunk(id="a", text="s1"), Chunk(id="b", text="s2")], answer="abcdef", question="q?" +) +PROMPT = PromptInput(prompt="the prompt", answer="abcdef") + + +class NewStyle(BaseDetector): + """Implements only _detect.""" + + supports_tokens = True + + def __init__(self) -> None: + """Create the detector.""" + self.requests = [] + + def _detect(self, request, *, include_tokens, include_detail): + self.requests.append(request) + tokens = [TokenScore(token="abc", start=0, end=3, score=0.8, flagged=True)] # noqa: S106 + return Detection( + spans=[ + DetectedSpan( + start=0, + end=3, + text="abc", + score=0.8, + category="c", + subcategory="s", + reasoning="r", + ), + DetectedSpan(start=4, end=6, text="ef", score=0.3), + ], + tokens=tokens if include_tokens else None, + ) + + +class LegacyStyle(BaseDetector): + """Implements only the old methods.""" + + model_id = "legacy-model" + spans: ClassVar[list[dict]] = [ + {"start": 0, "end": 3, "text": "abc", "confidence": 0.7, "category": "c", "reasoning": "r"}, + {"start": 4, "end": 6, "text": "ef"}, + ] + + def __init__(self) -> None: + """Create the detector.""" + self.calls = [] + self.thread_ids = [] + + def predict(self, context, answer, question=None, output_format="tokens", min_confidence=0.0): # noqa: D102 + self.calls.append(("predict", context, answer, question, output_format, min_confidence)) + self.thread_ids.append(threading.get_ident()) + return list(self.spans) + + def predict_prompt(self, prompt, answer, output_format="tokens", min_confidence=0.0): # noqa: D102 + self.calls.append(("predict_prompt", prompt, answer, output_format, min_confidence)) + self.thread_ids.append(threading.get_ident()) + return list(self.spans) + + +@pytest.fixture(autouse=True) +def _forget_warned_classes(): + """Start every test with no class marked as already warned.""" + base_module._reset_legacy_warnings() + + +# --- detect-only subclass answers predict* --------------------------------------------------- + + +def test_predict_spans_maps_score_to_confidence(): + """A detect-only subclass answers predict(output_format="spans") with confidence from score.""" + d = NewStyle() + out = d.predict(["s1", "s2"], "abcdef", "q?", "spans") + assert out == [ + { + "start": 0, + "end": 3, + "text": "abc", + "confidence": 0.8, + "category": "c", + "subcategory": "s", + "reasoning": "r", + }, + {"start": 4, "end": 6, "text": "ef", "confidence": 0.3}, + ] + assert d.requests[0] == SourcesInput( + sources=[Chunk(id="0", text="s1"), Chunk(id="1", text="s2")], answer="abcdef", question="q?" + ) + + +def test_predict_tokens_maps_score_to_prob(): + """The predict method returns token dicts with pred from flagged and prob from score.""" + out = NewStyle().predict(["s1"], "abcdef") + assert out == [{"token": "abc", "pred": 1, "prob": 0.8}] + + +def test_predict_min_confidence_filters_spans(): + """min_confidence is passed on as min_score and drops low spans.""" + out = NewStyle().predict(["s1"], "abcdef", output_format="spans", min_confidence=0.5) + assert [s["text"] for s in out] == ["abc"] + + +def test_predict_prompt_and_batch(): + """predict_prompt builds a PromptInput; the batch runs one pair at a time, in order.""" + d = NewStyle() + assert d.predict_prompt("p", "abcdef", "spans")[0]["confidence"] == 0.8 + assert d.requests[-1] == PromptInput(prompt="p", answer="abcdef") + batch = d.predict_prompt_batch(["p1", "p2"], ["abcdef", "abcdef"], "tokens") + assert batch == [[{"token": "abc", "pred": 1, "prob": 0.8}]] * 2 + assert [r.prompt for r in d.requests[-2:]] == ["p1", "p2"] + + +@pytest.mark.parametrize( + ("call", "code", "param"), + [ + ( + lambda d: d.predict(["s"], "a", output_format="words"), + "unsupported_output_format", + "output_format", + ), + ( + lambda d: d.predict_prompt("p", "a", output_format="words"), + "unsupported_output_format", + "output_format", + ), + ( + lambda d: d.predict(["s"], "a", min_confidence=1.5), + "invalid_min_score", + "min_confidence", + ), + ( + lambda d: d.predict_prompt("p", "a", min_confidence=-1), + "invalid_min_score", + "min_confidence", + ), + (lambda d: d.predict_prompt_batch(["p"], ["a", "b"]), "length_mismatch", "answers"), + ( + lambda d: d.predict_prompt_batch(["p"], ["a"], "words"), + "unsupported_output_format", + "output_format", + ), + ( + lambda d: d.predict_prompt_batch(["p"], ["a"], min_confidence=2), + "invalid_min_score", + "min_confidence", + ), + ], +) +def test_predict_argument_errors(call, code, param): + """The predict* methods raise InvalidInputError with the documented code and param.""" + d = NewStyle() + with pytest.raises(InvalidInputError) as exc: + call(d) + assert exc.value.code == code + assert exc.value.param == param + assert d.requests == [] + + +# --- predict-only subclass answers detect ---------------------------------------------------- + + +def test_legacy_detect_sources_and_prompt(): + """The detect method routes sources to predict and a prompt to predict_prompt, and maps the fields.""" + d = LegacyStyle() + with pytest.warns(LettuceDetectDeprecationWarning): + by_sources = d.detect(SOURCES) + by_prompt = d.detect(PROMPT) + assert d.calls[0] == ("predict", ["s1", "s2"], "abcdef", "q?", "spans", 0.0) + assert d.calls[1] == ("predict_prompt", "the prompt", "abcdef", "spans", 0.0) + for result in (by_sources, by_prompt): + first, second = result.spans + assert (first.score, first.category, first.reasoning) == (0.7, "c", "r") + assert second.score == 1.0 + assert [w.code for w in result.warnings] == ["synthetic_score"] + assert [(u.model_id, u.units) for u in result.usage] == [("legacy-model", {})] + + +def test_legacy_without_synthetic_span_has_no_warning_entry(): + """A result whose spans all carry a confidence has no synthetic_score warning.""" + + class Scored(LegacyStyle): + spans: ClassVar[list[dict]] = [{"start": 0, "end": 3, "text": "abc", "confidence": 0.7}] + + with pytest.warns(LettuceDetectDeprecationWarning): + assert Scored().detect(SOURCES).warnings == [] + + +def test_legacy_min_score_filters_after_mapping(): + """min_score applies to the mapped score, so the synthetic 1.0 passes and 0.7 does not.""" + with pytest.warns(LettuceDetectDeprecationWarning): + out = LegacyStyle().detect(SOURCES, min_score=0.8) + assert [s.text for s in out.spans] == ["ef"] + + +def test_legacy_detect_rejects_tokens_and_detail(): + """include_tokens / include_detail raise on a legacy subclass.""" + for kwargs, code in ( + ({"include_tokens": True}, "tokens_not_supported"), + ({"include_detail": True}, "detail_not_supported"), + ): + with pytest.raises(InvalidInputError) as exc: + LegacyStyle().detect(SOURCES, **kwargs) + assert exc.value.code == code + + +def test_legacy_prompt_request_without_predict_prompt_raises_instead_of_recursing(): + """A predict-only class given a prompt request raises, rather than predict_prompt <-> detect looping.""" + + class OnlyPredict(BaseDetector): + def predict( + self, context, answer, question=None, output_format="tokens", min_confidence=0.0 + ): + return [] + + with pytest.warns(LettuceDetectDeprecationWarning), pytest.raises(InvalidInputError) as exc: + OnlyPredict().detect(PROMPT) + assert exc.value.code == "prompt_input_not_supported" + + +# --- adetect on a legacy subclass ------------------------------------------------------------ + + +async def test_legacy_adetect_both_kinds_equal_detect_and_off_loop_thread(): + """The adetect method works on a predict-only subclass, returns what detect returns, off the loop thread.""" + d = LegacyStyle() + with pytest.warns(LettuceDetectDeprecationWarning): + awaited = [await d.adetect(request) for request in (SOURCES, PROMPT)] + assert d.thread_ids + assert threading.get_ident() not in d.thread_ids + assert awaited == [d.detect(SOURCES), d.detect(PROMPT)] + + +async def test_legacy_warning_once_per_class_across_sync_async_and_concurrent_calls(): + """One warning per class, however many sync, awaited or concurrent calls follow.""" + + class Fresh(LegacyStyle): + pass + + d = Fresh() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + d.detect(SOURCES) + d.detect(PROMPT) + await d.adetect(SOURCES) + await asyncio.gather(*(d.adetect(PROMPT) for _ in range(8))) + Fresh().detect(SOURCES) + mine = [w for w in caught if issubclass(w.category, LettuceDetectDeprecationWarning)] + assert len(mine) == 1 + assert "Fresh" in str(mine[0].message) + + +def test_each_legacy_class_warns_once(): + """Two different legacy classes warn once each.""" + + class One(LegacyStyle): + pass + + class Two(LegacyStyle): + pass + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + for cls in (One, Two, One, Two): + cls().detect(SOURCES) + assert len([w for w in caught if issubclass(w.category, LettuceDetectDeprecationWarning)]) == 2 + + +# --- defining subclasses --------------------------------------------------------------------- + + +def test_subclass_overriding_nothing_raises_type_error(): + """A class that overrides none of detect, _detect, predict fails at class definition.""" + with pytest.raises(TypeError, match="Neither"): + + class Neither(BaseDetector): + pass + + +def test_defining_valid_subclasses_emits_no_warning(): + """Defining subclasses that override detect, _detect or predict emits no warning.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + + class A(BaseDetector): + def _detect(self, request, *, include_tokens, include_detail): + raise NotImplementedError + + class B(BaseDetector): + def detect(self, request, **kwargs): + raise NotImplementedError + + class C(BaseDetector): + def predict(self, *args: object, **kwargs: object): + raise NotImplementedError + + class D(A): + pass + + +def test_reset_makes_a_warned_class_warn_again(): + """After the reset helper, a class that already warned warns on its next detect call.""" + + class Again(LegacyStyle): + pass + + with pytest.warns(LettuceDetectDeprecationWarning): + Again().detect(SOURCES) + with warnings.catch_warnings(): + warnings.simplefilter("error") + Again().detect(SOURCES) + base_module._reset_legacy_warnings() + with pytest.warns(LettuceDetectDeprecationWarning): + Again().detect(SOURCES) + + +def test_subclass_of_a_warned_class_warns_on_its_own(): + """The flag is per class: a subclass of a warned class still gets its own warning.""" + + class Parent(LegacyStyle): + pass + + class Child(Parent): + pass + + with pytest.warns(LettuceDetectDeprecationWarning, match="Parent"): + Parent().detect(SOURCES) + with pytest.warns(LettuceDetectDeprecationWarning, match="Child"): + Child().detect(SOURCES) diff --git a/tests/test_base_detector_pytest.py b/tests/test_base_detector_pytest.py index b42c19f..98f50b4 100644 --- a/tests/test_base_detector_pytest.py +++ b/tests/test_base_detector_pytest.py @@ -197,10 +197,6 @@ def test_adetect_docstring_states_the_caveats(): def test_default_hook_raises_not_implemented(): - """A detector that does not override _detect raises NotImplementedError when detect is called.""" - - class Bare(PlainDetector): - _detect = BaseDetector._detect - + """The base class itself, which has no hook and no legacy predict, raises NotImplementedError.""" with pytest.raises(NotImplementedError): - Bare().detect(REQUEST) + BaseDetector().detect(REQUEST) From 396a6cf6ecb4caa9e01bc0262b58ef356af0afea Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 15:41:37 +0100 Subject: [PATCH 17/60] test: add the reusable detector contract suite (#143) --- tests/detector_contract.py | 408 +++++++++++++++++++++++++ tests/test_detector_contract_pytest.py | 283 +++++++++++++++++ 2 files changed, 691 insertions(+) create mode 100644 tests/detector_contract.py create mode 100644 tests/test_detector_contract_pytest.py diff --git a/tests/detector_contract.py b/tests/detector_contract.py new file mode 100644 index 0000000..b4877cf --- /dev/null +++ b/tests/detector_contract.py @@ -0,0 +1,408 @@ +"""Reusable contract suite that every detector must pass. + +The suite checks the invariants of ``detect`` and ``adetect`` and nothing else, so it does not +care how a detector is built. It reads the public result and the public errors only. + +How a detector task plugs in +============================ + +1. Subclass :class:`DetectorContract` inside a ``tests/test_*_pytest.py`` file. The base class is + not collected by pytest itself, only your ``Test...`` subclass is:: + + from tests.detector_contract import DetectorContract + + class TestMyDetectorContract(DetectorContract): + sources_request = SourcesInput(...) + prompt_request = PromptInput(...) + + def make_detector(self, on_call=None): + return MyDetector(model=FakeModel(on_call)) + +2. Set ``sources_request`` and ``prompt_request``. The answers must be long enough that no + short fragment of them also appears in an unrelated log message, and the detector must flag + spans with at least two different scores for the same request (the ``min_score`` and + ordering checks need that). +3. Implement ``make_detector(on_call)``. It returns a fresh detector that works offline and + needs no GPU. When ``on_call`` is not ``None``, the detector must call ``on_call()`` once per + ``detect`` call, on the thread that runs the detection, after it started and before it + returns. Put it where the slow work happens (the model call or the HTTP call). The suite uses + it to make a detector slow, or to block it on an event. +4. Detectors that predate ``detect`` pass too. A ``predict``-only subclass is wrapped by + ``BaseDetector`` and is checked through ``detect`` and ``adetect``. Its test class must + silence ``LettuceDetectDeprecationWarning`` (``pytest.mark.filterwarnings("ignore::...")``). +5. Detectors that do not support tokens or detail leave ``supports_tokens`` and + ``supports_detail`` at ``False``. The suite then expects ``InvalidInputError``. + +Every check is a plain method without pytest fixtures, so ``tests/test_detector_contract_pytest.py`` +can also run a check against a deliberately broken detector and assert that it fails. + +About cancelling ``adetect`` +============================ + +``adetect`` runs ``detect`` in a worker thread. Cancelling the awaiting task, or timing out with +``asyncio.wait_for``, stops the wait only. The thread keeps running until the detector returns, +because Python cannot stop a thread. The cancel checks document that: the detector is still busy +right after the cancel, the thread is let go afterwards, and only then do the checks run. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import inspect +import io +import logging +import math +import os +import tempfile +import threading +import time +from collections.abc import Awaitable, Callable, Generator +from pathlib import Path + +import pytest + +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import InvalidInputError +from lettucedetect.detectors.types import Detection, DetectRequest, PromptInput, SourcesInput + +CONTENT_LOGGER = "lettucedetect.content" +"""The only logger allowed to carry answer or source text (CONTRIBUTING, "Errors and logging").""" + +_SLOW_SECONDS = 0.3 +_WAIT_SECONDS = 10.0 + + +@contextlib.contextmanager +def _isolated_environment() -> Generator[tuple[Path, Path]]: + """Run with an empty temporary directory as cwd and as ``HOME``; yield both paths.""" + with tempfile.TemporaryDirectory() as root: + cwd = Path(root) / "cwd" + home = Path(root) / "home" + cwd.mkdir() + home.mkdir() + old_cwd = Path.cwd() + saved = {key: os.environ.get(key) for key in ("HOME", "USERPROFILE")} + os.chdir(cwd) + os.environ["HOME"] = os.environ["USERPROFILE"] = str(home) + try: + yield cwd, home + finally: + os.chdir(old_cwd) + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +class _Recorder(logging.Handler): + """Collect every log record that reaches the root logger.""" + + def __init__(self) -> None: + """Create an empty recorder.""" + super().__init__(level=logging.DEBUG) + self.records: list[logging.LogRecord] = [] + + def emit(self, record: logging.LogRecord) -> None: + """Keep the record.""" + self.records.append(record) + + +def _is_content_logger(name: str) -> bool: + return name == CONTENT_LOGGER or name.startswith(CONTENT_LOGGER + ".") + + +def _texts_of(request: DetectRequest) -> list[str]: + """Return every piece of customer text in a request.""" + if isinstance(request, SourcesInput): + texts = [chunk.text for chunk in request.sources] + if request.question: + texts.append(request.question) + else: + texts = [request.prompt] + texts.append(request.answer) + return [text for text in texts if text] + + +def _assert_empty(directory: Path, what: str) -> None: + left = sorted(path.name for path in directory.rglob("*")) + assert not left, f"a call left files in the temporary {what}: {left}" + + +class DetectorContract: + """The checks every detector must pass. Subclass it and set the three members below.""" + + sources_request: SourcesInput + prompt_request: PromptInput + + def make_detector(self, on_call: Callable[[], None] | None = None) -> BaseDetector: + """Return a fresh detector that calls ``on_call()`` once per ``detect`` call.""" + raise NotImplementedError + + # -- helpers --------------------------------------------------------------------------- + + def _requests(self) -> list[DetectRequest]: + return [self.sources_request, self.prompt_request] + + def _distinct_scores(self, request: DetectRequest) -> list[float]: + scores = sorted({span.score for span in self.make_detector().detect(request).spans}) + assert len(scores) >= 2, "the sample request must produce spans with two different scores" + return scores + + # -- result shape ---------------------------------------------------------------------- + + def test_span_text_equals_answer_between_offsets(self) -> None: + """Every span's text equals the answer between its offsets, for both request kinds.""" + detector = self.make_detector() + for request in self._requests(): + spans = detector.detect(request).spans + assert spans, "the sample request must produce at least one span" + for span in spans: + assert request.answer[span.start : span.end] == span.text + + def test_every_span_has_a_numeric_score_and_min_score_filters_on_it(self) -> None: + """Every span has a numeric score in [0, 1], and min_score keeps exactly the spans at or above it.""" + detector = self.make_detector() + for request in self._requests(): + everything = detector.detect(request).spans + for span in everything: + assert isinstance(span.score, int | float) + assert not isinstance(span.score, bool) + assert 0.0 <= span.score <= 1.0 + for threshold in [0.0, *self._distinct_scores(request), 1.0]: + kept = detector.detect(request, min_score=threshold).spans + assert kept == [s for s in everything if s.score >= threshold] + + def test_usage_has_an_entry_with_the_model_id_and_a_model_version_field(self) -> None: + """The usage list has an entry whose model_id is the detector's and that has a model_version field.""" + detector = self.make_detector() + for request in self._requests(): + usage = detector.detect(request).usage + matching = [u for u in usage if u.model_id == detector.model_id] + assert matching, f"no usage entry for model_id {detector.model_id!r}" + assert "model_version" in type(matching[0]).model_fields + assert hasattr(matching[0], "model_version") + + def test_tokens_and_detail_raise_where_unsupported(self) -> None: + """include_tokens / include_detail raise InvalidInputError where unsupported, and return data where supported.""" + detector = self.make_detector() + for request in self._requests(): + if detector.supports_tokens: + assert detector.detect(request, include_tokens=True).tokens is not None + assert detector.detect(request).tokens is None + else: + with pytest.raises(InvalidInputError) as exc: + detector.detect(request, include_tokens=True) + assert exc.value.param == "include_tokens" + if detector.supports_detail: + assert detector.detect(request, include_detail=True).detail is not None + assert detector.detect(request).detail is None + else: + with pytest.raises(InvalidInputError) as exc: + detector.detect(request, include_detail=True) + assert exc.value.param == "include_detail" + + # -- repeatability and side effects ---------------------------------------------------- + + def test_same_input_gives_the_same_result_also_after_other_input(self) -> None: + """A second call with the same input returns the same result, also after a call with other input.""" + detector = self.make_detector() + for request, other in [ + (self.sources_request, self.prompt_request), + (self.prompt_request, self.sources_request), + ]: + first = detector.detect(request) + assert detector.detect(request) == first + detector.detect(other) + assert detector.detect(request) == first + + def test_a_call_leaves_an_empty_cwd_and_home_empty(self) -> None: + """With an empty temporary directory as cwd and HOME, detect and adetect leave both empty.""" + detector = self.make_detector() + with _isolated_environment() as (cwd, home): + for request in self._requests(): + detector.detect(request) + asyncio.run(detector.adetect(request)) + _assert_empty(cwd, "cwd") + _assert_empty(home, "HOME") + + def test_a_call_prints_nothing_and_logs_no_text_outside_the_content_logger(self) -> None: + """A call prints nothing, and no log record outside lettucedetect.content holds answer, source or prompt text.""" + detector = self.make_detector() + recorder = _Recorder() + root = logging.getLogger() + old_level = root.level + root.addHandler(recorder) + root.setLevel(logging.DEBUG) + out, err = io.StringIO(), io.StringIO() + try: + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + for request in self._requests(): + detector.detect(request) + asyncio.run(detector.adetect(request)) + finally: + root.removeHandler(recorder) + root.setLevel(old_level) + assert out.getvalue() == "", "a call printed to stdout" + assert err.getvalue() == "", "a call printed to stderr" + texts = [text for request in self._requests() for text in _texts_of(request)] + for record in recorder.records: + if _is_content_logger(record.name): + continue + rendered = record.getMessage() + (record.exc_text or "") + for text in texts: + assert text not in rendered, f"logger {record.name!r} logged customer text" + + # -- adetect --------------------------------------------------------------------------- + + async def test_adetect_equals_detect(self) -> None: + """Adetect returns the same result as detect, for both request kinds and with min_score.""" + detector = self.make_detector() + for request in self._requests(): + assert await detector.adetect(request) == detector.detect(request) + threshold = self._distinct_scores(request)[-1] + assert await detector.adetect(request, min_score=threshold) == detector.detect( + request, min_score=threshold + ) + + async def test_adetect_runs_off_the_loop_thread_and_keeps_the_loop_free(self) -> None: + """The detector runs on a thread other than the loop's, and a loop ticker keeps ticking while it is slow.""" + thread_ids: list[int] = [] + + def slow() -> None: + thread_ids.append(threading.get_ident()) + time.sleep(_SLOW_SECONDS) + + detector = self.make_detector(on_call=slow) + ticks = 0 + + async def ticker() -> None: + nonlocal ticks + while True: + await asyncio.sleep(0.02) + ticks += 1 + + task = asyncio.create_task(ticker()) + try: + await detector.adetect(self.sources_request) + finally: + task.cancel() + assert thread_ids, "the detector never called on_call" + assert thread_ids[0] != threading.get_ident(), "the detector ran on the event loop thread" + assert ticks >= 5, f"the loop was blocked while the detector waited (ticks={ticks})" + + async def test_concurrent_adetect_returns_results_in_call_order(self) -> None: + """Concurrent adetect calls under asyncio.gather finish out of order but return results in call order.""" + scores = self._distinct_scores(self.sources_request) + thresholds = [0.0, scores[0], scores[-1]] + delays = iter([0.15, 0.08, 0.0]) + + def make_slow(delay: float) -> BaseDetector: + return self.make_detector(on_call=lambda: time.sleep(delay)) + + detectors = [make_slow(next(delays)) for _ in thresholds] + expected = [ + self.make_detector().detect(self.sources_request, min_score=t) for t in thresholds + ] + assert len({len(e.spans) for e in expected}) > 1, "the thresholds must give different results" + results = await asyncio.gather( + *( + d.adetect(self.sources_request, min_score=t) + for d, t in zip(detectors, thresholds, strict=True) + ) + ) + assert list(results) == expected + + async def test_adetect_errors_match_detect_errors(self) -> None: + """Out-of-range min_score and unsupported flags come out of the await with the same class, code and param as from detect.""" + detector = self.make_detector() + cases: list[dict] = [ + {"min_score": -0.1}, + {"min_score": 1.1}, + {"min_score": math.nan}, + ] + if not detector.supports_tokens: + cases.append({"include_tokens": True}) + if not detector.supports_detail: + cases.append({"include_detail": True}) + for kwargs in cases: + with pytest.raises(InvalidInputError) as sync_exc: + detector.detect(self.sources_request, **kwargs) + with pytest.raises(InvalidInputError) as async_exc: + await detector.adetect(self.sources_request, **kwargs) + assert type(async_exc.value) is type(sync_exc.value) + assert async_exc.value.code == sync_exc.value.code + assert async_exc.value.param == sync_exc.value.param + assert async_exc.value.param is not None + + # -- cancelling adetect ---------------------------------------------------------------- + + async def _cancel_and_check(self, cancel: Callable[[asyncio.Task[Detection]], Awaitable[None]]) -> None: + """Cancel a blocked ``adetect`` with ``cancel`` and check the detector stays usable.""" + entered, gate, returned = threading.Event(), threading.Event(), threading.Event() + loop_errors: list[dict] = [] + loop = asyncio.get_running_loop() + loop.set_exception_handler(lambda _loop, context: loop_errors.append(context)) + + def blocked() -> None: + entered.set() + gate.wait(_WAIT_SECONDS) + returned.set() + + detector = self.make_detector(on_call=blocked) + request = self.sources_request + gate.set() + baseline = detector.detect(request) + gate.clear() + entered.clear() + returned.clear() + + with _isolated_environment() as (cwd, home): + task = asyncio.create_task(detector.adetect(request)) + deadline = time.monotonic() + _WAIT_SECONDS + while not entered.is_set(): + assert time.monotonic() < deadline, "the detector never started" + await asyncio.sleep(0.005) + await cancel(task) + # The wait is over, the thread is not: it keeps running until the detector returns. + assert not returned.is_set(), "the detector stopped when the wait was cancelled" + gate.set() + while not returned.is_set(): + assert time.monotonic() < deadline, "the abandoned thread never finished" + await asyncio.sleep(0.005) + await asyncio.sleep(0.05) # let the loop see anything the thread would report + + assert detector.detect(request) == baseline + assert await detector.adetect(request) == baseline + assert loop_errors == [], f"the abandoned thread reported to the loop: {loop_errors}" + _assert_empty(cwd, "cwd") + _assert_empty(home, "HOME") + + async def test_task_cancel_leaves_the_detector_usable(self) -> None: + """After Task.cancel() on a busy adetect the thread keeps running; once it finishes the detector is valid.""" + + async def cancel(task: asyncio.Task[Detection]) -> None: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + await self._cancel_and_check(cancel) + + async def test_wait_for_timeout_leaves_the_detector_usable(self) -> None: + """After asyncio.wait_for times out on a busy adetect the thread keeps running; once it finishes the detector is valid.""" + + async def cancel(task: asyncio.Task[Detection]) -> None: + with pytest.raises(TimeoutError): + await asyncio.wait_for(task, timeout=0.05) + + await self._cancel_and_check(cancel) + + +def run_check(contract: DetectorContract, name: str) -> None: + """Run one check of a contract instance, awaiting it when it is a coroutine function.""" + method = getattr(contract, name) + if inspect.iscoroutinefunction(method): + asyncio.run(method()) + else: + method() diff --git a/tests/test_detector_contract_pytest.py b/tests/test_detector_contract_pytest.py new file mode 100644 index 0000000..b098c67 --- /dev/null +++ b/tests/test_detector_contract_pytest.py @@ -0,0 +1,283 @@ +"""Run the detector contract suite against stand-ins, good and deliberately broken.""" + +from __future__ import annotations + +import asyncio +import inspect +import logging +import time +from collections.abc import Callable +from pathlib import Path + +import pytest + +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.types import ( + Chunk, + DetectedSpan, + Detection, + PromptInput, + SourcesInput, + Usage, +) +from tests.detector_contract import CONTENT_LOGGER, DetectorContract, run_check + +ANSWER = "The capital of France is Berlin, and about 3 million people live there." +SOURCES = SourcesInput( + sources=[Chunk(id="s1", text="Paris is the capital of France and has two million people.")], + answer=ANSWER, + question="What is the capital of France?", +) +PROMPT = PromptInput(prompt="Answer from the context: Paris is the capital of France.", answer=ANSWER) + +# (word, score): three flagged words with three different scores. +FLAGGED = [("France", 0.3), ("3 million", 0.6), ("Berlin", 0.9)] + + +def _raw_spans(answer: str, shift: int = 0) -> list[dict]: + spans = [] + for word, score in FLAGGED: + start = answer.index(word) + spans.append( + {"start": start + shift, "end": start + shift + len(word), "text": word, "confidence": score} + ) + return sorted(spans, key=lambda s: s["start"]) + + +def _span(raw: dict) -> DetectedSpan: + return DetectedSpan( + start=raw["start"], end=raw["end"], text=raw["text"], score=raw["confidence"] + ) + + +class DetectOnly(BaseDetector): + """Stand-in that implements only the new ``_detect`` hook.""" + + model_id = "stand-in" + + def __init__(self, on_call: Callable[[], None] | None = None) -> None: + """Keep the hook the suite wants called.""" + self.on_call = on_call + + def _spans(self, answer: str) -> list[DetectedSpan]: + return [_span(s) for s in _raw_spans(answer)] + + def _detect(self, request, *, include_tokens, include_detail): + if self.on_call: + self.on_call() + return Detection( + spans=self._spans(request.answer), + usage=[Usage(model_id=self.model_id, model_version="1", units={})], + ) + + +class PredictOnly(BaseDetector): + """Old-style stand-in that implements only the legacy ``predict*`` methods.""" + + model_id = "legacy-stand-in" + + def __init__(self, on_call: Callable[[], None] | None = None) -> None: + """Keep the hook the suite wants called.""" + self.on_call = on_call + + def predict(self, context, answer, question=None, output_format="tokens", min_confidence=0.0): # noqa: D102 + if self.on_call: + self.on_call() + return _raw_spans(answer) + + def predict_prompt(self, prompt, answer, output_format="tokens", min_confidence=0.0): # noqa: D102 + if self.on_call: + self.on_call() + return _raw_spans(answer) + + +class TestDetectOnlyContract(DetectorContract): + """The contract holds for a detector that implements ``detect`` only.""" + + sources_request = SOURCES + prompt_request = PROMPT + + def make_detector(self, on_call=None): # noqa: D102 + return DetectOnly(on_call) + + +@pytest.mark.filterwarnings("ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning") +class TestPredictOnlyContract(DetectorContract): + """The contract holds for an old-style detector that implements ``predict`` only.""" + + sources_request = SOURCES + prompt_request = PROMPT + + def make_detector(self, on_call=None): # noqa: D102 + return PredictOnly(on_call) + + +# -- deliberately broken stand-ins: each must fail the matching check --------------------------- + + +class WrongOffsets(DetectOnly): + """Spans point one character to the right of their text.""" + + def _spans(self, answer): + return [_span(s) for s in _raw_spans(answer, shift=1)] + + +class Prints(DetectOnly): + """Prints the answer.""" + + def _detect(self, request, *, include_tokens, include_detail): + print("checking", request.answer) + return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + + +class LogsAnswer(DetectOnly): + """Logs the answer on an ordinary module logger.""" + + def _detect(self, request, *, include_tokens, include_detail): + logging.getLogger("lettucedetect.detectors.broken").info("answer: %s", request.answer) + return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + + +class LogsAnswerOnContentLogger(DetectOnly): + """Logs the answer on the one logger that may carry it; this one is allowed.""" + + def _detect(self, request, *, include_tokens, include_detail): + logging.getLogger(CONTENT_LOGGER).debug("answer: %s", request.answer) + return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + + +class WritesFileToCwd(DetectOnly): + """Writes a file in the working directory.""" + + def _detect(self, request, *, include_tokens, include_detail): + Path("scratch.txt").write_text("x") + return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + + +class WritesFileToHome(DetectOnly): + """Writes a cache file below HOME.""" + + def _detect(self, request, *, include_tokens, include_detail): + (Path.home() / ".cache-of-broken-detector").write_text("x") + return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + + +class BlocksTheLoop(DetectOnly): + """Its ``adetect`` runs the detection on the event loop's own thread.""" + + async def adetect(self, request, *, min_score=0.0, include_tokens=False, include_detail=False): # noqa: D102 + return self.detect( + request, min_score=min_score, include_tokens=include_tokens, include_detail=include_detail + ) + + +class AdetectDiffers(DetectOnly): + """Its ``adetect`` ignores ``min_score``.""" + + async def adetect(self, request, *, min_score=0.0, include_tokens=False, include_detail=False): # noqa: D102 + return await super().adetect( + request, min_score=0.0, include_tokens=include_tokens, include_detail=include_detail + ) + + +class Unrepeatable(DetectOnly): + """Gives a different score on every call.""" + + calls = 0 + + def _detect(self, request, *, include_tokens, include_detail): + type(self).calls += 1 + result = super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + bump = 0.001 * type(self).calls + spans = [s.model_copy(update={"score": min(1.0, s.score / 2 + bump)}) for s in result.spans] + return result.model_copy(update={"spans": spans}) + + +class WrongModelId(DetectOnly): + """Reports usage for a model other than its own.""" + + def _detect(self, request, *, include_tokens, include_detail): + result = super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + return result.model_copy( + update={"usage": [Usage(model_id="someone-else", model_version=None, units={})]} + ) + + +class BrokenContract(DetectorContract): + """A contract bound to one broken stand-in.""" + + sources_request = SOURCES + prompt_request = PROMPT + detector_class: type[BaseDetector] + + def make_detector(self, on_call=None): # noqa: D102 + return self.detector_class(on_call) + + +def _contract_for(detector_class: type[BaseDetector]) -> BrokenContract: + contract = BrokenContract() + contract.detector_class = detector_class + return contract + + +BROKEN = [ + (WrongOffsets, "test_span_text_equals_answer_between_offsets"), + (Prints, "test_a_call_prints_nothing_and_logs_no_text_outside_the_content_logger"), + (LogsAnswer, "test_a_call_prints_nothing_and_logs_no_text_outside_the_content_logger"), + (WritesFileToCwd, "test_a_call_leaves_an_empty_cwd_and_home_empty"), + (WritesFileToHome, "test_a_call_leaves_an_empty_cwd_and_home_empty"), + (BlocksTheLoop, "test_adetect_runs_off_the_loop_thread_and_keeps_the_loop_free"), + (AdetectDiffers, "test_adetect_equals_detect"), + (Unrepeatable, "test_same_input_gives_the_same_result_also_after_other_input"), + (WrongModelId, "test_usage_has_an_entry_with_the_model_id_and_a_model_version_field"), +] + + +@pytest.mark.parametrize(("detector_class", "check"), BROKEN, ids=lambda v: getattr(v, "__name__", v)) +def test_broken_stand_in_fails_the_matching_check(detector_class, check): + """A deliberately broken stand-in fails the check that is about its defect.""" + with pytest.raises(AssertionError): + run_check(_contract_for(detector_class), check) + + +def test_logging_on_the_content_logger_is_allowed(): + """A detector that logs the answer on lettucedetect.content passes the logging check.""" + run_check( + _contract_for(LogsAnswerOnContentLogger), + "test_a_call_prints_nothing_and_logs_no_text_outside_the_content_logger", + ) + + +def test_every_check_of_the_contract_is_covered_by_a_stand_in_in_this_file(): + """Each contract check is run by both good stand-ins; the list of checks is not empty.""" + checks = [n for n, _ in inspect.getmembers(DetectorContract) if n.startswith("test_")] + assert len(checks) >= 12 + for suite in (TestDetectOnlyContract, TestPredictOnlyContract): + for name in checks: + assert hasattr(suite, name) + + +async def test_cancelled_thread_keeps_running_until_it_finishes(): + """After Task.cancel() the worker thread is still inside the detector, and it finishes once released.""" + import threading + + entered, gate, finished = threading.Event(), threading.Event(), threading.Event() + + def blocked() -> None: + entered.set() + gate.wait(10) + finished.set() + + task = asyncio.create_task(DetectOnly(blocked).adetect(SOURCES)) + while not entered.is_set(): + await asyncio.sleep(0.005) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.sleep(0.05) + assert not finished.is_set() # the thread was not stopped by the cancel + gate.set() + deadline = time.monotonic() + 10 + while not finished.is_set() and time.monotonic() < deadline: + await asyncio.sleep(0.005) + assert finished.is_set() From 7ff39293369cd2ef20db1d4ab7b75ce31b7cfbc7 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Fri, 6 Nov 2026 15:47:25 +0100 Subject: [PATCH 18/60] chore: format with ruff --- tests/detector_contract.py | 8 +++- tests/test_detector_contract_pytest.py | 52 ++++++++++++++++++++------ 2 files changed, 46 insertions(+), 14 deletions(-) diff --git a/tests/detector_contract.py b/tests/detector_contract.py index b4877cf..d834b20 100644 --- a/tests/detector_contract.py +++ b/tests/detector_contract.py @@ -305,7 +305,9 @@ def make_slow(delay: float) -> BaseDetector: expected = [ self.make_detector().detect(self.sources_request, min_score=t) for t in thresholds ] - assert len({len(e.spans) for e in expected}) > 1, "the thresholds must give different results" + assert len({len(e.spans) for e in expected}) > 1, ( + "the thresholds must give different results" + ) results = await asyncio.gather( *( d.adetect(self.sources_request, min_score=t) @@ -338,7 +340,9 @@ async def test_adetect_errors_match_detect_errors(self) -> None: # -- cancelling adetect ---------------------------------------------------------------- - async def _cancel_and_check(self, cancel: Callable[[asyncio.Task[Detection]], Awaitable[None]]) -> None: + async def _cancel_and_check( + self, cancel: Callable[[asyncio.Task[Detection]], Awaitable[None]] + ) -> None: """Cancel a blocked ``adetect`` with ``cancel`` and check the detector stays usable.""" entered, gate, returned = threading.Event(), threading.Event(), threading.Event() loop_errors: list[dict] = [] diff --git a/tests/test_detector_contract_pytest.py b/tests/test_detector_contract_pytest.py index b098c67..537f03e 100644 --- a/tests/test_detector_contract_pytest.py +++ b/tests/test_detector_contract_pytest.py @@ -28,7 +28,9 @@ answer=ANSWER, question="What is the capital of France?", ) -PROMPT = PromptInput(prompt="Answer from the context: Paris is the capital of France.", answer=ANSWER) +PROMPT = PromptInput( + prompt="Answer from the context: Paris is the capital of France.", answer=ANSWER +) # (word, score): three flagged words with three different scores. FLAGGED = [("France", 0.3), ("3 million", 0.6), ("Berlin", 0.9)] @@ -39,7 +41,12 @@ def _raw_spans(answer: str, shift: int = 0) -> list[dict]: for word, score in FLAGGED: start = answer.index(word) spans.append( - {"start": start + shift, "end": start + shift + len(word), "text": word, "confidence": score} + { + "start": start + shift, + "end": start + shift + len(word), + "text": word, + "confidence": score, + } ) return sorted(spans, key=lambda s: s["start"]) @@ -101,7 +108,9 @@ def make_detector(self, on_call=None): # noqa: D102 return DetectOnly(on_call) -@pytest.mark.filterwarnings("ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning") +@pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) class TestPredictOnlyContract(DetectorContract): """The contract holds for an old-style detector that implements ``predict`` only.""" @@ -127,7 +136,9 @@ class Prints(DetectOnly): def _detect(self, request, *, include_tokens, include_detail): print("checking", request.answer) - return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + return super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) class LogsAnswer(DetectOnly): @@ -135,7 +146,9 @@ class LogsAnswer(DetectOnly): def _detect(self, request, *, include_tokens, include_detail): logging.getLogger("lettucedetect.detectors.broken").info("answer: %s", request.answer) - return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + return super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) class LogsAnswerOnContentLogger(DetectOnly): @@ -143,7 +156,9 @@ class LogsAnswerOnContentLogger(DetectOnly): def _detect(self, request, *, include_tokens, include_detail): logging.getLogger(CONTENT_LOGGER).debug("answer: %s", request.answer) - return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + return super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) class WritesFileToCwd(DetectOnly): @@ -151,7 +166,9 @@ class WritesFileToCwd(DetectOnly): def _detect(self, request, *, include_tokens, include_detail): Path("scratch.txt").write_text("x") - return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + return super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) class WritesFileToHome(DetectOnly): @@ -159,7 +176,9 @@ class WritesFileToHome(DetectOnly): def _detect(self, request, *, include_tokens, include_detail): (Path.home() / ".cache-of-broken-detector").write_text("x") - return super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + return super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) class BlocksTheLoop(DetectOnly): @@ -167,7 +186,10 @@ class BlocksTheLoop(DetectOnly): async def adetect(self, request, *, min_score=0.0, include_tokens=False, include_detail=False): # noqa: D102 return self.detect( - request, min_score=min_score, include_tokens=include_tokens, include_detail=include_detail + request, + min_score=min_score, + include_tokens=include_tokens, + include_detail=include_detail, ) @@ -187,7 +209,9 @@ class Unrepeatable(DetectOnly): def _detect(self, request, *, include_tokens, include_detail): type(self).calls += 1 - result = super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + result = super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) bump = 0.001 * type(self).calls spans = [s.model_copy(update={"score": min(1.0, s.score / 2 + bump)}) for s in result.spans] return result.model_copy(update={"spans": spans}) @@ -197,7 +221,9 @@ class WrongModelId(DetectOnly): """Reports usage for a model other than its own.""" def _detect(self, request, *, include_tokens, include_detail): - result = super()._detect(request, include_tokens=include_tokens, include_detail=include_detail) + result = super()._detect( + request, include_tokens=include_tokens, include_detail=include_detail + ) return result.model_copy( update={"usage": [Usage(model_id="someone-else", model_version=None, units={})]} ) @@ -233,7 +259,9 @@ def _contract_for(detector_class: type[BaseDetector]) -> BrokenContract: ] -@pytest.mark.parametrize(("detector_class", "check"), BROKEN, ids=lambda v: getattr(v, "__name__", v)) +@pytest.mark.parametrize( + ("detector_class", "check"), BROKEN, ids=lambda v: getattr(v, "__name__", v) +) def test_broken_stand_in_fails_the_matching_check(detector_class, check): """A deliberately broken stand-in fails the check that is about its defect.""" with pytest.raises(AssertionError): From 65f4bf37f78b9d71d1485d68281d252515b83cf7 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 09:36:33 +0100 Subject: [PATCH 19/60] feat: add ResponseCache protocol, make_cache_key, SyncCacheBase and InMemoryCache (#145) --- lettucedetect/detectors/__init__.py | 12 +- lettucedetect/detectors/response_cache.py | 196 +++++++++++++ tests/cache_contract.py | 342 ++++++++++++++++++++++ tests/test_cache_contract_pytest.py | 280 ++++++++++++++++++ tests/test_response_cache_pytest.py | 128 ++++++++ 5 files changed, 957 insertions(+), 1 deletion(-) create mode 100644 lettucedetect/detectors/response_cache.py create mode 100644 tests/cache_contract.py create mode 100644 tests/test_cache_contract_pytest.py create mode 100644 tests/test_response_cache_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index a08a94d..1511775 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -11,6 +11,12 @@ from lettucedetect.detectors.factory import make_detector as _make_detector from lettucedetect.detectors.llm import LLMDetector from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector +from lettucedetect.detectors.response_cache import ( + InMemoryCache, + ResponseCache, + SyncCacheBase, + make_cache_key, +) from lettucedetect.detectors.transformer import TransformerDetector from lettucedetect.detectors.types import ( Chunk, @@ -34,18 +40,22 @@ "DetectRequest", "DetectedSpan", "Detection", + "InMemoryCache", "InvalidInputError", "LLMDetector", + "LettuceDetectDeprecationWarning", "LettuceDetectError", "PromptInput", - "LettuceDetectDeprecationWarning", "RAGFactCheckerDetector", + "ResponseCache", "ResultWarning", "SourcesInput", "Span", + "SyncCacheBase", "TokenScore", "TransformerDetector", "UpstreamError", "Usage", "_make_detector", + "make_cache_key", ] diff --git a/lettucedetect/detectors/response_cache.py b/lettucedetect/detectors/response_cache.py new file mode 100644 index 0000000..ddeb759 --- /dev/null +++ b/lettucedetect/detectors/response_cache.py @@ -0,0 +1,196 @@ +"""The ``ResponseCache`` protocol, the cache key function and an in-memory backend. + +A service that wants to cache LLM replies implements :class:`ResponseCache`. Backends that only +have synchronous storage subclass :class:`SyncCacheBase` and get the async methods for free. +:class:`InMemoryCache` is the simplest backend. + +New error codes (public API, do not rename): + +- ``invalid_cache_kind``: ``kind`` of :func:`make_cache_key` is not ``"judge"``, ``"native"`` + or ``"verify"``. +- ``invalid_ttl_seconds``: ``ttl_seconds`` is not a positive, finite number. +""" + +from __future__ import annotations + +import abc +import asyncio +import logging +import math +import threading +import time +from typing import Literal, Protocol, runtime_checkable + +from lettucedetect.detectors.cache import CacheManager +from lettucedetect.detectors.errors import InvalidInputError + +logger = logging.getLogger(__name__) + +CacheKind = Literal["judge", "native", "verify"] +_KINDS = ("judge", "native", "verify") + + +@runtime_checkable +class ResponseCache(Protocol): + """A key-value store for model replies. + + Keys are opaque strings and values are strings. A missing or expired key reads as ``None``. + Deleting a missing key does nothing. Each ``a...`` method takes the same arguments as its + synchronous pair and returns the same value. + + ``isinstance(obj, ResponseCache)`` only checks that the six names exist. The reusable suite in + ``tests/cache_contract.py`` checks the rest, such as that the ``a...`` methods are coroutine + functions. + """ + + def get(self, key: str) -> str | None: + """Return the value stored under ``key``, or ``None`` if it is missing or expired.""" + ... + + def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: + """Store ``value`` under ``key``; it expires after ``ttl_seconds`` (``None``: never).""" + ... + + def delete(self, key: str) -> None: + """Remove ``key``. Does nothing if the key is missing.""" + ... + + async def aget(self, key: str) -> str | None: + """Async pair of :meth:`get`.""" + ... + + async def aset(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: + """Async pair of :meth:`set`.""" + ... + + async def adelete(self, key: str) -> None: + """Async pair of :meth:`delete`.""" + ... + + +def make_cache_key( + prompt: str, + model: str, + model_version: str | None, + temperature: float, + kind: CacheKind, +) -> str: + """Build the cache key of one model call. + + With ``model_version=None`` the key equals the key ``LLMDetector`` builds today, so existing + cache files stay valid. With a version, a ``model_version=`` part is added, so a + redeployed model does not read the replies of the old one. + + :param prompt: The full text sent to the model. + :param model: The model name. + :param model_version: A version or deployment id of the model, or ``None``. + :param temperature: The sampling temperature. + :param kind: ``"judge"``, ``"native"`` or ``"verify"``. + :returns: A SHA-256 hex digest. + :raises InvalidInputError: ``kind`` is not one of the three values (``invalid_cache_kind``). + """ + if kind not in _KINDS: + raise InvalidInputError( + f"kind must be one of {', '.join(_KINDS)}.", + code="invalid_cache_kind", + param="kind", + ) + parts = [prompt, model, str(temperature)] + if kind != "judge": # today's judge key has no kind part + parts.append(kind) + if model_version is not None: + # Prefixed, so a version can never read as a kind ("native") and collide with its key. + parts.append(f"model_version={model_version}") + return CacheManager._hash(*parts) + + +class SyncCacheBase(abc.ABC): + """Base class for backends that only have synchronous storage. + + Implement :meth:`get`, :meth:`set` and :meth:`delete`. The base supplies :meth:`aget`, + :meth:`aset` and :meth:`adelete` by running them in a worker thread, so the event loop stays + free while storage blocks. + + Cancelling an ``a...`` call stops the wait, not the thread: the storage call still finishes. + So ``set`` and ``delete`` must be atomic, and a cancelled ``aset`` may still land. + + A backend does not have to use this class. Any class that implements :class:`ResponseCache` + works. + """ + + @abc.abstractmethod + def get(self, key: str) -> str | None: + """Return the value stored under ``key``, or ``None`` if it is missing or expired.""" + + @abc.abstractmethod + def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: + """Store ``value`` under ``key``; it expires after ``ttl_seconds`` (``None``: never).""" + + @abc.abstractmethod + def delete(self, key: str) -> None: + """Remove ``key``. Does nothing if the key is missing.""" + + async def aget(self, key: str) -> str | None: + """Run :meth:`get` in a worker thread.""" + return await asyncio.to_thread(self.get, key) + + async def aset(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: + """Run :meth:`set` in a worker thread.""" + await asyncio.to_thread(self.set, key, value, ttl_seconds=ttl_seconds) + + async def adelete(self, key: str) -> None: + """Run :meth:`delete` in a worker thread.""" + await asyncio.to_thread(self.delete, key) + + +class InMemoryCache(SyncCacheBase): + """A thread-safe cache in process memory, with a time to live per entry. + + Entries are lost when the process ends. There is no size limit: expired entries are removed + when they are read, and the cache grows with the number of distinct keys. + """ + + def __init__(self) -> None: + """Create an empty cache.""" + self._lock = threading.Lock() + self._data: dict[str, tuple[str, float | None]] = {} + + def get(self, key: str) -> str | None: + """Return the value stored under ``key``, or ``None`` if it is missing or expired.""" + with self._lock: + entry = self._data.get(key) + if entry is None: + return None + value, deadline = entry + if deadline is not None and time.monotonic() >= deadline: + del self._data[key] + return None + return value + + def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: + """Store ``value`` under ``key``, replacing the value and the deadline of an older entry. + + :raises InvalidInputError: ``ttl_seconds`` is not a positive, finite number + (``invalid_ttl_seconds``). + """ + deadline = None + if ttl_seconds is not None: + if ( + isinstance(ttl_seconds, bool) + or not isinstance(ttl_seconds, (int, float)) + or not math.isfinite(ttl_seconds) + or ttl_seconds <= 0 + ): + raise InvalidInputError( + "ttl_seconds must be a positive, finite number, or None for no expiry.", + code="invalid_ttl_seconds", + param="ttl_seconds", + ) + deadline = time.monotonic() + ttl_seconds + with self._lock: + self._data[key] = (value, deadline) + + def delete(self, key: str) -> None: + """Remove ``key``. Does nothing if the key is missing.""" + with self._lock: + self._data.pop(key, None) diff --git a/tests/cache_contract.py b/tests/cache_contract.py new file mode 100644 index 0000000..c26073f --- /dev/null +++ b/tests/cache_contract.py @@ -0,0 +1,342 @@ +"""Reusable contract suite that every ``ResponseCache`` backend must pass. + +The suite reads the public behaviour of a cache and nothing else, so it does not care how a +backend stores its data. ``InMemoryCache`` runs it, and so does every later backend (``FileCache``). + +How a backend task plugs in +=========================== + +1. Subclass :class:`CacheContract` inside a ``tests/test_*_pytest.py`` file. The base class is not + collected by pytest itself, only your ``Test...`` subclass is:: + + from tests.cache_contract import CacheContract + + class TestMyCacheContract(CacheContract): + def make_cache(self, on_call=None): + return MyCache(on_call=on_call) + +2. Implement ``make_cache(on_call)``. It returns a fresh, empty cache that works offline. When + ``on_call`` is not ``None``, the cache must call ``on_call()`` once per storage operation + (``get``, ``set`` or ``delete``), on the thread that runs the operation, before it touches its + storage. The suite uses it to make a backend slow, to see which thread runs it, and to block it + on an event. A backend with native async storage calls it from its async methods too (from a + worker thread or any other way that keeps the loop free). +3. Every check is a plain method without pytest fixtures, so ``tests/test_cache_contract_pytest.py`` + can also run a check against a deliberately broken backend and assert that it fails. + +About cancelling ``aset`` +========================= + +Cancelling the awaiting task of a ``SyncCacheBase`` backend stops the wait only. The storage call +keeps running until it returns, because Python cannot stop a thread. So the cancel check does not +say which of the two values wins. It says that the key reads as the old value or the new one, at +every moment, and that the cache works afterwards. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import inspect +import threading +import time +from collections.abc import Awaitable +from concurrent.futures import ThreadPoolExecutor +from typing import Callable + +from lettucedetect.detectors.response_cache import ResponseCache + +_PAIRS = (("get", "aget"), ("set", "aset"), ("delete", "adelete")) +_WAIT_SECONDS = 10.0 +_TTL = 0.2 +_AFTER_TTL = 0.4 +_SLOW_SECONDS = 0.3 + + +class CacheProbe: + """The ``on_call`` hook. It records the thread of each call, and can delay or block a call.""" + + def __init__(self) -> None: + """Create a probe that records only.""" + self.delay = 0.0 + self.threads: list[int] = [] + self.entered = threading.Event() + self._gate: threading.Event | None = None + + def block_next(self, gate: threading.Event) -> None: + """Make the next call wait until ``gate`` is set.""" + self.entered.clear() + self._gate = gate + + def __call__(self) -> None: + """Record the thread, then wait as armed.""" + self.threads.append(threading.get_ident()) + gate, self._gate = self._gate, None + self.entered.set() + if gate is not None: + assert gate.wait(_WAIT_SECONDS), "the probe was never released" + if self.delay: + time.sleep(self.delay) + + +async def _count_ticks(awaitable: Awaitable[object]) -> int: + """Await ``awaitable`` while a ticker runs on the loop; return how often it ticked.""" + ticks = 0 + + async def ticker() -> None: + nonlocal ticks + while True: + await asyncio.sleep(0.01) + ticks += 1 + + task = asyncio.create_task(ticker()) + try: + await awaitable + finally: + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + return ticks + + +class CacheContract: + """The checks every cache backend must pass. Subclass it and implement ``make_cache``.""" + + def make_cache(self, on_call: Callable[[], None] | None = None) -> ResponseCache: + """Return a fresh cache that calls ``on_call()`` once per storage operation.""" + raise NotImplementedError + + # -- the protocol ----------------------------------------------------------------------- + + def test_protocol_shape(self) -> None: + """Each ``a...`` method is a coroutine function with the arguments of its sync pair.""" + cache = self.make_cache() + for sync_name, async_name in _PAIRS: + assert hasattr(cache, sync_name), f"the cache has no {sync_name}" + assert hasattr(cache, async_name), f"the cache has no {async_name}" + sync_method = getattr(cache, sync_name) + async_method = getattr(cache, async_name) + assert inspect.iscoroutinefunction(async_method), f"{async_name} is not async def" + sync_params = [ + (p.name, p.kind, p.default) + for p in inspect.signature(sync_method).parameters.values() + ] + async_params = [ + (p.name, p.kind, p.default) + for p in inspect.signature(async_method).parameters.values() + ] + assert async_params == sync_params, ( + f"{async_name}{inspect.signature(async_method)} differs from " + f"{sync_name}{inspect.signature(sync_method)}" + ) + ttl = inspect.signature(cache.set).parameters["ttl_seconds"] + assert ttl.kind is inspect.Parameter.KEYWORD_ONLY, "ttl_seconds must be keyword-only" + assert ttl.default is None, "ttl_seconds must default to None" + + # -- sync behaviour --------------------------------------------------------------------- + + def test_value_reads_back(self) -> None: + """A stored value reads back unchanged, including non-ASCII text.""" + cache = self.make_cache() + cache.set("k", 'héllo ✓\n"quoted"') + assert cache.get("k") == 'héllo ✓\n"quoted"' + + def test_empty_string_is_a_value(self) -> None: + """An empty string is stored and read back; only a missing key is ``None``.""" + cache = self.make_cache() + cache.set("k", "") + assert cache.get("k") == "" + + def test_missing_key_is_none(self) -> None: + """A key that was never set reads as ``None``.""" + assert self.make_cache().get("missing") is None + + def test_overwrite(self) -> None: + """A second ``set`` replaces the first value.""" + cache = self.make_cache() + cache.set("k", "one") + cache.set("k", "two") + assert cache.get("k") == "two" + + def test_delete(self) -> None: + """``delete`` removes a key and leaves the others.""" + cache = self.make_cache() + cache.set("a", "1") + cache.set("b", "2") + cache.delete("a") + assert cache.get("a") is None + assert cache.get("b") == "2" + + def test_delete_missing_key_does_nothing(self) -> None: + """Deleting a missing key is not an error.""" + cache = self.make_cache() + cache.delete("missing") + assert cache.get("missing") is None + + def test_ttl_expires(self) -> None: + """A value with a TTL reads back at first and as ``None`` after the TTL.""" + cache = self.make_cache() + cache.set("k", "v", ttl_seconds=_TTL) + assert cache.get("k") == "v" + time.sleep(_AFTER_TTL) + assert cache.get("k") is None + + def test_no_ttl_never_expires(self) -> None: + """A value without a TTL is still there after the time a TTL value would have expired.""" + cache = self.make_cache() + cache.set("k", "v") + cache.set("other", "w", ttl_seconds=_TTL) + time.sleep(_AFTER_TTL) + assert cache.get("other") is None + assert cache.get("k") == "v" + + def test_set_without_ttl_clears_the_old_deadline(self) -> None: + """Overwriting a value that has a TTL with one that has none removes the deadline.""" + cache = self.make_cache() + cache.set("k", "old", ttl_seconds=_TTL) + cache.set("k", "new") + time.sleep(_AFTER_TTL) + assert cache.get("k") == "new" + + def test_a_new_ttl_replaces_the_old_deadline(self) -> None: + """Overwriting a value that has a short TTL with a longer one keeps it past the first.""" + cache = self.make_cache() + cache.set("k", "old", ttl_seconds=_TTL) + cache.set("k", "new", ttl_seconds=60) + time.sleep(_AFTER_TTL) + assert cache.get("k") == "new" + + # -- async behaviour -------------------------------------------------------------------- + + async def test_async_methods_work(self) -> None: + """``aset``, ``aget`` and ``adelete`` store, read and remove a value.""" + cache = self.make_cache() + assert await cache.aget("k") is None + await cache.aset("k", "v") + assert await cache.aget("k") == "v" + await cache.adelete("k") + assert await cache.aget("k") is None + await cache.adelete("k") + + async def test_each_sync_method_equals_its_async_pair(self) -> None: + """For the same state, a sync method and its async pair return the same value.""" + cache = self.make_cache() + cache.set("k", "v") + assert cache.get("k") == await cache.aget("k") == "v" + assert cache.get("missing") is None + assert await cache.aget("missing") is None + assert cache.set("a", "1") is None + assert await cache.aset("b", "2") is None + assert cache.delete("a") is None + assert await cache.adelete("b") is None + assert cache.get("a") is None + assert cache.get("b") is None + cache.set("c", "") + assert cache.get("c") == await cache.aget("c") == "" + + async def test_aset_with_ttl_expires_like_set(self) -> None: + """``aset(..., ttl_seconds=...)`` expires like ``set``, seen through both read methods.""" + cache = self.make_cache() + await cache.aset("k", "v", ttl_seconds=_TTL) + assert await cache.aget("k") == "v" + assert cache.get("k") == "v" + await asyncio.sleep(_AFTER_TTL) + assert await cache.aget("k") is None + assert cache.get("k") is None + + async def test_value_written_by_set_reads_via_aget_and_the_reverse(self) -> None: + """The sync and async methods share one storage.""" + cache = self.make_cache() + cache.set("sync", "from set") + assert await cache.aget("sync") == "from set" + await cache.aset("async", "from aset") + assert cache.get("async") == "from aset" + await cache.aset("sync", "replaced") + assert cache.get("sync") == "replaced" + cache.delete("async") + assert await cache.aget("async") is None + + async def test_async_methods_run_off_the_loop_thread(self) -> None: + """The storage work of every async method runs on a thread other than the loop's.""" + probe = CacheProbe() + cache = self.make_cache(probe) + cache.set("k", "v") + probe.threads.clear() + await cache.aget("k") + await cache.aset("k2", "v") + await cache.adelete("k") + assert len(probe.threads) == 3, "the cache must call on_call once per storage operation" + assert threading.get_ident() not in probe.threads, "an async method ran on the loop thread" + + async def test_loop_keeps_running_while_an_async_method_waits(self) -> None: + """A slow storage call does not stop other tasks on the loop (the ticker keeps ticking).""" + probe = CacheProbe() + cache = self.make_cache(probe) + cache.set("k", "v") + probe.delay = _SLOW_SECONDS + calls = { + "aget": lambda: cache.aget("k"), + "aset": lambda: cache.aset("k2", "v"), + "adelete": lambda: cache.adelete("k"), + } + for name, call in calls.items(): + ticks = await _count_ticks(call()) + assert ticks >= 5, f"the loop was blocked while {name} waited ({ticks} ticks)" + + async def test_cancelled_aset_leaves_the_cache_valid(self) -> None: + """After cancelling an ``aset``, the key is the old value or the new one, never else.""" + probe = CacheProbe() + cache = self.make_cache(probe) + cache.set("k", "old value") + gate = threading.Event() + probe.block_next(gate) + task = asyncio.create_task(cache.aset("k", "new value")) + assert await asyncio.to_thread(probe.entered.wait, _WAIT_SECONDS), "aset never started" + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + try: + # The storage call is still blocked: the cache is in the middle of the write. + assert cache.get("k") in ("old value", "new value") + finally: + gate.set() + await asyncio.sleep(0.2) # the storage call finishes: nothing stops a thread + assert cache.get("k") in ("old value", "new value") + cache.set("k", "later") + assert cache.get("k") == "later" + await cache.aset("other", "value") + assert await cache.aget("other") == "value" + + # -- concurrency ------------------------------------------------------------------------ + + def test_concurrent_threads_lose_no_key(self) -> None: + """Writers on several threads, each with its own keys, lose none of them.""" + cache = self.make_cache() + writers, per_writer = 8, 25 + + def write(writer: int) -> None: + for i in range(per_writer): + cache.set(f"k{writer}-{i}", f"v{writer}-{i}") + + with ThreadPoolExecutor(max_workers=writers) as pool: + list(pool.map(write, range(writers))) + for writer in range(writers): + for i in range(per_writer): + assert cache.get(f"k{writer}-{i}") == f"v{writer}-{i}", f"lost k{writer}-{i}" + + async def test_concurrent_aset_over_gather_loses_no_key(self) -> None: + """Many ``aset`` calls awaited together with ``asyncio.gather`` lose no key.""" + cache = self.make_cache() + count = 200 + await asyncio.gather(*(cache.aset(f"k{i}", f"v{i}") for i in range(count))) + values = await asyncio.gather(*(cache.aget(f"k{i}") for i in range(count))) + assert values == [f"v{i}" for i in range(count)] + + +def run_check(contract: CacheContract, name: str) -> None: + """Run one check of a contract instance, awaiting it when it is a coroutine function.""" + method = getattr(contract, name) + if inspect.iscoroutinefunction(method): + asyncio.run(method()) + else: + method() diff --git a/tests/test_cache_contract_pytest.py b/tests/test_cache_contract_pytest.py new file mode 100644 index 0000000..69923d6 --- /dev/null +++ b/tests/test_cache_contract_pytest.py @@ -0,0 +1,280 @@ +"""Run the cache contract suite against good backends and deliberately broken ones.""" + +from __future__ import annotations + +import asyncio +import threading +import time +from collections.abc import Callable + +import pytest + +from lettucedetect.detectors import InMemoryCache, ResponseCache, SyncCacheBase +from tests.cache_contract import CacheContract, run_check + +Hook = Callable[[], None] | None + + +class HookedInMemoryCache(InMemoryCache): + """``InMemoryCache`` that calls the contract's ``on_call`` before each storage operation.""" + + def __init__(self, on_call: Hook = None) -> None: + """Create the cache.""" + super().__init__() + self._on_call = on_call + + def get(self, key): + """Call the hook, then read.""" + if self._on_call: + self._on_call() + return super().get(key) + + def set(self, key, value, *, ttl_seconds=None): + """Call the hook, then write.""" + if self._on_call: + self._on_call() + super().set(key, value, ttl_seconds=ttl_seconds) + + def delete(self, key): + """Call the hook, then delete.""" + if self._on_call: + self._on_call() + super().delete(key) + + +class DictBackend(SyncCacheBase): + """A backend that implements only ``get``, ``set`` and ``delete`` on ``SyncCacheBase``.""" + + def __init__(self, on_call: Hook = None) -> None: + """Create the backend.""" + self._data: dict[str, tuple[str, float | None]] = {} + self._lock = threading.Lock() + self._on_call = on_call + + def _hook(self) -> None: + if self._on_call: + self._on_call() + + def get(self, key): + """Return the value, or ``None`` when it is missing or expired.""" + self._hook() + with self._lock: + entry = self._data.get(key) + if entry is None: + return None + value, deadline = entry + if deadline is not None and time.monotonic() >= deadline: + return None + return value + + def set(self, key, value, *, ttl_seconds=None): + """Store the value.""" + self._hook() + deadline = None if ttl_seconds is None else time.monotonic() + ttl_seconds + with self._lock: + self._data[key] = (value, deadline) + + def delete(self, key): + """Remove the key.""" + self._hook() + with self._lock: + self._data.pop(key, None) + + +class NativeAsyncCache: + """Implements the protocol directly, with no ``SyncCacheBase``: async storage of its own.""" + + def __init__(self, on_call: Hook = None) -> None: + """Create the cache.""" + self._inner = DictBackend(on_call) + self._on_call = on_call + + def get(self, key): + """Read synchronously.""" + return self._inner.get(key) + + def set(self, key, value, *, ttl_seconds=None): + """Write synchronously.""" + self._inner.set(key, value, ttl_seconds=ttl_seconds) + + def delete(self, key): + """Delete synchronously.""" + self._inner.delete(key) + + async def aget(self, key): + """Read; the blocking part runs off the loop.""" + return await asyncio.to_thread(self._inner.get, key) + + async def aset(self, key, value, *, ttl_seconds=None): + """Write; the blocking part runs off the loop.""" + await asyncio.to_thread(self._inner.set, key, value, ttl_seconds=ttl_seconds) + + async def adelete(self, key): + """Delete; the blocking part runs off the loop.""" + await asyncio.to_thread(self._inner.delete, key) + + +class TestInMemoryCacheContract(CacheContract): + """``InMemoryCache`` passes the whole suite.""" + + def make_cache(self, on_call=None): + """Make cache.""" + return HookedInMemoryCache(on_call) + + +class TestSyncCacheBaseContract(CacheContract): + """A backend with only ``get``, ``set`` and ``delete`` passes, async methods included.""" + + def make_cache(self, on_call=None): + """Make cache.""" + return DictBackend(on_call) + + def test_backend_defines_no_async_method_of_its_own(self): + """Backend defines no async method of its own.""" + for name in ("aget", "aset", "adelete"): + assert name not in vars(DictBackend) + assert name in vars(SyncCacheBase) + + +class TestDirectProtocolContract(CacheContract): + """A class that implements the protocol directly is not forced to use ``SyncCacheBase``.""" + + def make_cache(self, on_call=None): + """Make cache.""" + return NativeAsyncCache(on_call) + + def test_is_a_response_cache_without_the_base(self): + """Is a response cache without the base.""" + assert isinstance(NativeAsyncCache(), ResponseCache) + assert not issubclass(NativeAsyncCache, SyncCacheBase) + + +# -- deliberately broken backends: each must fail the matching check ------------------------- + + +class MissingAget(DictBackend): + """Has no ``aget`` at all.""" + + @property + def aget(self): + """Aget.""" + raise AttributeError("aget") + + +class SyncAset(DictBackend): + """``aset`` is a plain ``def`` that blocks the loop.""" + + def aset(self, key, value, *, ttl_seconds=None): + """Aset.""" + self.set(key, value, ttl_seconds=ttl_seconds) + + +class AsetWithoutTtl(DictBackend): + """``aset`` has no ``ttl_seconds`` argument.""" + + async def aset(self, key, value): + """Aset.""" + await asyncio.to_thread(self.set, key, value) + + +class AsetIgnoresTtl(DictBackend): + """``aset`` accepts ``ttl_seconds`` and drops it.""" + + async def aset(self, key, value, *, ttl_seconds=None): + """Aset.""" + await asyncio.to_thread(self.set, key, value) + + +class ExpiredStillReads(DictBackend): + """``get`` ignores the deadline.""" + + def get(self, key): + """Get.""" + self._hook() + entry = self._data.get(key) + return None if entry is None else entry[0] + + +class MissingAsEmpty(DictBackend): + """``aget`` returns ``""`` for a missing key, ``get`` returns ``None``.""" + + async def aget(self, key): + """Aget.""" + return await asyncio.to_thread(self.get, key) or "" + + +class OnLoop(DictBackend): + """The async methods run the storage call on the event loop's thread.""" + + async def aget(self, key): + """Aget.""" + return self.get(key) + + async def aset(self, key, value, *, ttl_seconds=None): + """Aset.""" + self.set(key, value, ttl_seconds=ttl_seconds) + + async def adelete(self, key): + """Adelete.""" + self.delete(key) + + +class LostUpdates(DictBackend): + """``set`` copies the dict, yields, and writes the copy back: writers overwrite each other.""" + + def set(self, key, value, *, ttl_seconds=None): + """Set.""" + self._hook() + snapshot = dict(self._data) + time.sleep(0.001) + snapshot[key] = (value, None if ttl_seconds is None else time.monotonic() + ttl_seconds) + self._data = snapshot + + +class PartialWrite(DictBackend): + """``set`` stores a half-written value, then does the slow part, then the real value.""" + + def set(self, key, value, *, ttl_seconds=None): + """Set.""" + with self._lock: + self._data[key] = (value[: len(value) // 2], None) + self._hook() + super().set(key, value, ttl_seconds=ttl_seconds) + + +def _contract_of(factory: Callable[[Hook], object]) -> CacheContract: + class Broken(CacheContract): + def make_cache(self, on_call=None): + return factory(on_call) + + return Broken() + + +BROKEN = [ + (MissingAget, "test_protocol_shape"), + (SyncAset, "test_protocol_shape"), + (AsetWithoutTtl, "test_protocol_shape"), + (AsetIgnoresTtl, "test_aset_with_ttl_expires_like_set"), + (ExpiredStillReads, "test_ttl_expires"), + (MissingAsEmpty, "test_each_sync_method_equals_its_async_pair"), + (OnLoop, "test_async_methods_run_off_the_loop_thread"), + (OnLoop, "test_loop_keeps_running_while_an_async_method_waits"), + (LostUpdates, "test_concurrent_threads_lose_no_key"), + (LostUpdates, "test_concurrent_aset_over_gather_loses_no_key"), + (PartialWrite, "test_cancelled_aset_leaves_the_cache_valid"), +] + + +@pytest.mark.parametrize(("backend", "check"), BROKEN, ids=[f"{b.__name__}-{c}" for b, c in BROKEN]) +def test_broken_backend_fails_the_matching_check(backend, check): + """Each stand-in breaks one rule, and the suite must notice.""" + with pytest.raises(AssertionError): + run_check(_contract_of(backend), check) + + +@pytest.mark.parametrize("backend", [HookedInMemoryCache, DictBackend, NativeAsyncCache]) +def test_good_backend_passes_every_check_through_run_check(backend): + """``run_check`` runs sync and async checks alike.""" + contract = _contract_of(backend) + run_check(contract, "test_protocol_shape") + run_check(contract, "test_async_methods_work") diff --git a/tests/test_response_cache_pytest.py b/tests/test_response_cache_pytest.py new file mode 100644 index 0000000..a745199 --- /dev/null +++ b/tests/test_response_cache_pytest.py @@ -0,0 +1,128 @@ +"""Tests for ``make_cache_key``, ``InMemoryCache`` specifics and the public exports.""" + +from __future__ import annotations + +import math + +import pytest + +import lettucedetect.detectors as detectors +from lettucedetect.detectors import ( + InMemoryCache, + InvalidInputError, + ResponseCache, + SyncCacheBase, + make_cache_key, +) +from lettucedetect.detectors.cache import CacheManager +from tests.golden import GOLDEN_DIR + +KINDS = ("judge", "native", "verify") + + +def _recorded() -> dict[str, str]: + import json + + return json.loads((GOLDEN_DIR / "cache_hash_strings.json").read_text(encoding="utf-8")) + + +class TestMakeCacheKey: + """The key function reproduces today's keys and adds the model version.""" + + @pytest.mark.parametrize("kind", KINDS) + def test_without_version_equals_the_recorded_key(self, kind): + """``model_version=None`` gives the key recorded by the golden tests (#131).""" + assert make_cache_key("prompt", "gpt-4.1-mini", None, 0.0, kind) == _recorded()[kind] + + def test_without_version_equals_the_inline_hash_of_the_detector(self): + """Same parts, same hash as the inline ``CacheManager._hash`` calls in ``llm.py``.""" + assert make_cache_key("p", "m", None, 0.5, "judge") == CacheManager._hash("p", "m", "0.5") + assert make_cache_key("p", "m", None, 0.5, "native") == CacheManager._hash( + "p", "m", "0.5", "native" + ) + assert make_cache_key("p", "m", None, 0.5, "verify") == CacheManager._hash( + "p", "m", "0.5", "verify" + ) + + @pytest.mark.parametrize("kind", KINDS) + def test_a_version_changes_the_key(self, kind): + """A version differs from no version, and two versions differ from each other.""" + none = make_cache_key("p", "m", None, 0.0, kind) + v1 = make_cache_key("p", "m", "v1", 0.0, kind) + v2 = make_cache_key("p", "m", "v2", 0.0, kind) + assert len({none, v1, v2}) == 3 + + def test_the_same_version_gives_the_same_key(self): + """The same version gives the same key.""" + assert make_cache_key("p", "m", "v1", 0.0, "judge") == make_cache_key( + "p", "m", "v1", 0.0, "judge" + ) + + def test_a_version_cannot_forge_a_kind(self): + """A judge key with version ``"native"`` is not the native key without a version.""" + assert make_cache_key("p", "m", "native", 0.0, "judge") != make_cache_key( + "p", "m", None, 0.0, "native" + ) + + def test_unknown_kind_raises_a_typed_error(self): + """Unknown kind raises a typed error.""" + with pytest.raises(InvalidInputError) as info: + make_cache_key("p", "m", None, 0.0, "other") # type: ignore[arg-type] + assert info.value.code == "invalid_cache_kind" + assert info.value.param == "kind" + + +class TestInMemoryCacheTtl: + """``ttl_seconds`` must be a positive, finite number.""" + + @pytest.mark.parametrize("ttl", [0, -1, 0.0, math.nan, math.inf, -math.inf]) + def test_bad_ttl_raises_and_stores_nothing(self, ttl): + """Bad ttl raises and stores nothing.""" + cache = InMemoryCache() + with pytest.raises(InvalidInputError) as info: + cache.set("k", "v", ttl_seconds=ttl) + assert info.value.code == "invalid_ttl_seconds" + assert info.value.param == "ttl_seconds" + assert cache.get("k") is None + + @pytest.mark.parametrize("ttl", [True, "5"]) + def test_non_numbers_raise(self, ttl): + """Non numbers raise.""" + with pytest.raises(InvalidInputError): + InMemoryCache().set("k", "v", ttl_seconds=ttl) # type: ignore[arg-type] + + async def test_aset_validates_like_set(self): + """Aset validates like set.""" + cache = InMemoryCache() + with pytest.raises(InvalidInputError) as info: + await cache.aset("k", "v", ttl_seconds=0) + assert info.value.code == "invalid_ttl_seconds" + + +class TestExports: + """The protocol, key function and both cache classes are public.""" + + def test_names_are_exported(self): + """Names are exported.""" + for name in ("ResponseCache", "make_cache_key", "SyncCacheBase", "InMemoryCache"): + assert name in detectors.__all__ + assert hasattr(detectors, name) + + def test_in_memory_cache_follows_the_protocol(self): + """In memory cache follows the protocol.""" + assert isinstance(InMemoryCache(), ResponseCache) + assert issubclass(InMemoryCache, SyncCacheBase) + + def test_the_protocol_does_not_force_the_base_class(self): + """A class that has the six methods is a ``ResponseCache`` without ``SyncCacheBase``.""" + + class Direct: + def get(self, key): ... + def set(self, key, value, *, ttl_seconds=None): ... + def delete(self, key): ... + async def aget(self, key): ... + async def aset(self, key, value, *, ttl_seconds=None): ... + async def adelete(self, key): ... + + assert isinstance(Direct(), ResponseCache) + assert not issubclass(Direct, SyncCacheBase) From 2917422841494e9aed8e32b74360c428267ca58a Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 10:31:59 +0100 Subject: [PATCH 20/60] feat: add FileCache with atomic writes and TTL (#146) --- lettucedetect/detectors/__init__.py | 2 + lettucedetect/detectors/file_cache.py | 163 ++++++++++ lettucedetect/detectors/response_cache.py | 33 +- tests/test_file_cache_pytest.py | 379 ++++++++++++++++++++++ 4 files changed, 563 insertions(+), 14 deletions(-) create mode 100644 lettucedetect/detectors/file_cache.py create mode 100644 tests/test_file_cache_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index 1511775..c3fd078 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -9,6 +9,7 @@ UpstreamError, ) from lettucedetect.detectors.factory import make_detector as _make_detector +from lettucedetect.detectors.file_cache import FileCache from lettucedetect.detectors.llm import LLMDetector from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector from lettucedetect.detectors.response_cache import ( @@ -40,6 +41,7 @@ "DetectRequest", "DetectedSpan", "Detection", + "FileCache", "InMemoryCache", "InvalidInputError", "LLMDetector", diff --git a/lettucedetect/detectors/file_cache.py b/lettucedetect/detectors/file_cache.py new file mode 100644 index 0000000..40e1361 --- /dev/null +++ b/lettucedetect/detectors/file_cache.py @@ -0,0 +1,163 @@ +"""A file-backed ``ResponseCache`` with atomic writes and a time to live. + +New error code (public API, do not rename): + +- ``cache_file_invalid`` (:class:`~lettucedetect.detectors.errors.ConfigurationError`): the cache file + exists but is not a JSON object. Every operation raises it and the file is never overwritten. +""" + +from __future__ import annotations + +import json +import logging +import os +import tempfile +import threading +import time +from pathlib import Path +from typing import Any + +from lettucedetect.detectors.errors import ConfigurationError +from lettucedetect.detectors.response_cache import SyncCacheBase, _validate_ttl + +logger = logging.getLogger(__name__) + +_LOCKS: dict[str, threading.Lock] = {} +_LOCKS_GUARD = threading.Lock() + + +def _lock_for(path: Path) -> threading.Lock: + """Return the one lock of a file path, shared by every ``FileCache`` on that path.""" + key = os.path.abspath(path) # noqa: PTH100 - no disk access, unlike Path.resolve() + with _LOCKS_GUARD: + return _LOCKS.setdefault(key, threading.Lock()) + + +def _is_ttl_entry(entry: object) -> bool: + """Whether ``entry`` is the ``{"value": str, "expires_at": number}`` form of a TTL entry.""" + return ( + isinstance(entry, dict) + and set(entry) == {"value", "expires_at"} + and isinstance(entry["value"], str) + and isinstance(entry["expires_at"], (int, float)) + and not isinstance(entry["expires_at"], bool) + ) + + +def _is_expired(entry: object, now: float) -> bool: + return _is_ttl_entry(entry) and now >= entry["expires_at"] # type: ignore[index] + + +def _read_value(entry: object, now: float) -> str | None: + """Return the string an entry holds, or ``None`` for a miss. + + Entries of any other shape (such as the dict replies ``CacheManager`` holds for the LLM + detector) are a miss: a ``ResponseCache`` holds strings only. + """ + if isinstance(entry, str): + return entry + if _is_ttl_entry(entry) and not _is_expired(entry, now): + return entry["value"] # type: ignore[index] + return None + + +class FileCache(SyncCacheBase): + """A ``ResponseCache`` stored in one JSON file, for **a single process**. + + The file is a JSON object. A value without a TTL is stored as ``key: "value"``, the format of + ``CacheManager``, so a file written by it reads back here. A value with a TTL is stored as + ``key: {"value": "...", "expires_at": }`` and reads as ``None`` once expired. + Expired entries are removed whenever the file is rewritten. + + - **Single process.** The lock covers the threads of one process, including several + ``FileCache`` objects on the same path. Two processes writing the same file can lose each + other's updates. The atomic rename keeps the file valid, it does not merge writers. + - **Atomic writes.** Each change goes to a temporary file in the same directory, which is then + moved over the file with ``os.replace``. A crash or a failed write leaves the previous file + in place and no temporary file behind. There is no ``fsync``, so a power loss can still lose + the latest write. + - **No disk access until needed.** The constructor reads and creates nothing. The directory is + created by the first write. The file is read on every call, so nothing goes stale. + - **Errors.** An invalid file raises ``ConfigurationError`` (``cache_file_invalid``). An error + from the file system (a failed write) is raised as it is, also out of ``aset``. + - **Async.** ``aget``, ``aset`` and ``adelete`` run the file work, the lock and the rename + included, in a worker thread. Cancelling the awaiting task stops the wait, not the thread: + the write still finishes, and the file holds the old or the new content, never a part. + """ + + def __init__(self, path: str | Path) -> None: + """Remember the path. Touches no disk. + + :param path: The JSON file. Its directory is created on the first write. + """ + self.path = Path(path) + self._lock = _lock_for(self.path) + + def get(self, key: str) -> str | None: + """Return the value stored under ``key``, or ``None`` if it is missing or expired.""" + with self._lock: + return _read_value(self._load().get(key), time.time()) + + def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: + """Store ``value`` under ``key`` and write the file atomically. + + :raises InvalidInputError: ``ttl_seconds`` is not a positive, finite number + (``invalid_ttl_seconds``). + :raises ConfigurationError: The file is invalid (``cache_file_invalid``). + """ + _validate_ttl(ttl_seconds) + with self._lock: + now = time.time() + data = self._purge(self._load(), now) + if ttl_seconds is None: + data[key] = value + else: + data[key] = {"value": value, "expires_at": now + ttl_seconds} + self._write(data) + + def delete(self, key: str) -> None: + """Remove ``key``. Does nothing, and writes nothing, if the key is missing.""" + with self._lock: + data = self._load() + kept = self._purge(data, time.time()) + kept.pop(key, None) + if kept != data: + self._write(kept) + + @staticmethod + def _purge(data: dict[str, Any], now: float) -> dict[str, Any]: + return {k: v for k, v in data.items() if not _is_expired(v, now)} + + def _load(self) -> dict[str, Any]: + try: + raw = self.path.read_text(encoding="utf-8") + except FileNotFoundError: + return {} + try: + data = json.loads(raw) + except ValueError as exc: + raise self._invalid() from exc + if not isinstance(data, dict): + raise self._invalid() + return data + + def _invalid(self) -> ConfigurationError: + return ConfigurationError( + f"The cache file {self.path} is not a JSON object. Repair or delete it; " + "FileCache never overwrites it.", + code="cache_file_invalid", + ) + + def _write(self, data: dict[str, Any]) -> None: + """Write ``data`` to a temporary file next to the cache file, then rename it over it.""" + parent = self.path.parent + parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=f".{self.path.name}.", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(json.dumps(data, ensure_ascii=False)) + os.replace(tmp, self.path) # noqa: PTH105 - the tests patch os.replace + except BaseException: + # Clean up after any failure, even a KeyboardInterrupt, then let it propagate unchanged. + Path(tmp).unlink(missing_ok=True) + raise diff --git a/lettucedetect/detectors/response_cache.py b/lettucedetect/detectors/response_cache.py index ddeb759..72a28a4 100644 --- a/lettucedetect/detectors/response_cache.py +++ b/lettucedetect/detectors/response_cache.py @@ -104,6 +104,23 @@ def make_cache_key( return CacheManager._hash(*parts) +def _validate_ttl(ttl_seconds: float | None) -> None: + """Raise ``invalid_ttl_seconds`` unless ``ttl_seconds`` is ``None`` or a positive finite number.""" + if ttl_seconds is None: + return + if ( + isinstance(ttl_seconds, bool) + or not isinstance(ttl_seconds, (int, float)) + or not math.isfinite(ttl_seconds) + or ttl_seconds <= 0 + ): + raise InvalidInputError( + "ttl_seconds must be a positive, finite number, or None for no expiry.", + code="invalid_ttl_seconds", + param="ttl_seconds", + ) + + class SyncCacheBase(abc.ABC): """Base class for backends that only have synchronous storage. @@ -173,20 +190,8 @@ def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None :raises InvalidInputError: ``ttl_seconds`` is not a positive, finite number (``invalid_ttl_seconds``). """ - deadline = None - if ttl_seconds is not None: - if ( - isinstance(ttl_seconds, bool) - or not isinstance(ttl_seconds, (int, float)) - or not math.isfinite(ttl_seconds) - or ttl_seconds <= 0 - ): - raise InvalidInputError( - "ttl_seconds must be a positive, finite number, or None for no expiry.", - code="invalid_ttl_seconds", - param="ttl_seconds", - ) - deadline = time.monotonic() + ttl_seconds + _validate_ttl(ttl_seconds) + deadline = None if ttl_seconds is None else time.monotonic() + ttl_seconds with self._lock: self._data[key] = (value, deadline) diff --git a/tests/test_file_cache_pytest.py b/tests/test_file_cache_pytest.py new file mode 100644 index 0000000..a4e7d78 --- /dev/null +++ b/tests/test_file_cache_pytest.py @@ -0,0 +1,379 @@ +"""Tests for ``FileCache``: the cache contract, atomic writes, CacheManager files and errors.""" + +from __future__ import annotations + +import asyncio +import contextlib +import itertools +import json +import math +import os +import threading +import time +from collections.abc import Callable +from unittest.mock import patch + +import pytest + +import lettucedetect.detectors as detectors +from lettucedetect.detectors import ( + ConfigurationError, + FileCache, + InvalidInputError, + ResponseCache, + SyncCacheBase, +) +from lettucedetect.detectors.cache import CacheManager +from tests.cache_contract import CacheContract + +REPLACE = "lettucedetect.detectors.file_cache.os.replace" +_WAIT = 10.0 + + +class HookedFileCache(FileCache): + """``FileCache`` that calls the contract's ``on_call`` before each storage operation.""" + + def __init__(self, path, on_call: Callable[[], None] | None = None) -> None: + """Create the cache.""" + super().__init__(path) + self._on_call = on_call + + def get(self, key): + """Call the hook, then read.""" + if self._on_call: + self._on_call() + return super().get(key) + + def set(self, key, value, *, ttl_seconds=None): + """Call the hook, then write.""" + if self._on_call: + self._on_call() + super().set(key, value, ttl_seconds=ttl_seconds) + + def delete(self, key): + """Call the hook, then delete.""" + if self._on_call: + self._on_call() + super().delete(key) + + +class TestFileCacheContract(CacheContract): + """``FileCache`` passes the whole cache contract suite, async methods included.""" + + @pytest.fixture(autouse=True) + def _directory(self, tmp_path): + self.directory = tmp_path + self._counter = itertools.count() + + def make_cache(self, on_call=None): + """Return a ``FileCache`` on a fresh file.""" + return HookedFileCache(self.directory / f"cache{next(self._counter)}.json", on_call) + + +def _gated_replace(gate: threading.Event, entered: threading.Event): + """Return an ``os.replace`` that waits on ``gate`` before it renames.""" + real = os.replace + + def replace(src, dst): + entered.set() + assert gate.wait(_WAIT), "the write was never released" + real(src, dst) + + return replace + + +async def _until(condition: Callable[[], bool]) -> None: + deadline = time.monotonic() + _WAIT + while not condition(): + assert time.monotonic() < deadline, "the worker thread never finished" + await asyncio.sleep(0.01) + + +class TestConstruction: + """The constructor and the read methods touch no disk.""" + + def test_constructor_touches_no_disk(self, tmp_path): + """Building a cache on a path in a missing directory creates nothing.""" + FileCache(tmp_path / "a" / "b" / "cache.json") + assert list(tmp_path.iterdir()) == [] + + def test_get_and_delete_create_nothing(self, tmp_path): + """Reading or deleting on a missing file leaves the disk as it was.""" + cache = FileCache(tmp_path / "a" / "cache.json") + assert cache.get("k") is None + cache.delete("k") + assert list(tmp_path.iterdir()) == [] + + def test_first_write_creates_the_directory_and_the_file(self, tmp_path): + """The first ``set`` makes the directory, and only the cache file is left in it.""" + path = tmp_path / "a" / "b" / "cache.json" + FileCache(path).set("k", "v") + assert json.loads(path.read_text(encoding="utf-8")) == {"k": "v"} + assert [p.name for p in path.parent.iterdir()] == ["cache.json"] + + def test_deleting_a_missing_key_writes_nothing(self, tmp_path): + """``delete`` of a key that is not there leaves the file byte for byte as it was.""" + path = tmp_path / "cache.json" + cache = FileCache(path) + cache.set("k", "v") + before = path.read_bytes() + cache.delete("missing") + assert path.read_bytes() == before + + +class TestFileFormat: + """The file is compatible with ``CacheManager`` and stores TTL entries as a pair.""" + + def test_file_written_by_cache_manager_reads_back(self, tmp_path): + """A ``CacheManager`` file with string values reads through ``get`` and ``aget``.""" + path = tmp_path / "cache.json" + legacy = CacheManager(path) + legacy.set("k", "héllo ✓") + cache = FileCache(path) + assert cache.get("k") == "héllo ✓" + assert asyncio.run(cache.aget("k")) == "héllo ✓" + + def test_legacy_non_string_entries_are_a_miss_and_survive_writes(self, tmp_path): + """Dict and null values (the LLM detector's replies) read as ``None`` and are kept.""" + path = tmp_path / "cache.json" + legacy = CacheManager(path) + legacy.set("reply", {"hallucination_list": []}) + legacy.set("nothing", None) + cache = FileCache(path) + assert cache.get("reply") is None + assert cache.get("nothing") is None + cache.set("k", "v") + assert json.loads(path.read_text(encoding="utf-8")) == { + "reply": {"hallucination_list": []}, + "nothing": None, + "k": "v", + } + + def test_file_without_ttls_is_readable_by_cache_manager(self, tmp_path): + """A value without a TTL is stored as ``key: "value"``.""" + path = tmp_path / "cache.json" + FileCache(path).set("k", "v") + assert CacheManager(path).get("k") == "v" + + def test_ttl_entry_is_value_and_expires_at(self, tmp_path): + """A value with a TTL is stored as ``{"value": ..., "expires_at": }``.""" + path = tmp_path / "cache.json" + before = time.time() + FileCache(path).set("k", "v", ttl_seconds=60) + entry = json.loads(path.read_text(encoding="utf-8"))["k"] + assert set(entry) == {"value", "expires_at"} + assert entry["value"] == "v" + assert before + 60 <= entry["expires_at"] <= time.time() + 60 + + def test_expired_entry_reads_as_none(self, tmp_path): + """An entry whose ``expires_at`` has passed is a miss; a later one is a hit.""" + path = tmp_path / "cache.json" + path.write_text( + json.dumps( + { + "old": {"value": "x", "expires_at": time.time() - 1}, + "new": {"value": "y", "expires_at": time.time() + 60}, + } + ), + encoding="utf-8", + ) + cache = FileCache(path) + assert cache.get("old") is None + assert cache.get("new") == "y" + + def test_get_never_rewrites_the_file(self, tmp_path): + """Reading an expired entry leaves the file as it was.""" + path = tmp_path / "cache.json" + path.write_text(json.dumps({"old": {"value": "x", "expires_at": 1.0}}), encoding="utf-8") + before = path.read_bytes() + assert FileCache(path).get("old") is None + assert path.read_bytes() == before + + def test_expired_entries_are_purged_on_write(self, tmp_path): + """A write drops the entries that have expired.""" + path = tmp_path / "cache.json" + path.write_text(json.dumps({"old": {"value": "x", "expires_at": 1.0}}), encoding="utf-8") + FileCache(path).set("new", "y") + assert json.loads(path.read_text(encoding="utf-8")) == {"new": "y"} + + def test_two_caches_on_one_path_share_the_data_and_the_lock(self, tmp_path): + """A second object on the same path sees the first one's writes at once.""" + path = tmp_path / "cache.json" + first, second = FileCache(path), FileCache(path) + first.set("a", "1") + second.set("b", "2") + assert first.get("b") == "2" + assert second.get("a") == "1" + assert first._lock is second._lock + + +class TestInvalidTtl: + """``ttl_seconds`` must be a positive, finite number.""" + + @pytest.mark.parametrize("ttl", [0, -1, math.nan, math.inf, True, "5"]) + def test_bad_ttl_raises_and_writes_nothing(self, tmp_path, ttl): + """The same error and code as ``InMemoryCache``, and no file is created.""" + cache = FileCache(tmp_path / "cache.json") + with pytest.raises(InvalidInputError) as info: + cache.set("k", "v", ttl_seconds=ttl) + assert info.value.code == "invalid_ttl_seconds" + assert info.value.param == "ttl_seconds" + assert list(tmp_path.iterdir()) == [] + + +class TestConcurrentWrites: + """The file stays valid JSON and holds every key.""" + + async def test_gather_of_aset_leaves_valid_json_with_every_key(self, tmp_path): + """200 ``aset`` calls awaited together: the file parses and has all 200 keys.""" + path = tmp_path / "cache.json" + cache = FileCache(path) + await asyncio.gather(*(cache.aset(f"k{i}", f"v{i}") for i in range(200))) + data = json.loads(path.read_text(encoding="utf-8")) + assert data == {f"k{i}": f"v{i}" for i in range(200)} + assert [p.name for p in tmp_path.iterdir()] == ["cache.json"] + + def test_threads_writing_different_keys_lose_none(self, tmp_path): + """Writers on separate ``FileCache`` objects of one path lose no key.""" + path = tmp_path / "cache.json" + errors: list[BaseException] = [] + + def write(worker: int) -> None: + cache = FileCache(path) + try: + for i in range(20): + cache.set(f"k{worker}-{i}", f"v{worker}-{i}") + except BaseException as exc: + errors.append(exc) + + threads = [threading.Thread(target=write, args=(n,)) for n in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert not errors + data = json.loads(path.read_text(encoding="utf-8")) + assert data == {f"k{w}-{i}": f"v{w}-{i}" for w in range(8) for i in range(20)} + + +class TestFailedWrite: + """A failed write leaves the previous file readable and raises the original error.""" + + def test_set_raises_and_keeps_the_old_file(self, tmp_path): + """``os.replace`` fails: ``set`` raises it, the file is byte for byte as it was.""" + path = tmp_path / "cache.json" + cache = FileCache(path) + cache.set("k", "old") + before = path.read_bytes() + with patch(REPLACE, side_effect=OSError("disk full")): + with pytest.raises(OSError, match="disk full"): + cache.set("k", "new") + assert path.read_bytes() == before + assert cache.get("k") == "old" + assert [p.name for p in tmp_path.iterdir()] == ["cache.json"] + + async def test_aset_raises_the_same_error_from_the_await(self, tmp_path): + """The error of the worker thread comes out of ``await aset`` unchanged.""" + path = tmp_path / "cache.json" + cache = FileCache(path) + cache.set("k", "old") + before = path.read_bytes() + error = OSError("disk full") + with patch(REPLACE, side_effect=error): + with pytest.raises(OSError) as info: + await cache.aset("k", "new") + assert info.value is error + assert path.read_bytes() == before + assert await cache.aget("k") == "old" + assert [p.name for p in tmp_path.iterdir()] == ["cache.json"] + await cache.aset("k", "later") + assert await cache.aget("k") == "later" + + +class TestInterruptedWrite: + """Cancelling ``aset``, or timing it out, while the write is in progress.""" + + @pytest.mark.parametrize("how", ["cancel", "timeout"]) + async def test_file_stays_valid_and_no_temporary_file_is_left(self, tmp_path, how): + """Before the thread ends the file is the old content; after, old or new, and clean.""" + path = tmp_path / "cache.json" + cache = FileCache(path) + cache.set("k", "old") + gate, entered = threading.Event(), threading.Event() + with patch(REPLACE, side_effect=_gated_replace(gate, entered)): + write = cache.aset("k", "new") + if how == "cancel": + task = asyncio.create_task(write) + assert await asyncio.to_thread(entered.wait, _WAIT), "the write never started" + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + else: + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(write, timeout=0.1) + assert entered.is_set() + # The thread is still inside the write: the temporary file exists, the file is old. + assert json.loads(path.read_text(encoding="utf-8")) == {"k": "old"} + assert any(p.name.endswith(".tmp") for p in tmp_path.iterdir()) + gate.set() + await _until(lambda: [p.name for p in tmp_path.iterdir()] == ["cache.json"]) + await _until(lambda: json.loads(path.read_text(encoding="utf-8")) == {"k": "new"}) + assert json.loads(path.read_text(encoding="utf-8")) in ({"k": "old"}, {"k": "new"}) + assert [p.name for p in tmp_path.iterdir()] == ["cache.json"] + assert cache.get("k") == "new" + cache.set("k", "later") + assert await cache.aget("k") == "later" + await cache.aset("other", "value") + assert cache.get("other") == "value" + + +class TestInvalidFile: + """A file that is not a JSON object is an error on every operation, and is never touched.""" + + @pytest.mark.parametrize("content", ["{not json", "", "[1, 2]", '"text"', "null"]) + def test_every_operation_raises(self, tmp_path, content): + """``get``, ``set``, ``delete`` and ``aget`` raise ``cache_file_invalid``.""" + path = tmp_path / "cache.json" + path.write_text(content, encoding="utf-8") + cache = FileCache(path) + operations = [ + lambda: cache.get("k"), + lambda: cache.set("k", "v"), + lambda: cache.delete("k"), + lambda: asyncio.run(cache.aget("k")), + ] + for operation in operations: + with pytest.raises(ConfigurationError) as info: + operation() + assert info.value.code == "cache_file_invalid" + assert str(path) in str(info.value) + assert path.read_text(encoding="utf-8") == content + assert [p.name for p in tmp_path.iterdir()] == ["cache.json"] + + def test_json_error_is_chained(self, tmp_path): + """The error keeps the parser error as its cause.""" + path = tmp_path / "cache.json" + path.write_text("{not json", encoding="utf-8") + with pytest.raises(ConfigurationError) as info: + FileCache(path).get("k") + assert isinstance(info.value.__cause__, ValueError) + + +class TestPublicApi: + """The class is public and says it is for one process.""" + + def test_exported_and_a_response_cache(self, tmp_path): + """Importable from ``lettucedetect.detectors`` and follows the protocol.""" + assert "FileCache" in detectors.__all__ + cache = FileCache(tmp_path / "cache.json") + assert isinstance(cache, ResponseCache) + assert isinstance(cache, SyncCacheBase) + + def test_docstring_says_single_process(self): + """The limit is documented.""" + assert "single process" in (FileCache.__doc__ or "").lower() + + def test_async_methods_come_from_the_base(self): + """The async pairs are written once, in ``SyncCacheBase``.""" + for name in ("aget", "aset", "adelete"): + assert name not in vars(FileCache) From 7d4d46a795e1a4cd8e2c2831d03af3273d414e13 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 10:45:31 +0100 Subject: [PATCH 21/60] refactor: make CacheManager a deprecated subclass of FileCache (#147) --- lettucedetect/detectors/cache.py | 57 +++---- lettucedetect/detectors/file_cache.py | 27 ++-- lettucedetect/detectors/response_cache.py | 12 +- tests/test_cache_manager_pytest.py | 182 ++++++++++++++++++++++ tests/test_file_cache_pytest.py | 3 + tests/test_golden_factory_cache_pytest.py | 3 + 6 files changed, 236 insertions(+), 48 deletions(-) create mode 100644 tests/test_cache_manager_pytest.py diff --git a/lettucedetect/detectors/cache.py b/lettucedetect/detectors/cache.py index 45eb4d4..c829e70 100644 --- a/lettucedetect/detectors/cache.py +++ b/lettucedetect/detectors/cache.py @@ -1,47 +1,40 @@ -"""Thread-safe JSON cache with SHA-256 keys.""" +"""The old file cache, kept for compatibility. Use :class:`~lettucedetect.detectors.FileCache`.""" from __future__ import annotations -import hashlib -import json -import threading from pathlib import Path from typing import Any +from lettucedetect.detectors._deprecation import deprecated +from lettucedetect.detectors.file_cache import FileCache, _is_ttl_entry +from lettucedetect.detectors.response_cache import _hash_parts -class CacheManager: - """Disk-backed cache for expensive LLM calls.""" + +@deprecated("FileCache") +class CacheManager(FileCache): + """Disk-backed cache for expensive LLM calls. + + .. deprecated:: 0.3.0 + Use :class:`~lettucedetect.detectors.FileCache`. ``CacheManager`` will be removed in 0.5.0. + + It is a ``FileCache`` that keeps its old behaviour: ``get`` returns any JSON value that was + stored, not only strings. ``aget``, ``aset`` and ``adelete`` are the ones of ``FileCache``. The + directory of the file is created by the first write, not by the constructor. + """ def __init__(self, file_path: str | Path) -> None: - """Initialize cache from disk. + """Remember the path of the cache file. :param file_path: Path to the JSON cache file. """ - self.path = Path(file_path) - self.path.parent.mkdir(parents=True, exist_ok=True) - self._lock = threading.Lock() - self._data: dict[str, Any] = ( - json.loads(self.path.read_text("utf-8")) if self.path.exists() else {} - ) + super().__init__(file_path) @staticmethod def _hash(*parts: str) -> str: - return hashlib.sha256("||".join(parts).encode()).hexdigest() - - def get(self, key: str) -> Any | None: # noqa: ANN401 - """Retrieve a cached value by key.""" - with self._lock: - return self._data.get(key) - - def set(self, key: str, value: Any) -> None: # noqa: ANN401 - """Store a value in the cache and persist to disk.""" - with self._lock: - self._data[key] = value - self.path.write_text(json.dumps(self._data, ensure_ascii=False), encoding="utf-8") - - def delete(self, key: str) -> None: - """Remove a key from the cache and persist to disk.""" - with self._lock: - if key in self._data: - del self._data[key] - self.path.write_text(json.dumps(self._data, ensure_ascii=False), encoding="utf-8") + return _hash_parts(*parts) + + def _decode(self, entry: object, now: float) -> Any: # noqa: ANN401 + """Return any stored JSON value as it is; only TTL entries are unwrapped.""" + if _is_ttl_entry(entry): + return super()._decode(entry, now) + return entry diff --git a/lettucedetect/detectors/file_cache.py b/lettucedetect/detectors/file_cache.py index 40e1361..6c412fb 100644 --- a/lettucedetect/detectors/file_cache.py +++ b/lettucedetect/detectors/file_cache.py @@ -48,19 +48,6 @@ def _is_expired(entry: object, now: float) -> bool: return _is_ttl_entry(entry) and now >= entry["expires_at"] # type: ignore[index] -def _read_value(entry: object, now: float) -> str | None: - """Return the string an entry holds, or ``None`` for a miss. - - Entries of any other shape (such as the dict replies ``CacheManager`` holds for the LLM - detector) are a miss: a ``ResponseCache`` holds strings only. - """ - if isinstance(entry, str): - return entry - if _is_ttl_entry(entry) and not _is_expired(entry, now): - return entry["value"] # type: ignore[index] - return None - - class FileCache(SyncCacheBase): """A ``ResponseCache`` stored in one JSON file, for **a single process**. @@ -96,7 +83,19 @@ def __init__(self, path: str | Path) -> None: def get(self, key: str) -> str | None: """Return the value stored under ``key``, or ``None`` if it is missing or expired.""" with self._lock: - return _read_value(self._load().get(key), time.time()) + return self._decode(self._load().get(key), time.time()) + + def _decode(self, entry: object, now: float) -> Any: # noqa: ANN401 + """Return the string an entry holds, or ``None`` for a miss. + + Entries of any other shape (such as the dict replies an old ``CacheManager`` file may + hold) are a miss: a ``ResponseCache`` holds strings only. + """ + if isinstance(entry, str): + return entry + if _is_ttl_entry(entry) and not _is_expired(entry, now): + return entry["value"] # type: ignore[index] # ty: ignore[not-subscriptable] + return None def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: """Store ``value`` under ``key`` and write the file atomically. diff --git a/lettucedetect/detectors/response_cache.py b/lettucedetect/detectors/response_cache.py index 72a28a4..523342a 100644 --- a/lettucedetect/detectors/response_cache.py +++ b/lettucedetect/detectors/response_cache.py @@ -15,13 +15,13 @@ import abc import asyncio +import hashlib import logging import math import threading import time from typing import Literal, Protocol, runtime_checkable -from lettucedetect.detectors.cache import CacheManager from lettucedetect.detectors.errors import InvalidInputError logger = logging.getLogger(__name__) @@ -68,6 +68,14 @@ async def adelete(self, key: str) -> None: ... +def _hash_parts(*parts: str) -> str: + """Return the SHA-256 hex digest of ``parts`` joined by ``||``. + + This is the hash ``CacheManager`` has always used, so existing cache files stay valid. + """ + return hashlib.sha256("||".join(parts).encode()).hexdigest() + + def make_cache_key( prompt: str, model: str, @@ -101,7 +109,7 @@ def make_cache_key( if model_version is not None: # Prefixed, so a version can never read as a kind ("native") and collide with its key. parts.append(f"model_version={model_version}") - return CacheManager._hash(*parts) + return _hash_parts(*parts) def _validate_ttl(ttl_seconds: float | None) -> None: diff --git a/tests/test_cache_manager_pytest.py b/tests/test_cache_manager_pytest.py new file mode 100644 index 0000000..0f4d41a --- /dev/null +++ b/tests/test_cache_manager_pytest.py @@ -0,0 +1,182 @@ +"""Tests for ``CacheManager``, now a deprecated subclass of ``FileCache``.""" + +from __future__ import annotations + +import json +import subprocess +import sys +import warnings + +import pytest + +from lettucedetect.detectors import FileCache, LettuceDetectDeprecationWarning, make_cache_key +from lettucedetect.detectors._deprecation import DEPRECATED_SINCE, REMOVED_IN +from lettucedetect.detectors.cache import CacheManager +from lettucedetect.detectors.llm import LLMDetector +from lettucedetect.detectors.response_cache import SyncCacheBase +from tests.golden import GOLDEN_DIR +from tests.test_golden_llm_pytest import PLAIN, FakeClient + +IGNORE = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + + +def _recorded() -> dict[str, str]: + return json.loads((GOLDEN_DIR / "cache_hash_strings.json").read_text(encoding="utf-8")) + + +class TestDeprecation: + """Constructing it from outside the package warns, and names ``FileCache``.""" + + def test_is_a_file_cache_and_warns_naming_file_cache(self, tmp_path): + """The warning has the helper's message and points at the line that built the cache.""" + with pytest.warns(LettuceDetectDeprecationWarning, match="FileCache") as rec: + cache = CacheManager(tmp_path / "cache.json") # ty: ignore[deprecated] + assert isinstance(cache, FileCache) + assert isinstance(cache, SyncCacheBase) + assert len(rec) == 1 + assert str(rec[0].message) == ( + f"CacheManager is deprecated since {DEPRECATED_SINCE} and will be removed in " + f"{REMOVED_IN}. Use FileCache." + ) + assert rec[0].filename == __file__ + + def test_docstring_has_the_deprecated_note(self): + """The class docstring carries ``.. deprecated::`` and names the replacement.""" + assert ".. deprecated::" in (CacheManager.__doc__ or "") + assert "FileCache" in (CacheManager.__doc__ or "") + assert "FileCache" in getattr(CacheManager, "__deprecated__") + + def test_internal_caller_is_silent_but_external_warns(self, tmp_path): + """A ``lettucedetect.*`` module builds it silently; the same code elsewhere warns.""" + namespace = {"CacheManager": CacheManager, "path": tmp_path / "c.json"} + with warnings.catch_warnings(): + warnings.simplefilter("error") + exec("CacheManager(path)", {**namespace, "__name__": "lettucedetect.fake"}) # noqa: S102 + with pytest.warns(LettuceDetectDeprecationWarning): + exec("CacheManager(path)", {**namespace, "__name__": "somewhere_else"}) # noqa: S102 + + def test_llm_detector_builds_it_without_a_warning(self, tmp_path): + """``LLMDetector`` keeps using ``CacheManager`` internally, silently.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + detector = LLMDetector(client=FakeClient(PLAIN), cache_file=str(tmp_path / "c.json")) + assert isinstance(detector.cache, CacheManager) + + def test_importing_the_module_has_no_import_cycle_or_warning(self): + """A fresh interpreter imports ``cache`` first, then ``response_cache``, with no warning.""" + code = ( + "import warnings; warnings.simplefilter('error')\n" + "import lettucedetect.detectors.cache\n" + "import lettucedetect.detectors.response_cache\n" + "import lettucedetect.detectors\n" + ) + result = subprocess.run( # noqa: S603 - our own interpreter and a fixed script + [sys.executable, "-I", "-c", code], capture_output=True, text=True, check=False + ) + assert result.returncode == 0, result.stderr + + +@IGNORE +class TestAsyncMethods: + """``aget``, ``aset`` and ``adelete`` are inherited and equal the sync methods.""" + + def test_no_override(self): + """The async methods are not redefined on ``CacheManager`` or ``FileCache``.""" + for name in ("aget", "aset", "adelete"): + assert name not in vars(CacheManager) + assert name not in vars(FileCache) + assert name in vars(SyncCacheBase) + + async def test_async_equals_sync_and_adds_no_warning(self, tmp_path): + """A value crosses the sync/async boundary both ways, with no warning after construction.""" + cache = CacheManager(tmp_path / "cache.json") + with warnings.catch_warnings(): + warnings.simplefilter("error") + cache.set("sync", "from set") + assert await cache.aget("sync") == cache.get("sync") == "from set" + await cache.aset("async", "from aset") + assert cache.get("async") == await cache.aget("async") == "from aset" + await cache.aset("ttl", "v", ttl_seconds=60) + assert cache.get("ttl") == "v" + assert cache.delete("sync") is None + assert await cache.adelete("async") is None + assert cache.get("sync") is None + assert await cache.aget("async") is None + + +@IGNORE +class TestBehavesAsBefore: + """``_hash``, ``path``, ``get``, ``set`` and ``delete`` keep their behaviour.""" + + @pytest.mark.parametrize("kind", ["judge", "native", "verify"]) + def test_hash_returns_the_recorded_strings(self, kind): + """``_hash`` is the key function behind the recorded keys.""" + parts = ("prompt", "gpt-4.1-mini", str(0.0)) + (() if kind == "judge" else (kind,)) + assert CacheManager._hash(*parts) == _recorded()[kind] + assert make_cache_key("prompt", "gpt-4.1-mini", None, 0.0, kind) == _recorded()[kind] + + def test_path_is_a_path(self, tmp_path): + """``path`` is the ``Path`` of the file, for a string or a ``Path`` argument.""" + assert CacheManager(str(tmp_path / "c.json")).path == tmp_path / "c.json" + assert CacheManager(tmp_path / "c.json").path == tmp_path / "c.json" + + @pytest.mark.parametrize( + "value", ["text", "héllo ✓", {"x": 1, "y": [1, 2]}, [1, "a"], None, 3, ""] + ) + def test_any_json_value_round_trips(self, tmp_path, value): + """As before, ``set`` stores any JSON value and ``get`` returns it.""" + cache = CacheManager(tmp_path / "cache.json") + cache.set("k", value) + assert cache.get("k") == value + assert CacheManager(tmp_path / "cache.json").get("k") == value + + def test_missing_key_is_none_and_delete_is_quiet(self, tmp_path): + """A missing key reads ``None``; deleting it does nothing.""" + cache = CacheManager(tmp_path / "cache.json") + assert cache.get("missing") is None + cache.delete("missing") + cache.set("k", "v") + cache.set("k", "w") + assert cache.get("k") == "w" + cache.delete("k") + assert cache.get("k") is None + + def test_file_bytes_are_unchanged(self, tmp_path): + """The golden sequence still ends in the same file, byte for byte.""" + path = tmp_path / "nested" / "cache.json" + cache = CacheManager(path) + cache.set("a", {"x": 1, "y": [1, 2]}) + cache.set("b", "héllo ✓") + cache.set("c", None) + cache.delete("a") + cache.delete("missing") + cache.set("b", "overwritten") + assert path.read_text(encoding="utf-8") == '{"b": "overwritten", "c": null}' + + def test_the_directory_appears_on_the_first_write_only(self, tmp_path): + """The constructor no longer creates the directory (an intended change).""" + path = tmp_path / "nested" / "cache.json" + cache = CacheManager(path) + assert not path.parent.exists() + cache.set("k", "v") + assert path.exists() + + def test_ttl_entries_still_expire_through_get(self, tmp_path): + """A TTL entry written by ``FileCache`` reads as a value, and as ``None`` once expired.""" + path = tmp_path / "cache.json" + path.write_text( + json.dumps( + { + "live": {"value": "x", "expires_at": 4102444800}, + "dead": {"value": "y", "expires_at": 1}, + "plain": {"value": 1, "other": 2}, + } + ), + encoding="utf-8", + ) + cache = CacheManager(path) + assert cache.get("live") == "x" + assert cache.get("dead") is None + assert cache.get("plain") == {"value": 1, "other": 2} diff --git a/tests/test_file_cache_pytest.py b/tests/test_file_cache_pytest.py index a4e7d78..9eb431b 100644 --- a/tests/test_file_cache_pytest.py +++ b/tests/test_file_cache_pytest.py @@ -121,6 +121,9 @@ def test_deleting_a_missing_key_writes_nothing(self, tmp_path): assert path.read_bytes() == before +@pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) class TestFileFormat: """The file is compatible with ``CacheManager`` and stores TTL entries as a pair.""" diff --git a/tests/test_golden_factory_cache_pytest.py b/tests/test_golden_factory_cache_pytest.py index ef673f2..6741b93 100644 --- a/tests/test_golden_factory_cache_pytest.py +++ b/tests/test_golden_factory_cache_pytest.py @@ -196,6 +196,9 @@ def test_rag_fact_checker(self): assert_golden("facade_rag_fact_checker", results) +@pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) class TestCacheManager: """The cache file format and the key strings the LLM detector builds.""" From dc9263ef7d01522f2aaab8a5f6c672dd54b25774 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 11:30:50 +0100 Subject: [PATCH 22/60] feat: log cache steps at DEBUG on the module loggers (#146, #145) --- lettucedetect/detectors/file_cache.py | 27 +++++++++-- lettucedetect/detectors/response_cache.py | 10 +++- tests/test_file_cache_pytest.py | 59 +++++++++++++++++++++++ tests/test_response_cache_pytest.py | 37 ++++++++++++++ 4 files changed, 128 insertions(+), 5 deletions(-) diff --git a/lettucedetect/detectors/file_cache.py b/lettucedetect/detectors/file_cache.py index 6c412fb..60f61c1 100644 --- a/lettucedetect/detectors/file_cache.py +++ b/lettucedetect/detectors/file_cache.py @@ -83,7 +83,9 @@ def __init__(self, path: str | Path) -> None: def get(self, key: str) -> str | None: """Return the value stored under ``key``, or ``None`` if it is missing or expired.""" with self._lock: - return self._decode(self._load().get(key), time.time()) + value = self._decode(self._load().get(key), time.time()) + logger.debug("FileCache get on %s: %s", self.path, "hit" if value is not None else "miss") + return value def _decode(self, entry: object, now: float) -> Any: # noqa: ANN401 """Return the string an entry holds, or ``None`` for a miss. @@ -93,8 +95,12 @@ def _decode(self, entry: object, now: float) -> Any: # noqa: ANN401 """ if isinstance(entry, str): return entry - if _is_ttl_entry(entry) and not _is_expired(entry, now): - return entry["value"] # type: ignore[index] # ty: ignore[not-subscriptable] + if _is_ttl_entry(entry): + if not _is_expired(entry, now): + return entry["value"] # type: ignore[index] # ty: ignore[not-subscriptable] + logger.debug("FileCache entry on %s has expired", self.path) + elif entry is not None: + logger.debug("FileCache entry on %s is not a string, read as a miss", self.path) return None def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: @@ -107,21 +113,33 @@ def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None _validate_ttl(ttl_seconds) with self._lock: now = time.time() - data = self._purge(self._load(), now) + loaded = self._load() + data = self._purge(loaded, now) + if len(data) != len(loaded): + logger.debug( + "FileCache set on %s: dropped %d expired entries", + self.path, + len(loaded) - len(data), + ) if ttl_seconds is None: data[key] = value else: data[key] = {"value": value, "expires_at": now + ttl_seconds} self._write(data) + logger.debug("FileCache set on %s: stored an entry, ttl_seconds=%s", self.path, ttl_seconds) def delete(self, key: str) -> None: """Remove ``key``. Does nothing, and writes nothing, if the key is missing.""" with self._lock: data = self._load() kept = self._purge(data, time.time()) + existed = key in kept kept.pop(key, None) if kept != data: self._write(kept) + logger.debug( + "FileCache delete on %s: %s", self.path, "removed" if existed else "key not found" + ) @staticmethod def _purge(data: dict[str, Any], now: float) -> dict[str, Any]: @@ -156,6 +174,7 @@ def _write(self, data: dict[str, Any]) -> None: with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(json.dumps(data, ensure_ascii=False)) os.replace(tmp, self.path) # noqa: PTH105 - the tests patch os.replace + logger.debug("FileCache wrote %d entries to %s", len(data), self.path) except BaseException: # Clean up after any failure, even a KeyboardInterrupt, then let it propagate unchanged. Path(tmp).unlink(missing_ok=True) diff --git a/lettucedetect/detectors/response_cache.py b/lettucedetect/detectors/response_cache.py index 523342a..1e0018b 100644 --- a/lettucedetect/detectors/response_cache.py +++ b/lettucedetect/detectors/response_cache.py @@ -185,11 +185,14 @@ def get(self, key: str) -> str | None: with self._lock: entry = self._data.get(key) if entry is None: + logger.debug("InMemoryCache get: miss") return None value, deadline = entry if deadline is not None and time.monotonic() >= deadline: del self._data[key] + logger.debug("InMemoryCache get: miss, the entry had expired and was removed") return None + logger.debug("InMemoryCache get: hit") return value def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None: @@ -202,8 +205,13 @@ def set(self, key: str, value: str, *, ttl_seconds: float | None = None) -> None deadline = None if ttl_seconds is None else time.monotonic() + ttl_seconds with self._lock: self._data[key] = (value, deadline) + count = len(self._data) + logger.debug( + "InMemoryCache set: stored an entry, ttl_seconds=%s, %d entries", ttl_seconds, count + ) def delete(self, key: str) -> None: """Remove ``key``. Does nothing if the key is missing.""" with self._lock: - self._data.pop(key, None) + existed = self._data.pop(key, None) is not None + logger.debug("InMemoryCache delete: %s", "removed" if existed else "key not found") diff --git a/tests/test_file_cache_pytest.py b/tests/test_file_cache_pytest.py index 9eb431b..223e688 100644 --- a/tests/test_file_cache_pytest.py +++ b/tests/test_file_cache_pytest.py @@ -6,6 +6,7 @@ import contextlib import itertools import json +import logging import math import os import threading @@ -380,3 +381,61 @@ def test_async_methods_come_from_the_base(self): """The async pairs are written once, in ``SyncCacheBase``.""" for name in ("aget", "aset", "adelete"): assert name not in vars(FileCache) + + +CUSTOMER_KEY = "key-with-CUSTOMER-TEXT-7f3a" +CUSTOMER_VALUE = "reply-with-CUSTOMER-TEXT-9c1e" + + +class TestLogging: + """Module logger only: DEBUG steps, no customer text, no printing, never log and raise.""" + + def test_steps_are_logged_at_debug_without_keys_or_values(self, tmp_path, caplog, capsys): + """Every operation leaves DEBUG records on the module logger; none carries a key or value.""" + cache = FileCache(tmp_path / "cache.json") + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + cache.set(CUSTOMER_KEY, CUSTOMER_VALUE) + cache.set("short", CUSTOMER_VALUE, ttl_seconds=0.05) + assert cache.get(CUSTOMER_KEY) == CUSTOMER_VALUE + assert cache.get("missing") is None + time.sleep(0.1) + assert cache.get("short") is None + cache.set("other", "v") # drops the expired entry + cache.delete(CUSTOMER_KEY) + cache.delete(CUSTOMER_KEY) + records = [r for r in caplog.records if r.name == "lettucedetect.detectors.file_cache"] + text = "\n".join(r.getMessage() for r in records) + assert records + assert {r.levelno for r in records} == {logging.DEBUG} + for secret in (CUSTOMER_KEY, CUSTOMER_VALUE, "CUSTOMER"): + assert secret not in text + for expected in ("get on", "miss", "hit", "expired", "removed", "key not found", "wrote"): + assert expected in text, expected + captured = capsys.readouterr() + assert captured.out == captured.err == "" + + def test_a_non_string_entry_is_logged_as_a_miss(self, tmp_path, caplog): + """A legacy dict value reads as a miss and says so at DEBUG, without its content.""" + path = tmp_path / "cache.json" + path.write_text( + json.dumps({"k": {"hallucination_list": [CUSTOMER_VALUE]}}), encoding="utf-8" + ) + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + assert FileCache(path).get("k") is None + text = "\n".join(r.getMessage() for r in caplog.records) + assert "not a string" in text + assert CUSTOMER_VALUE not in text + + def test_errors_are_raised_not_logged(self, tmp_path, caplog): + """A failed write and an invalid file raise; the cache adds no WARNING or ERROR record.""" + path = tmp_path / "cache.json" + cache = FileCache(path) + cache.set("k", "v") + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + with patch(REPLACE, side_effect=OSError("disk full")): + with pytest.raises(OSError): + cache.set("k", "new") + path.write_text("{not json", encoding="utf-8") + with pytest.raises(ConfigurationError): + cache.get("k") + assert [r for r in caplog.records if r.levelno >= logging.WARNING] == [] diff --git a/tests/test_response_cache_pytest.py b/tests/test_response_cache_pytest.py index a745199..ac4ac80 100644 --- a/tests/test_response_cache_pytest.py +++ b/tests/test_response_cache_pytest.py @@ -2,7 +2,9 @@ from __future__ import annotations +import logging import math +import time import pytest @@ -126,3 +128,38 @@ async def adelete(self, key): ... assert isinstance(Direct(), ResponseCache) assert not issubclass(Direct, SyncCacheBase) + + +class TestInMemoryCacheLogging: + """Module logger only: DEBUG steps, no customer text, no printing.""" + + def test_steps_are_logged_at_debug_without_keys_or_values(self, caplog, capsys): + """Every operation leaves a DEBUG record; none carries a key or a value.""" + cache = InMemoryCache() + secret_key, secret_value = "key-with-CUSTOMER-TEXT-7f3a", "reply-with-CUSTOMER-TEXT-9c1e" + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + cache.set(secret_key, secret_value) + cache.set("short", secret_value, ttl_seconds=0.05) + assert cache.get(secret_key) == secret_value + assert cache.get("missing") is None + time.sleep(0.1) + assert cache.get("short") is None + cache.delete(secret_key) + cache.delete(secret_key) + records = [r for r in caplog.records if r.name == "lettucedetect.detectors.response_cache"] + text = "\n".join(r.getMessage() for r in records) + assert records + assert {r.levelno for r in records} == {logging.DEBUG} + for secret in (secret_key, secret_value, "CUSTOMER"): + assert secret not in text + for expected in ("hit", "miss", "expired", "removed", "key not found", "stored"): + assert expected in text, expected + captured = capsys.readouterr() + assert captured.out == captured.err == "" + + def test_an_invalid_ttl_is_raised_not_logged(self, caplog): + """The error is the report: no WARNING or ERROR record is added.""" + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + with pytest.raises(InvalidInputError): + InMemoryCache().set("k", "v", ttl_seconds=0) + assert [r for r in caplog.records if r.levelno >= logging.WARNING] == [] From 8879fbb6ba34786a16b9d796e3eae8f450aa891d Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 12:34:49 +0100 Subject: [PATCH 23/60] feat: add EncoderDetector and EncoderConfig with detect spans (#149) --- lettucedetect/detectors/__init__.py | 3 + lettucedetect/detectors/encoder.py | 578 +++++++++++++++++++++++++ lettucedetect/detectors/transformer.py | 370 +--------------- tests/test_encoder_detector_pytest.py | 271 ++++++++++++ 4 files changed, 854 insertions(+), 368 deletions(-) create mode 100644 lettucedetect/detectors/encoder.py create mode 100644 tests/test_encoder_detector_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index c3fd078..64042b5 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -2,6 +2,7 @@ from lettucedetect.detectors._deprecation import LettuceDetectDeprecationWarning from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.encoder import EncoderConfig, EncoderDetector from lettucedetect.detectors.errors import ( ConfigurationError, InvalidInputError, @@ -41,6 +42,8 @@ "DetectRequest", "DetectedSpan", "Detection", + "EncoderConfig", + "EncoderDetector", "FileCache", "InMemoryCache", "InvalidInputError", diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py new file mode 100644 index 0000000..00bfc19 --- /dev/null +++ b/lettucedetect/detectors/encoder.py @@ -0,0 +1,578 @@ +"""Detector backed by a fine-tuned token classifier that the caller has already loaded.""" + +from __future__ import annotations + +import logging +import threading +from typing import Any + +import torch +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator + +from lettucedetect.datasets.hallucination_dataset import HallucinationDataset +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import ConfigurationError +from lettucedetect.detectors.prompt_utils import LANG_TO_PASSAGE, PromptUtils +from lettucedetect.detectors.types import ( + DetectedSpan, + Detection, + DetectRequest, + SourcesInput, + Usage, +) + +logger = logging.getLogger(__name__) + +__all__ = ["EncoderConfig", "EncoderDetector"] + +# Makes two racing first calls on one detector get the same scoring lock. +_LOCK_GUARD = threading.Lock() + + +class EncoderConfig(BaseModel): + """Options of an :class:`EncoderDetector`. + + An invalid option raises :class:`ConfigurationError` with the code ``invalid_config``, + ``invalid_language`` or ``invalid_batch_size`` and ``param`` set to the option. + + :param max_length: maximum number of tokens of prompt plus answer. + :param batch_size: number of requests scored together in one padded forward pass. + :param lang: language of the prompt template, one of the supported languages. + """ + + model_config = ConfigDict(frozen=True, extra="forbid", hide_input_in_errors=True) + + max_length: int = Field(default=4096, gt=0) + batch_size: int = Field(default=16, ge=1) + lang: str = "en" + + @model_validator(mode="wrap") + @classmethod + def _raise_configuration_error(cls, data: Any, handler: Any) -> EncoderConfig: # noqa: ANN401 + try: + config = handler(data) + except ValidationError as exc: + first = exc.errors(include_input=False, include_url=False)[0] + param = str(first["loc"][0]) if first["loc"] else None + code = {"lang": "invalid_language", "batch_size": "invalid_batch_size"}.get( + param or "", "invalid_config" + ) + if first["type"] == "extra_forbidden": + code = "invalid_config" + raise ConfigurationError( + f"Invalid EncoderConfig option {param!r}; see the EncoderConfig docstring.", + code=code, + param=param, + ) from exc + if config.lang not in LANG_TO_PASSAGE: + raise ConfigurationError( + f"Invalid language; choose from {', '.join(LANG_TO_PASSAGE)}.", + code="invalid_language", + param="lang", + ) + return config + + +class EncoderDetector(BaseDetector): + """Detect hallucinations with a token classifier and tokenizer the caller already holds. + + Construction downloads nothing, reads no environment variable and writes no file. The model + is not moved or switched to eval mode: pass it ready for inference. + + When prompt plus answer exceed ``max_length`` tokens, sources are split into passage groups, + each group is scored on its own and the per-token probability is the ``max()`` over groups. + Scoring runs under one private lock, so concurrent calls on one instance run one at a time. + + Example, loading the model once at startup:: + + from transformers import AutoModelForTokenClassification, AutoTokenizer + + model_id = "KRLabsOrg/lettucedect-base-modernbert-en-v1" + tokenizer = AutoTokenizer.from_pretrained(model_id) + model = AutoModelForTokenClassification.from_pretrained(model_id).eval() + + detector = EncoderDetector( + model, + tokenizer, + config=EncoderConfig(max_length=4096, batch_size=16, lang="en"), + model_id=model_id, + ) + result = detector.detect( + SourcesInput( + question="What is the capital of France?", + sources=[Chunk(id="doc-1", text="The capital of France is Paris.")], + answer="The capital of France is Lyon.", + ) + ) + + :param model: a token classification model. + :param tokenizer: the model's fast tokenizer. + :param typer: optional span typer; accepted but not applied yet. + :param config: options, ``EncoderConfig()`` when ``None``. + :param model_id: id reported in ``usage``. + :param model_version: version reported in ``usage``. + """ + + model_id: str | None = None + model_version: str | None = None + typer: Any = None + + def __init__( + self, + model: Any, # noqa: ANN401 + tokenizer: Any, # noqa: ANN401 + typer: Any = None, # noqa: ANN401 + *, + config: EncoderConfig | None = None, + model_id: str | None = None, + model_version: str | None = None, + ) -> None: + """Build the detector from loaded objects.""" + self.config = config if config is not None else EncoderConfig() + self.model = model + self.tokenizer = tokenizer + self.typer = typer + self.max_length = self.config.max_length + self.lang = self.config.lang + self.batch_size = self.config.batch_size + self.model_id = model_id + self.model_version = model_version + device = getattr(model, "device", None) + self.device = device if isinstance(device, torch.device) else torch.device("cpu") + logger.debug( + "encoder detector built: model_id=%s max_length=%d batch_size=%d lang=%s device=%s", + model_id, + self.max_length, + self.batch_size, + self.lang, + self.device, + ) + + # ------------------------------------------------------------------ + # Lock + # ------------------------------------------------------------------ + + def _get_scoring_lock(self) -> threading.RLock: + """Return the scoring lock, creating it on first use (not in ``__init__``).""" + lock = vars(self).get("_scoring_lock") + if lock is None: + with _LOCK_GUARD: + lock = vars(self).get("_scoring_lock") + if lock is None: + lock = threading.RLock() + self._scoring_lock = lock + return lock + + # ------------------------------------------------------------------ + # Detection + # ------------------------------------------------------------------ + + def _detect( + self, request: DetectRequest, *, include_tokens: bool, include_detail: bool + ) -> Detection: + """Score a request and return its spans. + + :param request: the sources (or prompt) and the answer to check. + :param include_tokens: unused until token scores are supported. + :param include_detail: unused, there is no detail. + :returns: the detection result. + """ + with self._get_scoring_lock(): + if isinstance(request, SourcesInput): + context = [chunk.text for chunk in request.sources] + groups = self._group_passages_into_chunks(context, request.question, request.answer) + logger.debug( + "scoring sources request: sources=%d passage_groups=%d", + len(context), + len(groups), + ) + if len(groups) == 1: + prompt = PromptUtils.format_context(groups[0], request.question, self.lang) + raw = self._predict_single(prompt, request.answer, "spans") + else: + prompts = [ + PromptUtils.format_context(group, request.question, self.lang) + for group in groups + ] + raw = self._predict_chunked(prompts, request.answer, "spans") + else: + logger.debug("scoring prompt request") + raw = self._predict_single(request.prompt, request.answer, "spans") + spans = [ + DetectedSpan( + start=item["start"], end=item["end"], text=item["text"], score=item["confidence"] + ) + for item in raw + ] + logger.debug("detected spans: count=%d", len(spans)) + usage = [Usage(model_id=self.model_id, model_version=self.model_version, units={})] + return Detection(spans=spans, usage=usage) + + # ------------------------------------------------------------------ + # Chunking helpers + # ------------------------------------------------------------------ + + def _group_passages_into_chunks( + self, + context: list[str], + question: str | None, + answer: str, + ) -> list[list[str]]: + """Group passages into chunks so each chunk, wrapped in the full instruction template, fits in ``max_length``. + + Preserves the instruction template (question, "Bear in mind...", etc.) + in every chunk by working at the passage level instead of slicing raw + tokens. + + :param context: List of passage strings. + :param question: Original question (``None`` for summarisation). + :param answer: The answer string (token budget is reserved). + :returns: List of passage groups. Each group will be formatted into a + complete prompt via ``PromptUtils.format_context``. + """ + answer_tokens = self.tokenizer(answer, add_special_tokens=False, return_tensors="pt")[ + "input_ids" + ].shape[1] + # Total prompt-token budget: max_length minus answer tokens minus 3 special tokens + total_budget = self.max_length - answer_tokens - 3 + + # Fast path: check whether all passages fit in one prompt. + full_prompt = PromptUtils.format_context(context, question, self.lang) + full_prompt_tokens = self.tokenizer( + full_prompt, add_special_tokens=False, return_tensors="pt" + )["input_ids"].shape[1] + + if full_prompt_tokens <= total_budget: + return [context] + + # Measure instruction overhead (everything except the passage content). + minimal_prompt = PromptUtils.format_context([""], question, self.lang) + instruction_overhead = self.tokenizer( + minimal_prompt, add_special_tokens=False, return_tensors="pt" + )["input_ids"].shape[1] + + passage_budget = total_budget - instruction_overhead + if passage_budget <= 0: + # Instructions + answer alone exceed max_length; single group, will truncate. + return [context] + + # Tokenize each formatted passage line to get its token count. + p_word = LANG_TO_PASSAGE[self.lang] + passage_token_counts: list[int] = [] + for i, passage in enumerate(context): + line = f"{p_word} {i + 1}: {passage}" + tok_count = self.tokenizer(line, add_special_tokens=False, return_tensors="pt")[ + "input_ids" + ].shape[1] + passage_token_counts.append(tok_count) + + # Greedily group passages into buckets that fit within the budget. + groups: list[list[str]] = [] + current_group: list[str] = [] + current_tokens = 0 + + for passage, tok_count in zip(context, passage_token_counts): + # +1 for the newline separator between passages + effective = tok_count + (1 if current_group else 0) + if current_tokens + effective > passage_budget and current_group: + groups.append(current_group) + current_group = [] + current_tokens = 0 + effective = tok_count + current_group.append(passage) + current_tokens += effective + + if current_group: + groups.append(current_group) + + return groups if groups else [context] + + # ------------------------------------------------------------------ + # Shared decoding helper for single-example and batched prediction + # ------------------------------------------------------------------ + + def _decode_sample( + self, + input_ids: torch.Tensor, + probabilities: torch.Tensor, + offsets: torch.Tensor, + answer_start_token: int, + answer: str, + output_format: str, + ) -> list: + """Decode one sample's model outputs into tokens or spans. + + Shared by the single-example and batched prediction paths so both produce + identical output for the same inputs. All tensors must already be trimmed + to this sample's true (unpadded) sequence length. + + :param input_ids: Token ids for the sample, shape ``(seq_len,)``. + :param probabilities: Softmax probabilities, shape ``(seq_len, num_labels)``. + :param offsets: Character offset mapping, shape ``(seq_len, 2)``. + :param answer_start_token: Index of the first answer-side token. + :param answer: The original answer string. + :param output_format: ``"tokens"`` or ``"spans"``. + """ + token_preds = torch.argmax(probabilities, dim=-1) + + if output_format == "tokens": + token_probs: list[dict] = [] + for i in range(answer_start_token, input_ids.size(0)): + token_probs.append( + { + "token": self.tokenizer.decode([input_ids[i]]), + "pred": token_preds[i].item(), + "prob": probabilities[i, 1].item(), + } + ) + return token_probs + + # output_format == "spans" + if answer_start_token < offsets.size(0): + answer_char_offset = offsets[answer_start_token][0].item() + else: + answer_char_offset = 0 + + spans: list[dict] = [] + current_span: dict | None = None + + for i in range(answer_start_token, token_preds.size(0)): + token_start, token_end = offsets[i].tolist() + if token_start == token_end: + continue + + rel_start = token_start - answer_char_offset + rel_end = token_end - answer_char_offset + + is_hallucination = token_preds[i].item() == 1 + confidence = probabilities[i, 1].item() if is_hallucination else 0.0 + + if is_hallucination: + if current_span is None: + current_span = {"start": rel_start, "end": rel_end, "confidence": confidence} + else: + current_span["end"] = rel_end + current_span["confidence"] = max(current_span["confidence"], confidence) + else: + if current_span is not None: + current_span["text"] = answer[current_span["start"] : current_span["end"]] + spans.append(current_span) + current_span = None + + if current_span is not None: + current_span["text"] = answer[current_span["start"] : current_span["end"]] + spans.append(current_span) + + return spans + + # ------------------------------------------------------------------ + # Single-chunk prediction (the original _predict logic) + # ------------------------------------------------------------------ + + def _predict_single(self, prompt: str, answer: str, output_format: str) -> list: + """Run prediction on a single (prompt, answer) pair that fits in ``max_length``. + + :param prompt: The prompt string. + :param answer: The answer string. + :param output_format: ``"tokens"`` or ``"spans"``. + """ + encoding, _, offsets, answer_start_token = HallucinationDataset.prepare_tokenized_input( + self.tokenizer, prompt, answer, self.max_length + ) + + encoding = { + key: value.to(self.device) + for key, value in encoding.items() + if key in ["input_ids", "attention_mask", "labels"] + } + + with torch.no_grad(): + outputs = self.model(**encoding) + probabilities = torch.softmax(outputs.logits, dim=-1)[0] + input_ids = encoding["input_ids"][0] + + return self._decode_sample( + input_ids, probabilities, offsets, answer_start_token, answer, output_format + ) + + # ------------------------------------------------------------------ + # Batched prediction with one forward pass for many pairs + # ------------------------------------------------------------------ + + def _predict_batch( + self, prompts: list[str], answers: list[str], output_format: str + ) -> list[list]: + """Tokenize ``prompts``/``answers`` as one padded batch and score them in one pass. + + :param prompts: Prompt strings for this batch (already length-validated + against ``answers`` by the caller). + :param answers: Answer strings for this batch. + :param output_format: ``"tokens"`` or ``"spans"``. + :returns: One prediction list per (prompt, answer) pair, in input order. + """ + with self._get_scoring_lock(): + if self.tokenizer.padding_side != "right": + raise ValueError( + "TransformerDetector batched inference requires a right-padding tokenizer." + ) + + batch = self.tokenizer( + prompts, + answers, + truncation="only_first", + max_length=self.max_length, + padding=True, + return_offsets_mapping=True, + return_tensors="pt", + add_special_tokens=True, + ) + offsets = batch.pop("offset_mapping") + seq_lens = batch["attention_mask"].sum(dim=1) + + model_inputs = { + key: value.to(self.device) + for key, value in batch.items() + if key in ["input_ids", "attention_mask"] + } + + with torch.no_grad(): + outputs = self.model(**model_inputs) + probabilities = torch.softmax(outputs.logits, dim=-1) + + results: list[list] = [] + for i, answer in enumerate(answers): + seq_len = int(seq_lens[i].item()) + sequence_ids = batch.sequence_ids(i) + answer_start_token = next( + (idx for idx, seq_id in enumerate(sequence_ids) if seq_id == 1), + seq_len - 1, + ) + + if seq_len >= self.max_length: + logger.warning( + "predict_prompt_batch: item %d (%d tokens) reached " + "max length (%d) and may have been truncated.", + i, + seq_len, + self.max_length, + ) + + results.append( + self._decode_sample( + batch["input_ids"][i, :seq_len], + probabilities[i, :seq_len], + offsets[i, :seq_len], + answer_start_token, + answer, + output_format, + ) + ) + return results + + # ------------------------------------------------------------------ + # Multi-chunk prediction with max() aggregation + # ------------------------------------------------------------------ + + def _predict_chunked(self, chunk_prompts: list[str], answer: str, output_format: str) -> list: + """Run prediction over multiple context chunks and aggregate with ``max()``. + + For each answer token, the hallucination probability is the maximum + across all chunks. This is conservative: a token is only considered + supported if *every* chunk considers it supported. + + :param chunk_prompts: Context chunk strings. + :param answer: The answer string (same for all chunks). + :param output_format: ``"tokens"`` or ``"spans"``. + """ + all_token_results: list[list[dict]] = [] + for chunk in chunk_prompts: + tokens = self._predict_single(chunk, answer, output_format="tokens") + all_token_results.append(tokens) + + n_tokens = len(all_token_results[0]) + + # Aggregate: max hallucination probability across chunks. + aggregated: list[dict] = [] + for tok_idx in range(n_tokens): + max_prob = max( + chunk_result[tok_idx]["prob"] + for chunk_result in all_token_results + if tok_idx < len(chunk_result) + ) + aggregated.append( + { + "token": all_token_results[0][tok_idx]["token"], + "pred": 1 if max_prob >= 0.5 else 0, + "prob": max_prob, + } + ) + + if output_format == "tokens": + return aggregated + + # For "spans", build character spans from the aggregated token predictions. + # Use offset mapping from the first chunk (answer offsets are identical + # across chunks because BERT tokenizers process segments independently). + return self._build_spans_from_tokens(aggregated, chunk_prompts[0], answer) + + def _build_spans_from_tokens( + self, token_results: list[dict], prompt: str, answer: str + ) -> list[dict]: + """Convert aggregated token predictions into character-level spans. + + Uses the tokenizer offset mapping from encoding *(prompt, answer)* to + get precise character positions within the answer. + + :param token_results: Per-answer-token dicts with ``token``, ``pred``, ``prob``. + :param prompt: A context prompt string (used to get answer offset mapping). + :param answer: The original answer string. + :returns: List of span dicts with ``start``, ``end``, ``confidence``, ``text``. + """ + _, _, offsets, answer_start_token = HallucinationDataset.prepare_tokenized_input( + self.tokenizer, prompt, answer, self.max_length + ) + + if answer_start_token < offsets.size(0): + answer_char_offset = offsets[answer_start_token][0].item() + else: + answer_char_offset = 0 + + # Collect answer-region offsets (skip special tokens with zero length). + answer_offsets: list[tuple[int, int]] = [] + for i in range(answer_start_token, offsets.size(0)): + s, e = offsets[i].tolist() + if s == e: + continue + answer_offsets.append((s - answer_char_offset, e - answer_char_offset)) + + spans: list[dict] = [] + current_span: dict | None = None + + for tok_idx, tok in enumerate(token_results): + if tok_idx >= len(answer_offsets): + break + rel_start, rel_end = answer_offsets[tok_idx] + is_hall = tok["pred"] == 1 + confidence = tok["prob"] if is_hall else 0.0 + + if is_hall: + if current_span is None: + current_span = { + "start": rel_start, + "end": rel_end, + "confidence": confidence, + } + else: + current_span["end"] = rel_end + current_span["confidence"] = max(current_span["confidence"], confidence) + else: + if current_span is not None: + current_span["text"] = answer[current_span["start"] : current_span["end"]] + spans.append(current_span) + current_span = None + + if current_span is not None: + current_span["text"] = answer[current_span["start"] : current_span["end"]] + spans.append(current_span) + + return spans diff --git a/lettucedetect/detectors/transformer.py b/lettucedetect/detectors/transformer.py index c488ddf..95f822f 100644 --- a/lettucedetect/detectors/transformer.py +++ b/lettucedetect/detectors/transformer.py @@ -7,8 +7,7 @@ import torch from transformers import AutoModelForTokenClassification, AutoTokenizer -from lettucedetect.datasets.hallucination_dataset import HallucinationDataset -from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.encoder import EncoderDetector from lettucedetect.detectors.prompt_utils import LANG_TO_PASSAGE, Lang, PromptUtils logger = logging.getLogger(__name__) @@ -16,7 +15,7 @@ __all__ = ["TransformerDetector"] -class TransformerDetector(BaseDetector): +class TransformerDetector(EncoderDetector): """Detect hallucinations with a fine-tuned token classifier. When the combined context + answer exceeds ``max_length`` tokens, the @@ -77,371 +76,6 @@ def __init__( subcategories=subcategories, ) - # ------------------------------------------------------------------ - # Chunking helpers - # ------------------------------------------------------------------ - - def _group_passages_into_chunks( - self, - context: list[str], - question: str | None, - answer: str, - ) -> list[list[str]]: - """Group passages into chunks so each chunk, wrapped in the full instruction template, fits in ``max_length``. - - Preserves the instruction template (question, "Bear in mind...", etc.) - in every chunk by working at the passage level instead of slicing raw - tokens. - - :param context: List of passage strings. - :param question: Original question (``None`` for summarisation). - :param answer: The answer string (token budget is reserved). - :returns: List of passage groups. Each group will be formatted into a - complete prompt via ``PromptUtils.format_context``. - """ - answer_tokens = self.tokenizer(answer, add_special_tokens=False, return_tensors="pt")[ - "input_ids" - ].shape[1] - # Total prompt-token budget: max_length minus answer tokens minus 3 special tokens - total_budget = self.max_length - answer_tokens - 3 - - # Fast path: check whether all passages fit in one prompt. - full_prompt = PromptUtils.format_context(context, question, self.lang) - full_prompt_tokens = self.tokenizer( - full_prompt, add_special_tokens=False, return_tensors="pt" - )["input_ids"].shape[1] - - if full_prompt_tokens <= total_budget: - return [context] - - # Measure instruction overhead (everything except the passage content). - minimal_prompt = PromptUtils.format_context([""], question, self.lang) - instruction_overhead = self.tokenizer( - minimal_prompt, add_special_tokens=False, return_tensors="pt" - )["input_ids"].shape[1] - - passage_budget = total_budget - instruction_overhead - if passage_budget <= 0: - # Instructions + answer alone exceed max_length; single group, will truncate. - return [context] - - # Tokenize each formatted passage line to get its token count. - p_word = LANG_TO_PASSAGE[self.lang] - passage_token_counts: list[int] = [] - for i, passage in enumerate(context): - line = f"{p_word} {i + 1}: {passage}" - tok_count = self.tokenizer(line, add_special_tokens=False, return_tensors="pt")[ - "input_ids" - ].shape[1] - passage_token_counts.append(tok_count) - - # Greedily group passages into buckets that fit within the budget. - groups: list[list[str]] = [] - current_group: list[str] = [] - current_tokens = 0 - - for passage, tok_count in zip(context, passage_token_counts): - # +1 for the newline separator between passages - effective = tok_count + (1 if current_group else 0) - if current_tokens + effective > passage_budget and current_group: - groups.append(current_group) - current_group = [] - current_tokens = 0 - effective = tok_count - current_group.append(passage) - current_tokens += effective - - if current_group: - groups.append(current_group) - - return groups if groups else [context] - - # ------------------------------------------------------------------ - # Shared decoding helper for single-example and batched prediction - # ------------------------------------------------------------------ - - def _decode_sample( - self, - input_ids: torch.Tensor, - probabilities: torch.Tensor, - offsets: torch.Tensor, - answer_start_token: int, - answer: str, - output_format: str, - ) -> list: - """Decode one sample's model outputs into tokens or spans. - - Shared by the single-example and batched prediction paths so both produce - identical output for the same inputs. All tensors must already be trimmed - to this sample's true (unpadded) sequence length. - - :param input_ids: Token ids for the sample, shape ``(seq_len,)``. - :param probabilities: Softmax probabilities, shape ``(seq_len, num_labels)``. - :param offsets: Character offset mapping, shape ``(seq_len, 2)``. - :param answer_start_token: Index of the first answer-side token. - :param answer: The original answer string. - :param output_format: ``"tokens"`` or ``"spans"``. - """ - token_preds = torch.argmax(probabilities, dim=-1) - - if output_format == "tokens": - token_probs: list[dict] = [] - for i in range(answer_start_token, input_ids.size(0)): - token_probs.append( - { - "token": self.tokenizer.decode([input_ids[i]]), - "pred": token_preds[i].item(), - "prob": probabilities[i, 1].item(), - } - ) - return token_probs - - # output_format == "spans" - if answer_start_token < offsets.size(0): - answer_char_offset = offsets[answer_start_token][0].item() - else: - answer_char_offset = 0 - - spans: list[dict] = [] - current_span: dict | None = None - - for i in range(answer_start_token, token_preds.size(0)): - token_start, token_end = offsets[i].tolist() - if token_start == token_end: - continue - - rel_start = token_start - answer_char_offset - rel_end = token_end - answer_char_offset - - is_hallucination = token_preds[i].item() == 1 - confidence = probabilities[i, 1].item() if is_hallucination else 0.0 - - if is_hallucination: - if current_span is None: - current_span = {"start": rel_start, "end": rel_end, "confidence": confidence} - else: - current_span["end"] = rel_end - current_span["confidence"] = max(current_span["confidence"], confidence) - else: - if current_span is not None: - current_span["text"] = answer[current_span["start"] : current_span["end"]] - spans.append(current_span) - current_span = None - - if current_span is not None: - current_span["text"] = answer[current_span["start"] : current_span["end"]] - spans.append(current_span) - - return spans - - # ------------------------------------------------------------------ - # Single-chunk prediction (the original _predict logic) - # ------------------------------------------------------------------ - - def _predict_single(self, prompt: str, answer: str, output_format: str) -> list: - """Run prediction on a single (prompt, answer) pair that fits in ``max_length``. - - :param prompt: The prompt string. - :param answer: The answer string. - :param output_format: ``"tokens"`` or ``"spans"``. - """ - encoding, _, offsets, answer_start_token = HallucinationDataset.prepare_tokenized_input( - self.tokenizer, prompt, answer, self.max_length - ) - - encoding = { - key: value.to(self.device) - for key, value in encoding.items() - if key in ["input_ids", "attention_mask", "labels"] - } - - with torch.no_grad(): - outputs = self.model(**encoding) - probabilities = torch.softmax(outputs.logits, dim=-1)[0] - input_ids = encoding["input_ids"][0] - - return self._decode_sample( - input_ids, probabilities, offsets, answer_start_token, answer, output_format - ) - - # ------------------------------------------------------------------ - # Batched prediction with one forward pass for many pairs - # ------------------------------------------------------------------ - - def _predict_batch( - self, prompts: list[str], answers: list[str], output_format: str - ) -> list[list]: - """Tokenize ``prompts``/``answers`` as one padded batch and score them in one pass. - - :param prompts: Prompt strings for this batch (already length-validated - against ``answers`` by the caller). - :param answers: Answer strings for this batch. - :param output_format: ``"tokens"`` or ``"spans"``. - :returns: One prediction list per (prompt, answer) pair, in input order. - """ - if self.tokenizer.padding_side != "right": - raise ValueError( - "TransformerDetector batched inference requires a right-padding tokenizer." - ) - - batch = self.tokenizer( - prompts, - answers, - truncation="only_first", - max_length=self.max_length, - padding=True, - return_offsets_mapping=True, - return_tensors="pt", - add_special_tokens=True, - ) - offsets = batch.pop("offset_mapping") - seq_lens = batch["attention_mask"].sum(dim=1) - - model_inputs = { - key: value.to(self.device) - for key, value in batch.items() - if key in ["input_ids", "attention_mask"] - } - - with torch.no_grad(): - outputs = self.model(**model_inputs) - probabilities = torch.softmax(outputs.logits, dim=-1) - - results: list[list] = [] - for i, answer in enumerate(answers): - seq_len = int(seq_lens[i].item()) - sequence_ids = batch.sequence_ids(i) - answer_start_token = next( - (idx for idx, seq_id in enumerate(sequence_ids) if seq_id == 1), - seq_len - 1, - ) - - if seq_len >= self.max_length: - logger.warning( - f"predict_prompt_batch: item {i} ({seq_len} tokens) reached " - f"max length ({self.max_length}) and may have been truncated." - ) - - results.append( - self._decode_sample( - batch["input_ids"][i, :seq_len], - probabilities[i, :seq_len], - offsets[i, :seq_len], - answer_start_token, - answer, - output_format, - ) - ) - return results - - # ------------------------------------------------------------------ - # Multi-chunk prediction with max() aggregation - # ------------------------------------------------------------------ - - def _predict_chunked(self, chunk_prompts: list[str], answer: str, output_format: str) -> list: - """Run prediction over multiple context chunks and aggregate with ``max()``. - - For each answer token, the hallucination probability is the maximum - across all chunks. This is conservative: a token is only considered - supported if *every* chunk considers it supported. - - :param chunk_prompts: Context chunk strings. - :param answer: The answer string (same for all chunks). - :param output_format: ``"tokens"`` or ``"spans"``. - """ - all_token_results: list[list[dict]] = [] - for chunk in chunk_prompts: - tokens = self._predict_single(chunk, answer, output_format="tokens") - all_token_results.append(tokens) - - n_tokens = len(all_token_results[0]) - - # Aggregate: max hallucination probability across chunks. - aggregated: list[dict] = [] - for tok_idx in range(n_tokens): - max_prob = max( - chunk_result[tok_idx]["prob"] - for chunk_result in all_token_results - if tok_idx < len(chunk_result) - ) - aggregated.append( - { - "token": all_token_results[0][tok_idx]["token"], - "pred": 1 if max_prob >= 0.5 else 0, - "prob": max_prob, - } - ) - - if output_format == "tokens": - return aggregated - - # For "spans", build character spans from the aggregated token predictions. - # Use offset mapping from the first chunk (answer offsets are identical - # across chunks because BERT tokenizers process segments independently). - return self._build_spans_from_tokens(aggregated, chunk_prompts[0], answer) - - def _build_spans_from_tokens( - self, token_results: list[dict], prompt: str, answer: str - ) -> list[dict]: - """Convert aggregated token predictions into character-level spans. - - Uses the tokenizer offset mapping from encoding *(prompt, answer)* to - get precise character positions within the answer. - - :param token_results: Per-answer-token dicts with ``token``, ``pred``, ``prob``. - :param prompt: A context prompt string (used to get answer offset mapping). - :param answer: The original answer string. - :returns: List of span dicts with ``start``, ``end``, ``confidence``, ``text``. - """ - _, _, offsets, answer_start_token = HallucinationDataset.prepare_tokenized_input( - self.tokenizer, prompt, answer, self.max_length - ) - - if answer_start_token < offsets.size(0): - answer_char_offset = offsets[answer_start_token][0].item() - else: - answer_char_offset = 0 - - # Collect answer-region offsets (skip special tokens with zero length). - answer_offsets: list[tuple[int, int]] = [] - for i in range(answer_start_token, offsets.size(0)): - s, e = offsets[i].tolist() - if s == e: - continue - answer_offsets.append((s - answer_char_offset, e - answer_char_offset)) - - spans: list[dict] = [] - current_span: dict | None = None - - for tok_idx, tok in enumerate(token_results): - if tok_idx >= len(answer_offsets): - break - rel_start, rel_end = answer_offsets[tok_idx] - is_hall = tok["pred"] == 1 - confidence = tok["prob"] if is_hall else 0.0 - - if is_hall: - if current_span is None: - current_span = { - "start": rel_start, - "end": rel_end, - "confidence": confidence, - } - else: - current_span["end"] = rel_end - current_span["confidence"] = max(current_span["confidence"], confidence) - else: - if current_span is not None: - current_span["text"] = answer[current_span["start"] : current_span["end"]] - spans.append(current_span) - current_span = None - - if current_span is not None: - current_span["text"] = answer[current_span["start"] : current_span["end"]] - spans.append(current_span) - - return spans - # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ diff --git a/tests/test_encoder_detector_pytest.py b/tests/test_encoder_detector_pytest.py new file mode 100644 index 0000000..a471b10 --- /dev/null +++ b/tests/test_encoder_detector_pytest.py @@ -0,0 +1,271 @@ +"""Tests for ``EncoderDetector`` and ``EncoderConfig``: offline, with a stub model.""" + +from __future__ import annotations + +import asyncio +import json +import threading +import time +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors.encoder import EncoderConfig, EncoderDetector +from lettucedetect.detectors.errors import ConfigurationError +from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput +from tests.detector_contract import DetectorContract +from tests.golden import GOLDEN_DIR +from tests.test_golden_transformer_pytest import ( + ANSWERS, + MULTI_ANSWER, + MULTI_CONTEXT, + MULTI_MAX_LENGTH, + MULTI_QUESTION, + PREDICT_INPUTS, + PROMPTS, + _stub_forward, +) + + +def _stub_model(on_call=None, delay: float = 0.0): + def forward(input_ids=None, attention_mask=None, **kwargs): + if on_call is not None: + on_call() + if delay: + time.sleep(delay) + return _stub_forward(input_ids=input_ids, attention_mask=attention_mask) + + return MagicMock(side_effect=forward) + + +def _detector(tokenizer, max_length=512, **model_kwargs) -> EncoderDetector: + return EncoderDetector( + _stub_model(**model_kwargs), + tokenizer, + config=EncoderConfig(max_length=max_length), + model_id="stub-encoder", + ) + + +def _sources(context, answer, question=None) -> SourcesInput: + return SourcesInput( + sources=[Chunk(id=str(i), text=t) for i, t in enumerate(context)], + answer=answer, + question=question, + ) + + +def _as_confidence(detection) -> list[dict]: + return [ + {"start": s.start, "end": s.end, "confidence": s.score, "text": s.text} + for s in detection.spans + ] + + +# -- construction and config -------------------------------------------------------------- + + +def test_construction_is_offline_and_leaves_cwd_empty( + tmp_path, monkeypatch, local_wordpiece_tokenizer +): + """Building from objects downloads nothing and writes no file.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + boom = MagicMock(side_effect=AssertionError("download attempted")) + with ( + patch("transformers.AutoTokenizer.from_pretrained", boom), + patch("transformers.AutoModelForTokenClassification.from_pretrained", boom), + ): + EncoderDetector(_stub_model(), local_wordpiece_tokenizer) + assert list(tmp_path.iterdir()) == [] + boom.assert_not_called() + + +def test_config_defaults(): + config = EncoderConfig() + assert (config.max_length, config.batch_size, config.lang) == (4096, 16, "en") + + +@pytest.mark.parametrize( + ("kwargs", "code", "param"), + [ + ({"colour": 1}, "invalid_config", "colour"), + ({"lang": "xx"}, "invalid_language", "lang"), + ({"batch_size": 0}, "invalid_batch_size", "batch_size"), + ({"max_length": 0}, "invalid_config", "max_length"), + ], +) +def test_config_errors_carry_code_and_param(kwargs, code, param): + with pytest.raises(ConfigurationError) as exc: + EncoderConfig(**kwargs) + assert (exc.value.code, exc.value.param) == (code, param) + with pytest.raises(ConfigurationError): + EncoderConfig.model_validate(kwargs) + + +# -- results ------------------------------------------------------------------------------ + + +def _golden(name: str): + return json.loads((GOLDEN_DIR / f"{name}.json").read_text()) + + +def _round(spans: list[dict]) -> list[dict]: + return [{**s, "confidence": round(s["confidence"], 6)} for s in spans] + + +def test_sources_spans_equal_golden_output(local_wordpiece_tokenizer): + """Detect spans equal today's predict(spans) fixtures, with score = confidence.""" + det = _detector(local_wordpiece_tokenizer) + got = [_round(_as_confidence(det.detect(_sources(*inp)))) for inp in PREDICT_INPUTS] + assert got == [_round(x) for x in _golden("transformer_predict_spans")] + + +def test_prompt_spans_equal_golden_output(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer) + got = [ + _round(_as_confidence(det.detect(PromptInput(prompt=p, answer=a)))) + for p, a in zip(PROMPTS, ANSWERS, strict=True) + ] + assert got == [_round(x) for x in _golden("transformer_predict_prompt_spans")] + + +def test_multi_group_sources_equal_golden_output(local_wordpiece_tokenizer): + """Several passage groups are aggregated with max(), as today.""" + det = _detector(local_wordpiece_tokenizer, max_length=MULTI_MAX_LENGTH) + assert len(det._group_passages_into_chunks(MULTI_CONTEXT, MULTI_QUESTION, MULTI_ANSWER)) > 1 + got = _round(_as_confidence(det.detect(_sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION)))) + assert got == _round(_golden("transformer_predict_multi_group_spans")["output"]) + + +async def test_adetect_equals_detect(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer) + for request in ( + _sources(*PREDICT_INPUTS[0]), + PromptInput(prompt=PROMPTS[0], answer=ANSWERS[0]), + ): + assert await det.adetect(request) == det.detect(request) + + +# -- concurrency -------------------------------------------------------------------------- + + +async def test_concurrent_adetect_calls_do_not_overlap(local_wordpiece_tokenizer): + state = {"active": 0, "max": 0} + guard = threading.Lock() + + def on_call(): + with guard: + state["active"] += 1 + state["max"] = max(state["max"], state["active"]) + time.sleep(0.005) + with guard: + state["active"] -= 1 + + det = _detector(local_wordpiece_tokenizer, max_length=MULTI_MAX_LENGTH, on_call=on_call) + requests = [] + for i in range(20): + word = ["paris", "word", "france", "capital"][i % 4] + answer = " ".join([word, "the", "capital", "of", "france"] * (1 + i % 5)) + if i % 3 == 0: + requests.append(_sources(MULTI_CONTEXT, answer, MULTI_QUESTION)) + elif i % 3 == 1: + requests.append( + PromptInput(prompt=" ".join(["the capital of france"] * (i * 3)), answer=answer) + ) + else: + requests.append(_sources(["short answer word ."], answer)) + expected = [det.detect(r) for r in requests] + state["max"] = 0 + results = await asyncio.gather(*(det.adetect(r) for r in requests)) + assert list(results) == expected + assert state["max"] == 1 + + +async def test_padded_batches_and_adetect_do_not_overlap(local_wordpiece_tokenizer): + """Padded batch scoring takes the same lock as detect, so mixed calls never overlap.""" + state = {"active": 0, "max": 0} + guard = threading.Lock() + + def on_call(): + with guard: + state["active"] += 1 + state["max"] = max(state["max"], state["active"]) + time.sleep(0.005) + with guard: + state["active"] -= 1 + + det = _detector(local_wordpiece_tokenizer, on_call=on_call) + batches = [(PROMPTS[: 1 + i % 3], ANSWERS[: 1 + i % 3]) for i in range(8)] + requests = [_sources(*PREDICT_INPUTS[i % len(PREDICT_INPUTS)]) for i in range(8)] + expected_batches = [det._predict_batch(p, a, "spans") for p, a in batches] + expected = [det.detect(r) for r in requests] + probe = local_wordpiece_tokenizer( + PROMPTS[:3], ANSWERS[:3], padding=True, truncation="only_first", return_tensors="pt" + ) + assert (probe["attention_mask"] == 0).any() # the batches really contain padding + state["max"] = 0 + results = await asyncio.gather( + *(asyncio.to_thread(det._predict_batch, p, a, "spans") for p, a in batches), + *(det.adetect(r) for r in requests), + ) + assert list(results[:8]) == expected_batches + assert list(results[8:]) == expected + assert state["max"] == 1 + + +def test_racing_first_calls_create_exactly_one_lock(local_wordpiece_tokenizer): + det = EncoderDetector.__new__(EncoderDetector) + det.model, det.tokenizer = _stub_model(), local_wordpiece_tokenizer + det.device, det.max_length, det.lang, det.typer = torch.device("cpu"), 512, "en", None + created = [] + real = threading.RLock + + def slow_rlock(): + time.sleep(0.05) + lock = real() + created.append(lock) + return lock + + barrier = threading.Barrier(8) + seen = [] + + def race(): + barrier.wait() + seen.append(det._get_scoring_lock()) + + with patch("lettucedetect.detectors.encoder.threading.RLock", slow_rlock): + threads = [threading.Thread(target=race) for _ in range(8)] + for t in threads: + t.start() + for t in threads: + t.join() + assert len(created) == 1 + assert all(lock is created[0] for lock in seen) + assert det.detect(_sources(*PREDICT_INPUTS[0])).spans is not None + + +# -- contract ----------------------------------------------------------------------------- + + +class TestEncoderDetectorContract(DetectorContract): + """The detector contract suite, run against an EncoderDetector with a stub model.""" + + sources_request = _sources( + ["the capital of france is paris . short answer word ."], + "paris is the capital of france and the answer is a short word and paris again", + "the capital of france ?", + ) + prompt_request = PromptInput( + prompt="the capital of france is paris . the capital of france", + answer="the capital of france is paris and paris is a short answer word again", + ) + + @pytest.fixture(autouse=True) + def _tokenizer(self, local_wordpiece_tokenizer): + self.tokenizer = local_wordpiece_tokenizer + + def make_detector(self, on_call=None): + """Build a detector whose stub model calls ``on_call`` in its forward pass.""" + return _detector(self.tokenizer, on_call=on_call) From 97b7873a102d83b542b6af2fefc4f9e8013d016d Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 12:56:37 +0100 Subject: [PATCH 24/60] feat: add token scores, input_truncated and usage to EncoderDetector (#150) --- lettucedetect/detectors/encoder.py | 251 ++++++++++++++++++++++---- tests/test_encoder_detector_pytest.py | 231 ++++++++++++++++++++++++ 2 files changed, 442 insertions(+), 40 deletions(-) diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py index 00bfc19..54bcc58 100644 --- a/lettucedetect/detectors/encoder.py +++ b/lettucedetect/detectors/encoder.py @@ -4,6 +4,7 @@ import logging import threading +import time from typing import Any import torch @@ -17,7 +18,9 @@ DetectedSpan, Detection, DetectRequest, + ResultWarning, SourcesInput, + TokenScore, Usage, ) @@ -113,6 +116,7 @@ class EncoderDetector(BaseDetector): :param model_version: version reported in ``usage``. """ + supports_tokens = True model_id: str | None = None model_version: str | None = None typer: Any = None @@ -170,43 +174,217 @@ def _get_scoring_lock(self) -> threading.RLock: def _detect( self, request: DetectRequest, *, include_tokens: bool, include_detail: bool ) -> Detection: - """Score a request and return its spans. + """Score a request and return its spans, optional token scores, usage and warnings. + + One forward pass per passage group serves the spans, the tokens, the usage and the + truncation check. :param request: the sources (or prompt) and the answer to check. - :param include_tokens: unused until token scores are supported. + :param include_tokens: whether to fill ``Detection.tokens``. :param include_detail: unused, there is no detail. :returns: the detection result. """ + answer = request.answer + units: dict[str, int] = {"answer_chars": len(answer)} + requested = time.perf_counter() with self._get_scoring_lock(): + started = time.perf_counter() + logger.debug( + "detect started: kind=%s model_id=%s include_tokens=%s lock_wait_ms=%.1f", + request.kind, + self.model_id, + include_tokens, + (started - requested) * 1000, + ) if isinstance(request, SourcesInput): context = [chunk.text for chunk in request.sources] - groups = self._group_passages_into_chunks(context, request.question, request.answer) + groups = self._group_passages_into_chunks(context, request.question, answer) logger.debug( "scoring sources request: sources=%d passage_groups=%d", len(context), len(groups), ) - if len(groups) == 1: - prompt = PromptUtils.format_context(groups[0], request.question, self.lang) - raw = self._predict_single(prompt, request.answer, "spans") - else: - prompts = [ - PromptUtils.format_context(group, request.question, self.lang) - for group in groups - ] - raw = self._predict_chunked(prompts, request.answer, "spans") + prompts = [ + PromptUtils.format_context(group, request.question, self.lang) + for group in groups + ] + units["sources"] = len(context) + units["source_chars"] = sum(len(text) for text in context) else: - logger.debug("scoring prompt request") - raw = self._predict_single(request.prompt, request.answer, "spans") + prompts = [request.prompt] + units["source_chars"] = len(request.prompt) + scored = [self._score_tokens(prompt, answer) for prompt in prompts] + scoring_ms = (time.perf_counter() - started) * 1000 + + truncated = False + for index, (_, input_tokens, full_tokens) in enumerate(scored): + if full_tokens is not None: + truncated = True + logger.warning( + "input_truncated: group %d of %d has %d tokens, max_length is %d", + index + 1, + len(scored), + full_tokens, + self.max_length, + ) + units["input_tokens"] = sum(input_tokens for _, input_tokens, _ in scored) + + tokens = ( + scored[0][0] + if len(scored) == 1 + else self._max_aggregate([group_tokens for group_tokens, _, _ in scored]) + ) spans = [ DetectedSpan( start=item["start"], end=item["end"], text=item["text"], score=item["confidence"] ) - for item in raw + for item in self._spans_from_scored_tokens(tokens, answer) ] - logger.debug("detected spans: count=%d", len(spans)) - usage = [Usage(model_id=self.model_id, model_version=self.model_version, units={})] - return Detection(spans=spans, usage=usage) + logger.debug( + "detect finished: spans=%d answer_tokens=%d input_tokens=%d groups=%d " + "truncated=%s scoring_ms=%.1f", + len(spans), + len(tokens), + units["input_tokens"], + len(scored), + truncated, + scoring_ms, + ) + token_scores = ( + [ + TokenScore( + token=t["token"], + start=t["start"], + end=t["end"], + score=t["prob"], + flagged=t["pred"] == 1, + ) + for t in tokens + ] + if include_tokens + else None + ) + warnings = ( + [ + ResultWarning( + code="input_truncated", + message=( + "The input exceeded max_length tokens and was cut; raise max_length " + "or pass sources so passages are split into groups." + ), + ) + ] + if truncated + else [] + ) + usage = [Usage(model_id=self.model_id, model_version=self.model_version, units=units)] + return Detection(spans=spans, tokens=token_scores, usage=usage, warnings=warnings) + + def _score_tokens(self, prompt: str, answer: str) -> tuple[list[dict], int, int | None]: + """Score the answer tokens of one (prompt, answer) pair. + + :param prompt: the prompt string. + :param answer: the answer string. + :returns: the answer tokens as dicts with ``token``, ``pred``, ``prob`` and the answer + offsets ``start`` and ``end``; the number of tokens fed to the model; and the + untruncated token count when the input was cut, else ``None``. + """ + input_ids, probabilities, offsets, answer_start_token = self._run_model(prompt, answer) + seq_len = int(input_ids.size(0)) + logger.debug( + "scored one group: input_tokens=%d answer_tokens=%d max_length=%d", + seq_len, + seq_len - answer_start_token, + self.max_length, + ) + full_tokens = None + if seq_len >= self.max_length: + # Count only at the limit: an input that fits exactly is not truncated. + total = self.tokenizer(prompt, answer, add_special_tokens=True, return_tensors="pt")[ + "input_ids" + ].shape[1] + if total > self.max_length: + full_tokens = int(total) + token_preds = torch.argmax(probabilities, dim=-1) + if answer_start_token < offsets.size(0): + answer_char_offset = offsets[answer_start_token][0].item() + else: + answer_char_offset = 0 + tokens: list[dict] = [] + for i in range(answer_start_token, seq_len): + start, end = offsets[i].tolist() + if start == end: # special token such as the trailing [SEP]: zero-width at the end + start = end = len(answer) + else: + start, end = start - answer_char_offset, end - answer_char_offset + tokens.append( + { + "token": self.tokenizer.decode([input_ids[i]]), + "pred": token_preds[i].item(), + "prob": probabilities[i, 1].item(), + "start": start, + "end": end, + } + ) + return tokens, seq_len, full_tokens + + @staticmethod + def _max_aggregate(all_token_results: list[list[dict]]) -> list[dict]: + """Aggregate per-group token results: the probability of a token is the ``max()``. + + A token is flagged when the aggregated probability is at least 0.5. Other keys (such as + offsets) come from the first group, whose answer offsets equal those of every group. + + :param all_token_results: one token list per group. + :returns: the aggregated token list. + """ + aggregated: list[dict] = [] + for tok_idx in range(len(all_token_results[0])): + max_prob = max( + chunk_result[tok_idx]["prob"] + for chunk_result in all_token_results + if tok_idx < len(chunk_result) + ) + aggregated.append( + { + **all_token_results[0][tok_idx], + "pred": 1 if max_prob >= 0.5 else 0, + "prob": max_prob, + } + ) + return aggregated + + @staticmethod + def _spans_from_scored_tokens(tokens: list[dict], answer: str) -> list[dict]: + """Merge consecutive flagged tokens into spans with the highest probability as score. + + :param tokens: token dicts with ``pred``, ``prob``, ``start`` and ``end``. + :param answer: the answer string. + :returns: span dicts with ``start``, ``end``, ``confidence`` and ``text``. + """ + spans: list[dict] = [] + current: dict | None = None + for token in tokens: + if token["start"] == token["end"]: + continue + if token["pred"] == 1: + if current is None: + current = { + "start": token["start"], + "end": token["end"], + "confidence": token["prob"], + } + else: + current["end"] = token["end"] + current["confidence"] = max(current["confidence"], token["prob"]) + elif current is not None: + current["text"] = answer[current["start"] : current["end"]] + spans.append(current) + current = None + if current is not None: + current["text"] = answer[current["start"] : current["end"]] + spans.append(current) + return spans # ------------------------------------------------------------------ # Chunking helpers @@ -376,6 +554,19 @@ def _predict_single(self, prompt: str, answer: str, output_format: str) -> list: :param answer: The answer string. :param output_format: ``"tokens"`` or ``"spans"``. """ + input_ids, probabilities, offsets, answer_start_token = self._run_model(prompt, answer) + return self._decode_sample( + input_ids, probabilities, offsets, answer_start_token, answer, output_format + ) + + def _run_model(self, prompt: str, answer: str) -> tuple[torch.Tensor, torch.Tensor, Any, int]: + """Tokenize one (prompt, answer) pair and run the model on it. + + :param prompt: The prompt string. + :param answer: The answer string. + :returns: token ids ``(seq_len,)``, probabilities ``(seq_len, num_labels)``, character + offsets and the index of the first answer token. + """ encoding, _, offsets, answer_start_token = HallucinationDataset.prepare_tokenized_input( self.tokenizer, prompt, answer, self.max_length ) @@ -389,11 +580,7 @@ def _predict_single(self, prompt: str, answer: str, output_format: str) -> list: with torch.no_grad(): outputs = self.model(**encoding) probabilities = torch.softmax(outputs.logits, dim=-1)[0] - input_ids = encoding["input_ids"][0] - - return self._decode_sample( - input_ids, probabilities, offsets, answer_start_token, answer, output_format - ) + return encoding["input_ids"][0], probabilities, offsets, answer_start_token # ------------------------------------------------------------------ # Batched prediction with one forward pass for many pairs @@ -489,23 +676,7 @@ def _predict_chunked(self, chunk_prompts: list[str], answer: str, output_format: tokens = self._predict_single(chunk, answer, output_format="tokens") all_token_results.append(tokens) - n_tokens = len(all_token_results[0]) - - # Aggregate: max hallucination probability across chunks. - aggregated: list[dict] = [] - for tok_idx in range(n_tokens): - max_prob = max( - chunk_result[tok_idx]["prob"] - for chunk_result in all_token_results - if tok_idx < len(chunk_result) - ) - aggregated.append( - { - "token": all_token_results[0][tok_idx]["token"], - "pred": 1 if max_prob >= 0.5 else 0, - "prob": max_prob, - } - ) + aggregated = self._max_aggregate(all_token_results) if output_format == "tokens": return aggregated diff --git a/tests/test_encoder_detector_pytest.py b/tests/test_encoder_detector_pytest.py index a471b10..168b2ff 100644 --- a/tests/test_encoder_detector_pytest.py +++ b/tests/test_encoder_detector_pytest.py @@ -4,6 +4,7 @@ import asyncio import json +import logging import threading import time from unittest.mock import MagicMock, patch @@ -13,6 +14,7 @@ from lettucedetect.detectors.encoder import EncoderConfig, EncoderDetector from lettucedetect.detectors.errors import ConfigurationError +from lettucedetect.detectors.prompt_utils import PromptUtils from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput from tests.detector_contract import DetectorContract from tests.golden import GOLDEN_DIR @@ -148,6 +150,235 @@ async def test_adetect_equals_detect(local_wordpiece_tokenizer): assert await det.adetect(request) == det.detect(request) +# -- tokens, truncation and usage --------------------------------------------------------- + + +def _as_old_tokens(detection) -> list[dict]: + return [ + {"token": t.token, "pred": int(t.flagged), "prob": round(t.score, 6)} + for t in detection.tokens + ] + + +def _round_tokens(tokens: list[dict]) -> list[dict]: + return [{**t, "prob": round(t["prob"], 6)} for t in tokens] + + +def test_tokens_equal_golden_output(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer) + got = [ + _as_old_tokens(det.detect(_sources(*inp), include_tokens=True)) for inp in PREDICT_INPUTS + ] + assert got == [_round_tokens(x) for x in _golden("transformer_predict_tokens")] + got = [ + _as_old_tokens(det.detect(PromptInput(prompt=p, answer=a), include_tokens=True)) + for p, a in zip(PROMPTS, ANSWERS, strict=True) + ] + assert got == [_round_tokens(x) for x in _golden("transformer_predict_prompt_tokens")] + + +def test_multi_group_tokens_equal_golden_output(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer, max_length=MULTI_MAX_LENGTH) + request = _sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION) + got = _as_old_tokens(det.detect(request, include_tokens=True)) + assert got == _round_tokens(_golden("transformer_predict_multi_group_tokens")["output"]) + + +def test_token_offsets_lie_in_the_answer_and_spans_cover_flagged_tokens(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer) + for inp in PREDICT_INPUTS: + request = _sources(*inp) + result = det.detect(request, include_tokens=True) + previous_end = 0 + for t in result.tokens: + assert 0 <= t.start <= t.end <= len(request.answer) + assert t.start >= previous_end or t.start == t.end + if t.start != t.end: + assert request.answer[t.start : t.end] == t.token + previous_end = t.end + assert result.tokens[-1].token == "[SEP]" # noqa: S105 + assert (result.tokens[-1].start, result.tokens[-1].end) == ( + len(request.answer), + len(request.answer), + ) + flagged = {(t.start, t.end) for t in result.tokens if t.flagged and t.start != t.end} + for span in result.spans: + assert any(s >= span.start and e <= span.end for s, e in flagged) + + +def test_tokens_are_not_filtered_by_min_score_and_absent_by_default(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer) + request = _sources(*PREDICT_INPUTS[0]) + everything = det.detect(request, include_tokens=True) + filtered = det.detect(request, include_tokens=True, min_score=1.0) + assert filtered.spans == [] + assert filtered.tokens == everything.tokens + assert det.detect(request).tokens is None + + +def test_group_scores_are_aggregated_with_max_of_the_per_group_scores(local_wordpiece_tokenizer): + """With group-dependent scores, each token's score is the max over the groups' own scores.""" + + def forward(input_ids=None, attention_mask=None, **kwargs): + score = ((input_ids * 7 + input_ids.sum()) % 11 - 5).float() / 2 + output = MagicMock() + output.logits = torch.stack([-score, score], dim=-1) + return output + + det = EncoderDetector( + MagicMock(side_effect=forward), + local_wordpiece_tokenizer, + config=EncoderConfig(max_length=MULTI_MAX_LENGTH), + ) + request = _sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION) + groups = det._group_passages_into_chunks(MULTI_CONTEXT, MULTI_QUESTION, MULTI_ANSWER) + per_group = [ + det.detect( + PromptInput( + prompt=PromptUtils.format_context(group, MULTI_QUESTION, "en"), answer=MULTI_ANSWER + ), + include_tokens=True, + ).tokens + for group in groups + ] + assert len(groups) > 1 + assert any(len({g[i].score for g in per_group}) > 1 for i in range(len(per_group[0]))) + merged = det.detect(request, include_tokens=True).tokens + assert [t.score for t in merged] == [ + max(g[i].score for g in per_group) for i in range(len(merged)) + ] + + +def test_tokens_cost_no_extra_forward_pass(local_wordpiece_tokenizer): + det = _detector(local_wordpiece_tokenizer, max_length=MULTI_MAX_LENGTH) + request = _sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION) + det.detect(request) + plain_calls = det.model.call_count + det.detect(request, include_tokens=True) + assert plain_calls > 1 + assert det.model.call_count == 2 * plain_calls + + +def _warning_codes(detection) -> list[str]: + return [w.code for w in detection.warnings] + + +def _truncation_records(caplog): + return [r for r in caplog.records if r.levelno == logging.WARNING] + + +def test_debug_log_traces_the_call_with_counts_only(local_wordpiece_tokenizer, caplog): + det = _detector(local_wordpiece_tokenizer, max_length=MULTI_MAX_LENGTH) + request = _sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION) + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + det.detect(request) + messages = [r.getMessage() for r in caplog.records] + assert any( + m.startswith("detect started: kind=sources") and "lock_wait_ms=" in m for m in messages + ) + assert any(m.startswith("scoring sources request: sources=4 passage_groups=") for m in messages) + assert sum(m.startswith("scored one group: input_tokens=") for m in messages) > 1 + assert any(m.startswith("detect finished: spans=") and "scoring_ms=" in m for m in messages) + assert all(r.levelno == logging.DEBUG for r in caplog.records) + assert not any(MULTI_ANSWER in m or MULTI_CONTEXT[0] in m for m in messages) + + +def test_overlong_prompt_warns_and_logs_counts_without_text(local_wordpiece_tokenizer, caplog): + prompt = " ".join(["the capital of france is paris ."] * 30) + answer = "paris is the capital of france" + det = _detector(local_wordpiece_tokenizer, max_length=40) + full = local_wordpiece_tokenizer(prompt, answer, return_tensors="pt")["input_ids"].shape[1] + with caplog.at_level(logging.DEBUG, logger="lettucedetect"): + result = det.detect(PromptInput(prompt=prompt, answer=answer)) + assert _warning_codes(result) == ["input_truncated"] + records = _truncation_records(caplog) + assert len(records) == 1 + message = records[0].getMessage() + assert "input_truncated" in message and str(full) in message and "40" in message + for record in caplog.records: + assert prompt not in record.getMessage() and answer not in record.getMessage() + + +def test_passage_group_that_still_exceeds_max_length_warns(local_wordpiece_tokenizer, caplog): + huge = " ".join(["the capital of france is paris ."] * 30) + det = _detector(local_wordpiece_tokenizer, max_length=100) + request = _sources([huge, "short answer word ."], "paris is the capital", "capital ?") + groups = det._group_passages_into_chunks( + [huge, "short answer word ."], "capital ?", "paris is the capital" + ) + assert len(groups) == 2 # the oversized passage is alone in its group + with caplog.at_level(logging.WARNING, logger="lettucedetect"): + result = det.detect(request) + assert _warning_codes(result) == ["input_truncated"] + assert len(_truncation_records(caplog)) >= 1 + + +def test_multi_group_input_that_fits_each_group_does_not_warn(local_wordpiece_tokenizer, caplog): + det = _detector(local_wordpiece_tokenizer, max_length=MULTI_MAX_LENGTH) + with caplog.at_level(logging.WARNING, logger="lettucedetect"): + result = det.detect(_sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION)) + assert result.warnings == [] + assert _truncation_records(caplog) == [] + + +def test_input_of_exactly_max_length_is_not_truncated(local_wordpiece_tokenizer): + prompt, answer = PROMPTS[2], ANSWERS[2] + full = local_wordpiece_tokenizer(prompt, answer, return_tensors="pt")["input_ids"].shape[1] + request = PromptInput(prompt=prompt, answer=answer) + assert _detector(local_wordpiece_tokenizer, max_length=full).detect(request).warnings == [] + cut = _detector(local_wordpiece_tokenizer, max_length=full - 1).detect(request) + assert _warning_codes(cut) == ["input_truncated"] + + +def _recording_detector(tokenizer, max_length=512): + lengths = [] + + def on_call(): + pass + + det = _detector(tokenizer, max_length=max_length, on_call=on_call) + real = det.model.side_effect + + def record(input_ids=None, attention_mask=None, **kwargs): + lengths.append(int(input_ids.shape[1])) + return real(input_ids=input_ids, attention_mask=attention_mask) + + det.model.side_effect = record + return det, lengths + + +def test_usage_units_for_sources_sum_over_groups(local_wordpiece_tokenizer): + det, lengths = _recording_detector(local_wordpiece_tokenizer, MULTI_MAX_LENGTH) + result = det.detect(_sources(MULTI_CONTEXT, MULTI_ANSWER, MULTI_QUESTION)) + assert len(lengths) > 1 + (usage,) = result.usage + assert (usage.model_id, usage.model_version) == ("stub-encoder", None) + assert usage.units == { + "sources": len(MULTI_CONTEXT), + "source_chars": sum(len(t) for t in MULTI_CONTEXT), + "answer_chars": len(MULTI_ANSWER), + "input_tokens": sum(lengths), + } + + +def test_usage_units_for_prompt_have_no_sources(local_wordpiece_tokenizer): + det, lengths = _recording_detector(local_wordpiece_tokenizer) + result = det.detect(PromptInput(prompt=PROMPTS[0], answer=ANSWERS[0])) + assert result.usage[0].units == { + "source_chars": len(PROMPTS[0]), + "answer_chars": len(ANSWERS[0]), + "input_tokens": lengths[0], + } + + +def test_usage_input_tokens_count_the_truncated_input(local_wordpiece_tokenizer): + det, lengths = _recording_detector(local_wordpiece_tokenizer, max_length=40) + prompt = " ".join(["the capital of france is paris ."] * 30) + result = det.detect(PromptInput(prompt=prompt, answer="paris is the capital of france")) + assert lengths == [40] + assert result.usage[0].units["input_tokens"] == 40 + + # -- concurrency -------------------------------------------------------------------------- From afb876fe9252b184a27a147ff2fef135917cb5da Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 13:15:24 +0100 Subject: [PATCH 25/60] feat: add EncoderDetector.from_pretrained with model_version (#151) --- lettucedetect/detectors/encoder.py | 109 +++++++++- tests/test_encoder_from_pretrained_pytest.py | 198 +++++++++++++++++++ 2 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 tests/test_encoder_from_pretrained_pytest.py diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py index 54bcc58..7b42ffd 100644 --- a/lettucedetect/detectors/encoder.py +++ b/lettucedetect/detectors/encoder.py @@ -5,14 +5,17 @@ import logging import threading import time +from pathlib import Path from typing import Any import torch +from huggingface_hub import try_to_load_from_cache from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator +from transformers import AutoModelForTokenClassification, AutoTokenizer from lettucedetect.datasets.hallucination_dataset import HallucinationDataset from lettucedetect.detectors.base import BaseDetector -from lettucedetect.detectors.errors import ConfigurationError +from lettucedetect.detectors.errors import ConfigurationError, UpstreamError from lettucedetect.detectors.prompt_utils import LANG_TO_PASSAGE, PromptUtils from lettucedetect.detectors.types import ( DetectedSpan, @@ -28,6 +31,22 @@ __all__ = ["EncoderConfig", "EncoderDetector"] + +def _resolved_commit(model_id: str, loader_kwargs: dict[str, Any]) -> str | None: + """Return the Hugging Face commit that is cached for ``model_id``, or ``None``. + + Reads the snapshot directory name from the local cache, so it needs no network and + names the revision that was just loaded (``revision`` and ``cache_dir`` are honoured). + """ + cached = try_to_load_from_cache( + model_id, + "config.json", + cache_dir=loader_kwargs.get("cache_dir"), + revision=loader_kwargs.get("revision"), + ) + return Path(cached).parent.name if isinstance(cached, str) else None + + # Makes two racing first calls on one detector get the same scoring lock. _LOCK_GUARD = threading.Lock() @@ -152,6 +171,94 @@ def __init__( self.device, ) + @classmethod + def from_pretrained( + cls, + model_id: str, + *, + device: torch.device | str | None = None, + taxonomy_head: str | None = None, + include_taxonomy: bool | list | dict = True, + model_version: str | None = None, + config: EncoderConfig | None = None, + **loader_kwargs: Any, # noqa: ANN401 + ) -> EncoderDetector: + """Load the tokenizer and model for ``model_id`` and build the detector. + + This is the one place where a model name becomes a model. It may download, unless + the caller set ``HF_HUB_OFFLINE`` (this method neither reads nor sets it). + + :param model_id: Hugging Face id or local directory. + :param device: device for the model; CUDA when available, else CPU, when ``None``. + :param taxonomy_head: optional id or path of a label-conditioned typing head. It is + loaded, but spans are not typed until typed spans arrive. + :param include_taxonomy: label set for the typing head. + :param model_version: version reported in ``usage`` for a local path. For a hub id the + resolved commit is used and this is only the fallback. + :param config: options, ``EncoderConfig()`` when ``None``. + :param loader_kwargs: passed to both ``from_pretrained`` loaders. + :raises UpstreamError: (``model_load_failed``) a hub model could not be loaded. + :raises ConfigurationError: (``model_load_failed``) a local model could not be loaded. + """ + categories = subcategories = None + if taxonomy_head is not None: + from lettucedetect.detectors.taxonomy_head import resolve_taxonomy + + categories, subcategories = resolve_taxonomy(include_taxonomy) + is_local = Path(model_id).is_dir() + started = time.perf_counter() + try: + tokenizer = AutoTokenizer.from_pretrained(model_id, **loader_kwargs) + model = AutoModelForTokenClassification.from_pretrained(model_id, **loader_kwargs) + except OSError as exc: + if is_local: + raise ConfigurationError( + "The model could not be loaded from the local path. Check that model_id " + "is a directory with a saved model and tokenizer.", + code="model_load_failed", + param="model_id", + ) from exc + raise UpstreamError( + f"The model {model_id!r} could not be loaded. Check the id, the network or " + "HF_HUB_OFFLINE setting and your access to the repository.", + code="model_load_failed", + service="huggingface", + ) from exc + device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) + model.to(device) + model.eval() + typer = None + if taxonomy_head is not None: + from lettucedetect.detectors.taxonomy_head import TaxonomyTyper + + typer = TaxonomyTyper( + taxonomy_head, + device=device, + categories=categories, + subcategories=subcategories, + ) + version = model_version + if not is_local: + version = _resolved_commit(model_id, loader_kwargs) or model_version + detector = cls( + model, + tokenizer, + typer, + config=config, + model_id=model_id, + model_version=version, + ) + detector.device = device + logger.info( + "model loaded: model_id=%s model_version=%s device=%s load_seconds=%.1f", + model_id, + version, + device, + time.perf_counter() - started, + extra={"event": "model_loaded"}, + ) + return detector + # ------------------------------------------------------------------ # Lock # ------------------------------------------------------------------ diff --git a/tests/test_encoder_from_pretrained_pytest.py b/tests/test_encoder_from_pretrained_pytest.py new file mode 100644 index 0000000..d50d121 --- /dev/null +++ b/tests/test_encoder_from_pretrained_pytest.py @@ -0,0 +1,198 @@ +"""Tests for ``EncoderDetector.from_pretrained``: offline, with fake loaders.""" + +from __future__ import annotations + +import logging +import socket +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors.encoder import EncoderConfig, EncoderDetector +from lettucedetect.detectors.errors import ConfigurationError, UpstreamError +from lettucedetect.detectors.types import PromptInput +from tests.test_encoder_detector_pytest import _stub_model + +REQUEST = PromptInput(prompt="The capital of France is Paris.", answer="It is Lyon.") +SHA_MAIN = "a" * 40 +SHA_V1 = "b" * 40 +SECRET_PROMPT = "ZEBRA-PROMPT-TEXT" # noqa: S105 +SECRET_ANSWER = "ZEBRA-ANSWER-TEXT" # noqa: S105 + + +@pytest.fixture +def loaders(local_wordpiece_tokenizer): + """Fake ``from_pretrained`` loaders; yields the model and both mocks.""" + model = _stub_model() + tok_loader = MagicMock(return_value=local_wordpiece_tokenizer) + model_loader = MagicMock(return_value=model) + with ( + patch("transformers.AutoTokenizer.from_pretrained", tok_loader), + patch("transformers.AutoModelForTokenClassification.from_pretrained", model_loader), + ): + yield model, tok_loader, model_loader + + +@pytest.fixture +def offline_cache(tmp_path, monkeypatch): + """Build a Hugging Face cache with ``org/name`` at two revisions, with the network blocked.""" + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + + def no_network(*args: object, **kwargs: object) -> None: + raise AssertionError("network used") + + monkeypatch.setattr(socket.socket, "connect", no_network) + repo = tmp_path / "hub" / "models--org--name" + for sha in (SHA_MAIN, SHA_V1): + (repo / "snapshots" / sha).mkdir(parents=True) + (repo / "snapshots" / sha / "config.json").write_text("{}") + (repo / "refs").mkdir() + (repo / "refs" / "main").write_text(SHA_MAIN) + (repo / "refs" / "v1").write_text(SHA_V1) + return tmp_path / "hub" + + +def test_builds_a_working_detector_and_passes_device_through(loaders, local_wordpiece_tokenizer): + model, tok_loader, model_loader = loaders + detector = EncoderDetector.from_pretrained( + "org/name", + device="cpu", + config=EncoderConfig(max_length=256), + local_files_only=True, + ) + tok_loader.assert_called_once_with("org/name", local_files_only=True) + model_loader.assert_called_once_with("org/name", local_files_only=True) + model.to.assert_called_once_with(torch.device("cpu")) + model.eval.assert_called_once_with() + assert detector.device == torch.device("cpu") + assert detector.max_length == 256 + assert detector.model_id == "org/name" + expected = EncoderDetector( + _stub_model(), local_wordpiece_tokenizer, config=EncoderConfig(max_length=256) + ).detect(REQUEST) + assert detector.detect(REQUEST).spans == expected.spans + + +def test_hub_id_reports_the_resolved_commit(loaders, offline_cache): + detector = EncoderDetector.from_pretrained("org/name", cache_dir=str(offline_cache)) + assert detector.model_version == SHA_MAIN + assert detector.detect(REQUEST).usage[0].model_version == SHA_MAIN + + +def test_hub_id_follows_the_requested_revision(loaders, offline_cache): + detector = EncoderDetector.from_pretrained( + "org/name", revision="v1", cache_dir=str(offline_cache) + ) + assert detector.model_version == SHA_V1 + + +def test_resolved_commit_wins_over_the_callers_version(loaders, offline_cache): + detector = EncoderDetector.from_pretrained( + "org/name", model_version="mine", cache_dir=str(offline_cache) + ) + assert detector.model_version == SHA_MAIN + + +def test_callers_version_is_the_fallback_when_nothing_is_cached(loaders, offline_cache): + kwargs = {"cache_dir": str(offline_cache)} + assert EncoderDetector.from_pretrained("other/model", **kwargs).model_version is None + assert ( + EncoderDetector.from_pretrained("other/model", model_version="v7", **kwargs).model_version + == "v7" + ) + + +def test_local_path_uses_the_callers_version_and_no_cache_lookup(loaders, tmp_path): + boom = MagicMock(side_effect=AssertionError("cache consulted")) + with patch("lettucedetect.detectors.encoder.try_to_load_from_cache", boom): + assert EncoderDetector.from_pretrained(str(tmp_path)).model_version is None + detector = EncoderDetector.from_pretrained(str(tmp_path), model_version="2024-05") + assert detector.model_version == "2024-05" + boom.assert_not_called() + + +def test_model_loaded_is_logged_exactly_once_at_info(loaders, offline_cache, caplog): + caplog.set_level(logging.DEBUG) + detector = EncoderDetector.from_pretrained( + "org/name", device="cpu", cache_dir=str(offline_cache) + ) + detector.detect(PromptInput(prompt=SECRET_PROMPT, answer=SECRET_ANSWER)) + loud = [r for r in caplog.records if r.levelno >= logging.INFO] + assert len(loud) == 1 + record = loud[0] + assert (record.levelno, record.name, record.event) == ( + logging.INFO, + "lettucedetect.detectors.encoder", + "model_loaded", + ) + assert record.args[:3] == ("org/name", SHA_MAIN, torch.device("cpu")) + assert SECRET_PROMPT not in caplog.text + assert SECRET_ANSWER not in caplog.text + + +def test_building_from_objects_logs_nothing_at_info(local_wordpiece_tokenizer, caplog): + caplog.set_level(logging.DEBUG) + EncoderDetector(_stub_model(), local_wordpiece_tokenizer) + assert [r for r in caplog.records if r.levelno >= logging.INFO] == [] + + +def test_taxonomy_head_loads_the_typer_with_the_device(loaders): + typer_class = MagicMock() + with patch("lettucedetect.detectors.taxonomy_head.TaxonomyTyper", typer_class): + detector = EncoderDetector.from_pretrained( + "org/name", + device="cpu", + taxonomy_head="org/head", + include_taxonomy={"Fabricated": "Made up facts"}, + ) + typer_class.assert_called_once_with( + "org/head", + device=torch.device("cpu"), + categories={"Fabricated": "Made up facts"}, + subcategories=None, + ) + assert detector.typer is typer_class.return_value + + +def test_no_taxonomy_head_means_no_typer(loaders): + typer_class = MagicMock() + with patch("lettucedetect.detectors.taxonomy_head.TaxonomyTyper", typer_class): + assert EncoderDetector.from_pretrained("org/name").typer is None + typer_class.assert_not_called() + + +def test_bad_taxonomy_spec_fails_before_any_download(loaders): + _, tok_loader, model_loader = loaders + with pytest.raises(TypeError): + EncoderDetector.from_pretrained("org/name", taxonomy_head="org/head", include_taxonomy=5) + tok_loader.assert_not_called() + model_loader.assert_not_called() + + +def test_uncached_hub_model_offline_raises_upstream_error(offline_cache, monkeypatch): + """With ``HF_HUB_OFFLINE=1`` and nothing cached the loader error is translated.""" + with pytest.raises(UpstreamError) as exc: + EncoderDetector.from_pretrained("nope/not-cached", cache_dir=str(offline_cache)) + assert (exc.value.code, exc.value.service) == ("model_load_failed", "huggingface") + assert isinstance(exc.value.__cause__, OSError) + + +def test_loader_failure_for_a_hub_id_is_an_upstream_error(loaders): + _, tok_loader, _ = loaders + tok_loader.side_effect = OSError("secret detail") + with pytest.raises(UpstreamError) as exc: + EncoderDetector.from_pretrained("org/name") + assert exc.value.code == "model_load_failed" + assert "secret detail" not in str(exc.value) + assert isinstance(exc.value.__cause__, OSError) + + +def test_loader_failure_for_a_local_path_is_a_configuration_error(loaders, tmp_path): + _, _, model_loader = loaders + model_loader.side_effect = OSError("secret detail") + with pytest.raises(ConfigurationError) as exc: + EncoderDetector.from_pretrained(str(tmp_path)) + assert (exc.value.code, exc.value.param) == ("model_load_failed", "model_id") + assert "secret detail" not in str(exc.value) + assert isinstance(exc.value.__cause__, OSError) From be63d293010594792ea19cd6dc941ef92e01cd63 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 13:41:28 +0100 Subject: [PATCH 26/60] feat: make TransformerDetector a deprecated subclass of EncoderDetector (#152) --- lettucedetect/detectors/encoder.py | 83 ++++-- lettucedetect/detectors/transformer.py | 97 +++++--- tests/test_golden_factory_cache_pytest.py | 3 + tests/test_golden_transformer_pytest.py | 4 + tests/test_transformer_deprecated_pytest.py | 263 ++++++++++++++++++++ 5 files changed, 382 insertions(+), 68 deletions(-) create mode 100644 tests/test_transformer_deprecated_pytest.py diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py index 7b42ffd..d227ffd 100644 --- a/lettucedetect/detectors/encoder.py +++ b/lettucedetect/detectors/encoder.py @@ -51,6 +51,55 @@ def _resolved_commit(model_id: str, loader_kwargs: dict[str, Any]) -> str | None _LOCK_GUARD = threading.Lock() +def _resolve_taxonomy( + taxonomy_head: str | None, include_taxonomy: bool | list | dict +) -> tuple[dict | None, dict | None]: + """Resolve the label set of the typing head; ``(None, None)`` without a head.""" + if taxonomy_head is None: + return None, None + from lettucedetect.detectors.taxonomy_head import resolve_taxonomy + + return resolve_taxonomy(include_taxonomy) + + +def _finish_load( + model: Any, # noqa: ANN401 + device: torch.device | str | None, + taxonomy_head: str | None, + categories: dict | None, + subcategories: dict | None, +) -> tuple[torch.device, Any]: + """Move the model to the device, set eval mode and load the typer, if any. + + Shared by ``EncoderDetector.from_pretrained`` and the deprecated ``TransformerDetector``. + """ + device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) + model.to(device) + model.eval() + typer = None + if taxonomy_head is not None: + from lettucedetect.detectors.taxonomy_head import TaxonomyTyper + + typer = TaxonomyTyper( + taxonomy_head, device=device, categories=categories, subcategories=subcategories + ) + return device, typer + + +def _log_model_loaded( + model_id: str, version: str | None, device: torch.device, started: float +) -> None: + """Log the ``model_loaded`` event: ids and timing only, never customer text.""" + logger.info( + "model loaded: model_id=%s model_version=%s device=%s load_seconds=%.1f", + model_id, + version, + device, + time.perf_counter() - started, + extra={"event": "model_loaded"}, + ) + + class EncoderConfig(BaseModel): """Options of an :class:`EncoderDetector`. @@ -200,11 +249,7 @@ def from_pretrained( :raises UpstreamError: (``model_load_failed``) a hub model could not be loaded. :raises ConfigurationError: (``model_load_failed``) a local model could not be loaded. """ - categories = subcategories = None - if taxonomy_head is not None: - from lettucedetect.detectors.taxonomy_head import resolve_taxonomy - - categories, subcategories = resolve_taxonomy(include_taxonomy) + categories, subcategories = _resolve_taxonomy(taxonomy_head, include_taxonomy) is_local = Path(model_id).is_dir() started = time.perf_counter() try: @@ -224,23 +269,14 @@ def from_pretrained( code="model_load_failed", service="huggingface", ) from exc - device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) - model.to(device) - model.eval() - typer = None - if taxonomy_head is not None: - from lettucedetect.detectors.taxonomy_head import TaxonomyTyper - - typer = TaxonomyTyper( - taxonomy_head, - device=device, - categories=categories, - subcategories=subcategories, - ) + device, typer = _finish_load(model, device, taxonomy_head, categories, subcategories) version = model_version if not is_local: version = _resolved_commit(model_id, loader_kwargs) or model_version - detector = cls( + # ``__new__`` plus the base ``__init__``: a subclass with its own ``__init__`` still works. + detector = cls.__new__(cls) + EncoderDetector.__init__( + detector, model, tokenizer, typer, @@ -249,14 +285,7 @@ def from_pretrained( model_version=version, ) detector.device = device - logger.info( - "model loaded: model_id=%s model_version=%s device=%s load_seconds=%.1f", - model_id, - version, - device, - time.perf_counter() - started, - extra={"event": "model_loaded"}, - ) + _log_model_loaded(model_id, version, device, started) return detector # ------------------------------------------------------------------ diff --git a/lettucedetect/detectors/transformer.py b/lettucedetect/detectors/transformer.py index 95f822f..5c0bad0 100644 --- a/lettucedetect/detectors/transformer.py +++ b/lettucedetect/detectors/transformer.py @@ -3,11 +3,21 @@ from __future__ import annotations import logging +import time +from pathlib import Path import torch from transformers import AutoModelForTokenClassification, AutoTokenizer -from lettucedetect.detectors.encoder import EncoderDetector +from lettucedetect.detectors._deprecation import deprecated +from lettucedetect.detectors.encoder import ( + EncoderConfig, + EncoderDetector, + _finish_load, + _log_model_loaded, + _resolve_taxonomy, + _resolved_commit, +) from lettucedetect.detectors.prompt_utils import LANG_TO_PASSAGE, Lang, PromptUtils logger = logging.getLogger(__name__) @@ -15,9 +25,14 @@ __all__ = ["TransformerDetector"] +@deprecated("EncoderDetector.from_pretrained") class TransformerDetector(EncoderDetector): """Detect hallucinations with a fine-tuned token classifier. + .. deprecated:: 0.3.0 + Use :meth:`EncoderDetector.from_pretrained`. ``TransformerDetector`` will be removed + in 0.5.0. It is an :class:`EncoderDetector`, so ``detect`` and ``adetect`` work too. + When the combined context + answer exceeds ``max_length`` tokens, the context is automatically split into chunks. Each chunk is scored independently and the per-token hallucination probability is aggregated @@ -56,25 +71,22 @@ def __init__( raise ValueError(f"Invalid language. Choose from {', '.join(LANG_TO_PASSAGE)}") if batch_size < 1: raise ValueError("batch_size must be >= 1") - self.lang, self.max_length = lang, max_length - self.batch_size = batch_size - self.tokenizer = AutoTokenizer.from_pretrained(model_path, **tok_kwargs) - self.model = AutoModelForTokenClassification.from_pretrained(model_path, **tok_kwargs) - self.device = device or ( - torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + started = time.perf_counter() + categories, subcategories = _resolve_taxonomy(taxonomy_head, include_taxonomy) + tokenizer = AutoTokenizer.from_pretrained(model_path, **tok_kwargs) + model = AutoModelForTokenClassification.from_pretrained(model_path, **tok_kwargs) + device, typer = _finish_load(model, device, taxonomy_head, categories, subcategories) + version = None if Path(model_path).is_dir() else _resolved_commit(model_path, tok_kwargs) + super().__init__( + model, + tokenizer, + typer, + config=EncoderConfig(max_length=max_length, batch_size=batch_size, lang=lang), + model_id=model_path, + model_version=version, ) - self.model.to(self.device).eval() - self.typer = None - if taxonomy_head is not None: - from lettucedetect.detectors.taxonomy_head import TaxonomyTyper, resolve_taxonomy - - categories, subcategories = resolve_taxonomy(include_taxonomy) - self.typer = TaxonomyTyper( - taxonomy_head, - device=self.device, - categories=categories, - subcategories=subcategories, - ) + self.device = device + _log_model_loaded(model_path, version, device, started) # ------------------------------------------------------------------ # Public API @@ -105,16 +117,18 @@ def predict( ) self._validate_min_confidence(min_confidence) - groups = self._group_passages_into_chunks(context, question, answer) + # The tokenizer and model are shared state, so scoring takes the same lock as detect(). + with self._get_scoring_lock(): + groups = self._group_passages_into_chunks(context, question, answer) - if len(groups) == 1: - prompt = PromptUtils.format_context(groups[0], question, self.lang) - result = self._predict_single(prompt, answer, output_format) - else: - chunk_prompts = [ - PromptUtils.format_context(group, question, self.lang) for group in groups - ] - result = self._predict_chunked(chunk_prompts, answer, output_format) + if len(groups) == 1: + prompt = PromptUtils.format_context(groups[0], question, self.lang) + result = self._predict_single(prompt, answer, output_format) + else: + chunk_prompts = [ + PromptUtils.format_context(group, question, self.lang) for group in groups + ] + result = self._predict_chunked(chunk_prompts, answer, output_format) if output_format == "spans" and self.typer is not None: result = self.typer.type_spans(answer, "\n".join(context), result) @@ -142,19 +156,20 @@ def predict_prompt( "Use 'tokens' or 'spans'" ) self._validate_min_confidence(min_confidence) - # Warn if the input will be truncated. - total_tokens = self.tokenizer(prompt, answer, add_special_tokens=True, return_tensors="pt")[ - "input_ids" - ].shape[1] - if total_tokens > self.max_length: - logger.warning( - "predict_prompt: input (%d tokens) exceeds max_length (%d). " - "The prompt will be truncated. Use predict() with structured " - "passages for automatic chunking.", - total_tokens, - self.max_length, - ) - spans = self._predict_single(prompt, answer, output_format) + with self._get_scoring_lock(): + # Warn if the input will be truncated. + total_tokens = self.tokenizer( + prompt, answer, add_special_tokens=True, return_tensors="pt" + )["input_ids"].shape[1] + if total_tokens > self.max_length: + logger.warning( + "predict_prompt: input (%d tokens) exceeds max_length (%d). " + "The prompt will be truncated. Use predict() with structured " + "passages for automatic chunking.", + total_tokens, + self.max_length, + ) + spans = self._predict_single(prompt, answer, output_format) if output_format == "spans" and self.typer is not None: spans = self.typer.type_spans(answer, prompt, spans) return self._filter_spans_by_confidence(spans, output_format, min_confidence) diff --git a/tests/test_golden_factory_cache_pytest.py b/tests/test_golden_factory_cache_pytest.py index 6741b93..834a079 100644 --- a/tests/test_golden_factory_cache_pytest.py +++ b/tests/test_golden_factory_cache_pytest.py @@ -123,6 +123,9 @@ def _facade_outputs(detector) -> dict: return out +@pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) class TestFacade: """``HallucinationDetector`` returns exactly what the detector alone returns.""" diff --git a/tests/test_golden_transformer_pytest.py b/tests/test_golden_transformer_pytest.py index 071cde0..1cf38c6 100644 --- a/tests/test_golden_transformer_pytest.py +++ b/tests/test_golden_transformer_pytest.py @@ -18,6 +18,10 @@ from lettucedetect.detectors.transformer import TransformerDetector from tests.golden import assert_golden +pytestmark = pytest.mark.filterwarnings( + "ignore::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning" +) + FORMATS = ["tokens", "spans"] MULTI_MAX_LENGTH = 90 diff --git a/tests/test_transformer_deprecated_pytest.py b/tests/test_transformer_deprecated_pytest.py new file mode 100644 index 0000000..6cf97d1 --- /dev/null +++ b/tests/test_transformer_deprecated_pytest.py @@ -0,0 +1,263 @@ +"""``TransformerDetector`` is a deprecated subclass of ``EncoderDetector``: offline, stub model.""" + +from __future__ import annotations + +import asyncio +import logging +import threading +import time +import warnings +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors import _deprecation as dep +from lettucedetect.detectors._deprecation import LettuceDetectDeprecationWarning +from lettucedetect.detectors.encoder import EncoderConfig, EncoderDetector +from lettucedetect.detectors.factory import make_detector +from lettucedetect.detectors.transformer import TransformerDetector +from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput +from lettucedetect.models.inference import HallucinationDetector +from tests.golden import assert_golden +from tests.test_golden_transformer_pytest import ( + ANSWERS, + PREDICT_INPUTS, + PROMPTS, + _stub_forward, +) + +WARNING = LettuceDetectDeprecationWarning + + +def _construct(tokenizer, model=None, **kwargs) -> TransformerDetector: + """Build a TransformerDetector from a test module: this warns.""" + model = model or MagicMock(side_effect=_stub_forward) + with ( + patch("transformers.AutoTokenizer.from_pretrained", return_value=tokenizer), + patch("transformers.AutoModelForTokenClassification.from_pretrained", return_value=model), + pytest.warns(WARNING), + ): + return TransformerDetector(model_path="dummy_path", **kwargs) + + +def _encoder(tokenizer, max_length=512) -> EncoderDetector: + return EncoderDetector( + MagicMock(side_effect=_stub_forward), + tokenizer, + config=EncoderConfig(max_length=max_length), + model_id="dummy_path", + ) + + +def _sources(context, answer, question=None) -> SourcesInput: + return SourcesInput( + sources=[Chunk(id=str(i), text=t) for i, t in enumerate(context)], + answer=answer, + question=question, + ) + + +def _bare(tokenizer, model=None) -> TransformerDetector: + """Make a detector with ``__new__`` and only the six attributes set by hand.""" + with pytest.warns(WARNING): + det = TransformerDetector.__new__(TransformerDetector) + det.model = model or MagicMock(side_effect=_stub_forward) + det.tokenizer = tokenizer + det.device = torch.device("cpu") + det.max_length, det.lang, det.typer = 512, "en", None + return det + + +# -- deprecation -------------------------------------------------------------------------- + + +def test_construction_warns_and_names_the_replacement(local_wordpiece_tokenizer): + with ( + patch("transformers.AutoTokenizer.from_pretrained", return_value=local_wordpiece_tokenizer), + patch( + "transformers.AutoModelForTokenClassification.from_pretrained", + return_value=MagicMock(side_effect=_stub_forward), + ), + pytest.warns(WARNING) as caught, + ): + TransformerDetector(model_path="dummy_path") + assert [str(w.message) for w in caught] == [ + f"TransformerDetector is deprecated since {dep.DEPRECATED_SINCE} and will be removed in " + f"{dep.REMOVED_IN}. Use EncoderDetector.from_pretrained." + ] + + +def test_construction_inside_the_package_is_silent(local_wordpiece_tokenizer): + namespace = {"__name__": "lettucedetect.fake_internal", "T": TransformerDetector} + with ( + patch("transformers.AutoTokenizer.from_pretrained", return_value=local_wordpiece_tokenizer), + patch( + "transformers.AutoModelForTokenClassification.from_pretrained", + return_value=MagicMock(side_effect=_stub_forward), + ), + warnings.catch_warnings(), + ): + warnings.simplefilter("error") + exec("T(model_path='dummy_path')", namespace) # noqa: S102 + make_detector("transformer", model_path="dummy_path") + HallucinationDetector(method="transformer", model_path="dummy_path") + + +def test_is_an_encoder_detector_with_the_old_attributes(local_wordpiece_tokenizer): + det = _construct(local_wordpiece_tokenizer, max_length=300, batch_size=4, device="meta") + assert isinstance(det, EncoderDetector) + assert det.model_id == "dummy_path" + assert det.tokenizer is local_wordpiece_tokenizer + assert (det.max_length, det.lang, det.batch_size, det.typer) == (300, "en", 4, None) + assert det.device == torch.device("meta") # the requested device, not the stub model's + assert TransformerDetector.__deprecated__.endswith("EncoderDetector.from_pretrained.") # ty: ignore[unresolved-attribute] + assert ".. deprecated::" in TransformerDetector.__doc__ + for name in ( + "_predict_single", + "_predict_batch", + "_predict_chunked", + "_build_spans_from_tokens", + ): + assert callable(getattr(det, name)) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [({"lang": "xx"}, "Invalid language"), ({"batch_size": 0}, "batch_size must be >= 1")], +) +def test_bad_options_still_raise_value_error(kwargs, message): + with pytest.warns(WARNING), pytest.raises(ValueError, match=message): + TransformerDetector(model_path="dummy_path", **kwargs) + + +def test_loader_os_error_is_not_translated(): + """Old callers see the raw loader error.""" + boom = MagicMock(side_effect=OSError("gone")) + with ( + patch("transformers.AutoTokenizer.from_pretrained", boom), + pytest.warns(WARNING), + pytest.raises(OSError, match="gone"), + ): + TransformerDetector(model_path="dummy_path") + + +def test_construction_logs_model_loaded_once(local_wordpiece_tokenizer, caplog): + caplog.set_level(logging.DEBUG) + det = _construct(local_wordpiece_tokenizer) + det.predict(*PREDICT_INPUTS[0][:1], PREDICT_INPUTS[0][1]) + loud = [r for r in caplog.records if r.levelno >= logging.INFO] + assert [r.event for r in loud] == ["model_loaded"] + assert loud[0].args[0] == "dummy_path" + + +# -- detect and adetect ------------------------------------------------------------------- + + +def test_detect_and_adetect_equal_an_encoder_detector_without_warning(local_wordpiece_tokenizer): + old = _construct(local_wordpiece_tokenizer) + new = _encoder(local_wordpiece_tokenizer) + requests = [_sources(*inp) for inp in PREDICT_INPUTS] + [ + PromptInput(prompt=p, answer=a) for p, a in zip(PROMPTS, ANSWERS) + ] + with warnings.catch_warnings(): + warnings.simplefilter("error") + for request in requests: + assert old.detect(request, include_tokens=True) == new.detect( + request, include_tokens=True + ) + assert asyncio.run(old.adetect(request)) == new.detect(request) + + +# -- predict output and __new__ ----------------------------------------------------------- + + +def test_predict_and_predict_prompt_equal_the_golden_files(local_wordpiece_tokenizer): + det = _construct(local_wordpiece_tokenizer) + for fmt in ("tokens", "spans"): + assert_golden( + f"transformer_predict_{fmt}", + [det.predict(c, a, q, output_format=fmt) for c, a, q in PREDICT_INPUTS], + ) + assert_golden( + f"transformer_predict_prompt_{fmt}", + [det.predict_prompt(p, a, output_format=fmt) for p, a in zip(PROMPTS, ANSWERS)], + ) + + +def test_new_with_six_attributes_answers_predict_and_detect(local_wordpiece_tokenizer): + det = _bare(local_wordpiece_tokenizer) + assert_golden( + "transformer_predict_spans", + [det.predict(c, a, q, output_format="spans") for c, a, q in PREDICT_INPUTS], + ) + assert det.detect(_sources(*PREDICT_INPUTS[0])).spans is not None + + +def test_new_answers_concurrent_predict_with_one_lock(local_wordpiece_tokenizer): + state = {"active": 0, "max": 0} + guard = threading.Lock() + + def forward(input_ids=None, attention_mask=None, **kwargs): + with guard: + state["active"] += 1 + state["max"] = max(state["max"], state["active"]) + time.sleep(0.005) + with guard: + state["active"] -= 1 + return _stub_forward(input_ids=input_ids, attention_mask=attention_mask) + + det = _bare(local_wordpiece_tokenizer, MagicMock(side_effect=forward)) + inputs = [PREDICT_INPUTS[i % len(PREDICT_INPUTS)] for i in range(16)] + expected = [det.predict(c, a, q, output_format="spans") for c, a, q in inputs] + prompt_expected = [ + det.predict_prompt(p, a, output_format="spans") for p, a in zip(PROMPTS, ANSWERS) + ] + state["max"] = 0 + det.__dict__.pop("_scoring_lock", None) # race the first creation again + + created, real = [], threading.RLock + + def slow_rlock(): + time.sleep(0.05) + created.append(real()) + return created[-1] + + barrier = threading.Barrier(16) + results: dict[int, list] = {} + + def work(i): + barrier.wait() + c, a, q = inputs[i] + results[i] = det.predict(c, a, q, output_format="spans") + + with patch("lettucedetect.detectors.encoder.threading.RLock", slow_rlock): + threads = [threading.Thread(target=work, args=(i,)) for i in range(16)] + for t in threads: + t.start() + for t in threads: + t.join() + assert len(created) == 1 + assert [results[i] for i in range(16)] == expected + assert state["max"] == 1 + assert [ + det.predict_prompt(p, a, output_format="spans") for p, a in zip(PROMPTS, ANSWERS) + ] == prompt_expected + + +# -- from_pretrained on the subclass ------------------------------------------------------ + + +def test_inherited_from_pretrained_builds_a_transformer_detector(local_wordpiece_tokenizer): + with ( + patch("transformers.AutoTokenizer.from_pretrained", return_value=local_wordpiece_tokenizer), + patch( + "transformers.AutoModelForTokenClassification.from_pretrained", + return_value=MagicMock(side_effect=_stub_forward), + ), + warnings.catch_warnings(), + ): + warnings.simplefilter("error") # the instance is made inside the package: silent + det = TransformerDetector.from_pretrained("dummy_path", device="cpu") + assert type(det) is TransformerDetector + assert det.model_id == "dummy_path" From 8d198e591154a9dfbd4af5f992bf8a168ca3b57c Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 14:27:52 +0100 Subject: [PATCH 27/60] feat: make TaxonomyTyper take loaded objects and add from_pretrained (#154) --- lettucedetect/detectors/encoder.py | 74 +++- lettucedetect/detectors/taxonomy_head.py | 166 +++++++-- lettucedetect/detectors/transformer.py | 4 +- tests/test_custom_taxonomy_pytest.py | 2 +- tests/test_encoder_from_pretrained_pytest.py | 4 +- tests/test_taxonomy_typer_pytest.py | 369 +++++++++++++++++++ 6 files changed, 563 insertions(+), 56 deletions(-) create mode 100644 tests/test_taxonomy_typer_pytest.py diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py index d227ffd..ee4928d 100644 --- a/lettucedetect/detectors/encoder.py +++ b/lettucedetect/detectors/encoder.py @@ -62,16 +62,51 @@ def _resolve_taxonomy( return resolve_taxonomy(include_taxonomy) +def _model_load_error(model_id: str, is_local: bool) -> ConfigurationError | UpstreamError: + """Build the error for a model that could not be loaded; the caller chains the cause. + + A local path is the caller's configuration, a hub id is an upstream failure. The message + never carries the loader's own text, which may hold paths or tokens. + """ + if is_local: + return ConfigurationError( + "The model could not be loaded from the local path. Check that model_id " + "is a directory with a saved model and tokenizer.", + code="model_load_failed", + param="model_id", + ) + return UpstreamError( + f"The model {model_id!r} could not be loaded. Check the id, the network or " + "HF_HUB_OFFLINE setting and your access to the repository.", + code="model_load_failed", + service="huggingface", + ) + + +# Loader options that say where and how to reach the Hugging Face cache. They describe the +# environment, not one repository, so the typing head is loaded with the same ones. ``revision`` +# is left out on purpose: it names a revision of the encoder's repository, not of the head's. +_HEAD_LOADER_KWARGS = ("cache_dir", "local_files_only", "token") + + +def _head_loader_kwargs(loader_kwargs: dict[str, Any]) -> dict[str, Any]: + """Pick the loader options the typing head shares with the encoder.""" + return {key: loader_kwargs[key] for key in _HEAD_LOADER_KWARGS if key in loader_kwargs} + + def _finish_load( model: Any, # noqa: ANN401 device: torch.device | str | None, taxonomy_head: str | None, categories: dict | None, subcategories: dict | None, + loader_kwargs: dict[str, Any] | None = None, ) -> tuple[torch.device, Any]: """Move the model to the device, set eval mode and load the typer, if any. Shared by ``EncoderDetector.from_pretrained`` and the deprecated ``TransformerDetector``. + ``loader_kwargs`` are the caller's loader options; only the cache location and access + options reach the typing head. """ device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) model.to(device) @@ -80,17 +115,28 @@ def _finish_load( if taxonomy_head is not None: from lettucedetect.detectors.taxonomy_head import TaxonomyTyper - typer = TaxonomyTyper( - taxonomy_head, device=device, categories=categories, subcategories=subcategories + typer = TaxonomyTyper.from_pretrained( + taxonomy_head, + device=device, + categories=categories, + subcategories=subcategories, + **_head_loader_kwargs(loader_kwargs or {}), ) return device, typer def _log_model_loaded( - model_id: str, version: str | None, device: torch.device, started: float + model_id: str, + version: str | None, + device: torch.device, + started: float, + module_logger: logging.Logger | None = None, ) -> None: - """Log the ``model_loaded`` event: ids and timing only, never customer text.""" - logger.info( + """Log the ``model_loaded`` event: ids and timing only, never customer text. + + :param module_logger: the calling module's logger, this module's logger when ``None``. + """ + (module_logger or logger).info( "model loaded: model_id=%s model_version=%s device=%s load_seconds=%.1f", model_id, version, @@ -256,20 +302,10 @@ def from_pretrained( tokenizer = AutoTokenizer.from_pretrained(model_id, **loader_kwargs) model = AutoModelForTokenClassification.from_pretrained(model_id, **loader_kwargs) except OSError as exc: - if is_local: - raise ConfigurationError( - "The model could not be loaded from the local path. Check that model_id " - "is a directory with a saved model and tokenizer.", - code="model_load_failed", - param="model_id", - ) from exc - raise UpstreamError( - f"The model {model_id!r} could not be loaded. Check the id, the network or " - "HF_HUB_OFFLINE setting and your access to the repository.", - code="model_load_failed", - service="huggingface", - ) from exc - device, typer = _finish_load(model, device, taxonomy_head, categories, subcategories) + raise _model_load_error(model_id, is_local) from exc + device, typer = _finish_load( + model, device, taxonomy_head, categories, subcategories, loader_kwargs + ) version = model_version if not is_local: version = _resolved_commit(model_id, loader_kwargs) or model_version diff --git a/lettucedetect/detectors/taxonomy_head.py b/lettucedetect/detectors/taxonomy_head.py index 7bc7484..9f9c062 100644 --- a/lettucedetect/detectors/taxonomy_head.py +++ b/lettucedetect/detectors/taxonomy_head.py @@ -10,11 +10,25 @@ from __future__ import annotations +import logging +import threading +import time +from pathlib import Path +from typing import Any + import torch from transformers import AutoModel, AutoTokenizer +from lettucedetect.detectors.encoder import ( + _LOCK_GUARD, + _log_model_loaded, + _model_load_error, + _resolved_commit, +) from lettucedetect.prompts.generative import CATEGORY_DESCRIPTIONS, SUBCATEGORY_DESCRIPTIONS +logger = logging.getLogger(__name__) + _SEP = " [CTX] " # answer + _SEP + context; must match the taxonomy-head training script @@ -44,40 +58,113 @@ def resolve_taxonomy( class TaxonomyTyper: - """Types spans (category + subcategory) via a label-conditioned encoder.""" + """Types spans (category + subcategory) via a label-conditioned encoder. + + Built from an encoder and tokenizer the caller already holds, so construction downloads + nothing. :meth:`from_pretrained` is where a model name becomes a model. + + Typing runs under one private lock, so concurrent calls on one typer (for example from + ``adetect`` worker threads, or from several detectors sharing it) run one at a time. + + :param encoder: the label-conditioned encoder, ready for inference (it is not moved or + switched to eval mode). + :param tokenizer: the encoder's fast tokenizer. + :param categories: custom ``{name: description}`` category labels; REPLACES the frozen + set (labels enter only as text, so held-out labels type zero-shot from their + description). ``None`` keeps the trained taxonomy. + :param subcategories: custom subcategory labels, same semantics. + :param max_length: max tokens for the ``answer + context`` input. + :param model_id: id reported in ``usage``. + :param model_version: version reported in ``usage``. + """ + + model_id: str | None = None + model_version: str | None = None def __init__( self, - model_path: str, - device: torch.device | str | None = None, - max_length: int = 1024, + encoder: Any, # noqa: ANN401 + tokenizer: Any, # noqa: ANN401 + *, categories: dict[str, str] | None = None, subcategories: dict[str, str] | None = None, - **tok_kwargs: object, + max_length: int = 1024, + model_id: str | None = None, + model_version: str | None = None, ) -> None: - """Load the typing encoder and pre-compute taxonomy-label embeddings. - - :param model_path: Path or HF id of the label-conditioned encoder. - :param device: Device for inference (defaults to CUDA when available). - :param max_length: Max tokens for the ``answer + context`` input. - :param categories: Custom ``{name: description}`` category labels; REPLACES the - frozen set (labels enter only as text, so held-out labels type zero-shot from - their description). ``None`` keeps the trained taxonomy. - :param subcategories: Custom subcategory labels, same semantics. - :param tok_kwargs: Extra arguments for the tokenizer / model loaders. - """ - self.device = device or ( - torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") - ) + """Build the typer from loaded objects and pre-compute taxonomy-label embeddings.""" + device = getattr(encoder, "device", None) + self.device = device if isinstance(device, torch.device) else torch.device("cpu") self.max_length = max_length - self.tokenizer = AutoTokenizer.from_pretrained(model_path, **tok_kwargs) - self.encoder = AutoModel.from_pretrained(model_path, **tok_kwargs).to(self.device).eval() + self.tokenizer = tokenizer + self.encoder = encoder + self.model_id = model_id + self.model_version = model_version cats = categories if categories is not None else CATEGORY_DESCRIPTIONS subs = subcategories if subcategories is not None else SUBCATEGORY_DESCRIPTIONS self.cat_names = list(cats) self.sub_names = list(subs) self._cat_vecs = self._label_vecs(self.cat_names, cats) self._sub_vecs = self._label_vecs(self.sub_names, subs) + logger.debug( + "taxonomy typer built: model_id=%s categories=%d subcategories=%d max_length=%d " + "device=%s", + model_id, + len(self.cat_names), + len(self.sub_names), + max_length, + self.device, + ) + + @classmethod + def from_pretrained( + cls, + model_id: str, + *, + device: torch.device | str | None = None, + categories: dict[str, str] | None = None, + subcategories: dict[str, str] | None = None, + model_version: str | None = None, + **loader_kwargs: Any, # noqa: ANN401 + ) -> TaxonomyTyper: + """Load the encoder and tokenizer for ``model_id`` and build the typer. + + Like :meth:`EncoderDetector.from_pretrained`, this may download, unless the caller set + ``HF_HUB_OFFLINE`` (this method neither reads nor sets it). + + :param model_id: Hugging Face id or local directory of the label-conditioned encoder. + :param device: device for the encoder; CUDA when available, else CPU, when ``None``. + :param categories: custom category labels, see the class docstring. + :param subcategories: custom subcategory labels. + :param model_version: version reported in ``usage`` for a local path. For a hub id the + resolved commit is used and this is only the fallback. + :param loader_kwargs: passed to both ``from_pretrained`` loaders. + :raises UpstreamError: (``model_load_failed``) a hub model could not be loaded. + :raises ConfigurationError: (``model_load_failed``) a local model could not be loaded. + """ + is_local = Path(model_id).is_dir() + started = time.perf_counter() + try: + tokenizer = AutoTokenizer.from_pretrained(model_id, **loader_kwargs) + encoder = AutoModel.from_pretrained(model_id, **loader_kwargs) + except OSError as exc: + raise _model_load_error(model_id, is_local) from exc + device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) + encoder = encoder.to(device).eval() + version = model_version + if not is_local: + version = _resolved_commit(model_id, loader_kwargs) or model_version + typer = cls( + encoder, + tokenizer, + categories=categories, + subcategories=subcategories, + model_id=model_id, + model_version=version, + ) + typer.device = device + _log_model_loaded(model_id, version, device, started, logger) + return typer @torch.no_grad() def _label_vecs(self, names: list[str], descs: dict) -> torch.Tensor: @@ -92,6 +179,17 @@ def _label_vecs(self, names: list[str], descs: dict) -> torch.Tensor: m = enc.attention_mask.unsqueeze(-1).float() return torch.nn.functional.normalize((h * m).sum(1) / m.sum(1).clamp(min=1), dim=-1) + def _get_scoring_lock(self) -> threading.RLock: + """Return the typing lock, creating it on first use (not in ``__init__``).""" + lock = vars(self).get("_scoring_lock") + if lock is None: + with _LOCK_GUARD: + lock = vars(self).get("_scoring_lock") + if lock is None: + lock = threading.RLock() + self._scoring_lock = lock + return lock + @torch.no_grad() def type_spans(self, answer: str, context: str, spans: list[dict]) -> list[dict]: """Attach ``category`` and ``subcategory`` to each span (offsets relative to ``answer``). @@ -103,18 +201,20 @@ def type_spans(self, answer: str, context: str, spans: list[dict]) -> list[dict] """ if not spans: return spans - enc = self.tokenizer( - answer + _SEP + (context or ""), - truncation=True, - max_length=self.max_length, - return_offsets_mapping=True, - return_tensors="pt", - ) - offs = enc.pop("offset_mapping")[0].tolist() - h = self.encoder( - input_ids=enc.input_ids.to(self.device), - attention_mask=enc.attention_mask.to(self.device), - ).last_hidden_state.float()[0] + # The tokenizer and encoder are shared state; everything after this block is local. + with self._get_scoring_lock(): + enc = self.tokenizer( + answer + _SEP + (context or ""), + truncation=True, + max_length=self.max_length, + return_offsets_mapping=True, + return_tensors="pt", + ) + offs = enc.pop("offset_mapping")[0].tolist() + h = self.encoder( + input_ids=enc.input_ids.to(self.device), + attention_mask=enc.attention_mask.to(self.device), + ).last_hidden_state.float()[0] for sp in spans: s, e = sp["start"], sp["end"] mask = torch.tensor( diff --git a/lettucedetect/detectors/transformer.py b/lettucedetect/detectors/transformer.py index 5c0bad0..76c554f 100644 --- a/lettucedetect/detectors/transformer.py +++ b/lettucedetect/detectors/transformer.py @@ -75,7 +75,9 @@ def __init__( categories, subcategories = _resolve_taxonomy(taxonomy_head, include_taxonomy) tokenizer = AutoTokenizer.from_pretrained(model_path, **tok_kwargs) model = AutoModelForTokenClassification.from_pretrained(model_path, **tok_kwargs) - device, typer = _finish_load(model, device, taxonomy_head, categories, subcategories) + device, typer = _finish_load( + model, device, taxonomy_head, categories, subcategories, tok_kwargs + ) version = None if Path(model_path).is_dir() else _resolved_commit(model_path, tok_kwargs) super().__init__( model, diff --git a/tests/test_custom_taxonomy_pytest.py b/tests/test_custom_taxonomy_pytest.py index 0c148e3..f2b54a6 100644 --- a/tests/test_custom_taxonomy_pytest.py +++ b/tests/test_custom_taxonomy_pytest.py @@ -211,7 +211,7 @@ def eval(self): monkeypatch.setattr( th, "AutoModel", type("M", (), {"from_pretrained": lambda *a, **k: StubModel()}) ) - typer = th.TaxonomyTyper( + typer = th.TaxonomyTyper.from_pretrained( "stub", device="cpu", categories=CUSTOM_CATS, subcategories=CUSTOM_SUBS ) assert typer.cat_names == ["pricing_claim"] diff --git a/tests/test_encoder_from_pretrained_pytest.py b/tests/test_encoder_from_pretrained_pytest.py index d50d121..4f291eb 100644 --- a/tests/test_encoder_from_pretrained_pytest.py +++ b/tests/test_encoder_from_pretrained_pytest.py @@ -146,13 +146,13 @@ def test_taxonomy_head_loads_the_typer_with_the_device(loaders): taxonomy_head="org/head", include_taxonomy={"Fabricated": "Made up facts"}, ) - typer_class.assert_called_once_with( + typer_class.from_pretrained.assert_called_once_with( "org/head", device=torch.device("cpu"), categories={"Fabricated": "Made up facts"}, subcategories=None, ) - assert detector.typer is typer_class.return_value + assert detector.typer is typer_class.from_pretrained.return_value def test_no_taxonomy_head_means_no_typer(loaders): diff --git a/tests/test_taxonomy_typer_pytest.py b/tests/test_taxonomy_typer_pytest.py new file mode 100644 index 0000000..f2ba63c --- /dev/null +++ b/tests/test_taxonomy_typer_pytest.py @@ -0,0 +1,369 @@ +"""Tests for ``TaxonomyTyper``: built from loaded objects, and ``from_pretrained``, offline.""" + +from __future__ import annotations + +import logging +import os +import socket +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors.encoder import EncoderDetector +from lettucedetect.detectors.errors import ConfigurationError, UpstreamError +from lettucedetect.detectors.taxonomy_head import TaxonomyTyper +from tests.test_encoder_detector_pytest import _stub_model + +CATS = {"pricing_claim": "any statement about price not supported by the context"} +SUBS = {"currency": "a currency amount not present in the context"} +SHA_HEAD = "c" * 40 +SHA_MAIN = "a" * 40 +SECRET_ANSWER = "ZEBRA-ANSWER-TEXT" # noqa: S105 + + +class _StubEncoder: + """A label-conditioned encoder with a fixed hidden state.""" + + def __init__(self, device: torch.device | None = None) -> None: + if device is not None: + self.device = device + self.calls = 0 + + def to(self, device): + self.device = torch.device(device) + return self + + def eval(self): + return self + + def __call__(self, input_ids, attention_mask): + self.calls += 1 + hidden = torch.arange(input_ids.numel() * 8, dtype=torch.float).reshape(*input_ids.shape, 8) + return SimpleNamespace(last_hidden_state=hidden) + + +@pytest.fixture +def block_network(monkeypatch): + """Fail any test that opens a socket.""" + + def no_network(*args: object, **kwargs: object) -> None: + raise AssertionError("network used") + + monkeypatch.setattr(socket.socket, "connect", no_network) + + +@pytest.fixture +def offline_cache(tmp_path, monkeypatch, block_network): + """Build a Hugging Face cache with the encoder and the head, with the network blocked.""" + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + for repo_name, sha in (("models--org--name", SHA_MAIN), ("models--org--head", SHA_HEAD)): + repo = tmp_path / "hub" / repo_name + (repo / "snapshots" / sha).mkdir(parents=True) + (repo / "snapshots" / sha / "config.json").write_text("{}") + (repo / "refs").mkdir() + (repo / "refs" / "main").write_text(sha) + return tmp_path / "hub" + + +@pytest.fixture +def head_loaders(local_wordpiece_tokenizer): + """Fake ``from_pretrained`` loaders for the head; yields the encoder and both mocks.""" + encoder = _StubEncoder() + tok_loader = MagicMock(return_value=local_wordpiece_tokenizer) + model_loader = MagicMock(return_value=encoder) + with ( + patch("transformers.AutoTokenizer.from_pretrained", tok_loader), + patch("transformers.AutoModel.from_pretrained", model_loader), + ): + yield encoder, tok_loader, model_loader + + +# ---------------------------------------------------------------------- +# Construction from loaded objects +# ---------------------------------------------------------------------- + + +def test_construction_downloads_nothing(local_wordpiece_tokenizer, block_network): + boom = MagicMock(side_effect=AssertionError("loader called")) + with ( + patch("transformers.AutoTokenizer.from_pretrained", boom), + patch("transformers.AutoModel.from_pretrained", boom), + ): + typer = TaxonomyTyper(_StubEncoder(), local_wordpiece_tokenizer) + boom.assert_not_called() + assert typer.cat_names and typer.sub_names + + +def test_construction_does_not_move_or_switch_the_encoder(local_wordpiece_tokenizer): + class Spy(_StubEncoder): + moved = switched = False + + def to(self, device): + self.moved = True + return super().to(device) + + def eval(self): + self.switched = True + return super().eval() + + encoder = Spy() + TaxonomyTyper(encoder, local_wordpiece_tokenizer, categories=CATS, subcategories=SUBS) + assert (encoder.moved, encoder.switched) == (False, False) + + +def test_constructor_records_ids_and_takes_the_device_from_the_encoder(local_wordpiece_tokenizer): + typer = TaxonomyTyper( + _StubEncoder(torch.device("cpu")), + local_wordpiece_tokenizer, + categories=CATS, + subcategories=SUBS, + max_length=64, + model_id="org/head", + model_version="v3", + ) + assert (typer.model_id, typer.model_version, typer.max_length) == ("org/head", "v3", 64) + assert typer.device == torch.device("cpu") + + +def test_a_device_less_encoder_falls_back_to_cpu(local_wordpiece_tokenizer): + typer = TaxonomyTyper(_StubEncoder(), local_wordpiece_tokenizer) + assert typer.device == torch.device("cpu") + assert (typer.model_id, typer.model_version) == (None, None) + + +def test_custom_labels_replace_the_frozen_set(local_wordpiece_tokenizer): + typer = TaxonomyTyper( + _StubEncoder(), local_wordpiece_tokenizer, categories=CATS, subcategories=SUBS + ) + assert (typer.cat_names, typer.sub_names) == (["pricing_claim"], ["currency"]) + + +def test_type_spans_attaches_a_category_and_subcategory(local_wordpiece_tokenizer): + typer = TaxonomyTyper( + _StubEncoder(), local_wordpiece_tokenizer, categories=CATS, subcategories=SUBS + ) + spans = [{"start": 0, "end": 3, "confidence": 0.9, "text": "the"}] + typed = typer.type_spans("the capital", "paris", spans) + assert typed is spans + assert (typed[0]["category"], typed[0]["subcategory"]) == ("pricing_claim", "currency") + assert typer.type_spans("the capital", "paris", []) == [] + + +# ---------------------------------------------------------------------- +# from_pretrained +# ---------------------------------------------------------------------- + + +def test_from_pretrained_builds_a_typer_and_passes_device_and_kwargs(head_loaders): + encoder, tok_loader, model_loader = head_loaders + typer = TaxonomyTyper.from_pretrained( + "org/head", device="cpu", categories=CATS, subcategories=SUBS, local_files_only=True + ) + tok_loader.assert_called_once_with("org/head", local_files_only=True) + model_loader.assert_called_once_with("org/head", local_files_only=True) + assert typer.encoder is encoder + assert typer.device == torch.device("cpu") + assert encoder.device == torch.device("cpu") + assert (typer.cat_names, typer.sub_names) == (["pricing_claim"], ["currency"]) + assert typer.model_id == "org/head" + + +def test_hub_id_reports_the_resolved_commit(head_loaders, offline_cache): + typer = TaxonomyTyper.from_pretrained("org/head", cache_dir=str(offline_cache)) + assert typer.model_version == SHA_HEAD + + +def test_resolved_commit_wins_over_the_callers_version(head_loaders, offline_cache): + typer = TaxonomyTyper.from_pretrained( + "org/head", model_version="mine", cache_dir=str(offline_cache) + ) + assert typer.model_version == SHA_HEAD + + +def test_callers_version_is_the_fallback_when_nothing_is_cached(head_loaders, offline_cache): + kwargs = {"cache_dir": str(offline_cache)} + assert TaxonomyTyper.from_pretrained("other/head", **kwargs).model_version is None + assert ( + TaxonomyTyper.from_pretrained("other/head", model_version="v7", **kwargs).model_version + == "v7" + ) + + +def test_local_path_uses_the_callers_version_and_no_cache_lookup(head_loaders, tmp_path): + boom = MagicMock(side_effect=AssertionError("cache consulted")) + with patch("lettucedetect.detectors.encoder.try_to_load_from_cache", boom): + assert TaxonomyTyper.from_pretrained(str(tmp_path)).model_version is None + typer = TaxonomyTyper.from_pretrained(str(tmp_path), model_version="2024-05") + assert typer.model_version == "2024-05" + boom.assert_not_called() + + +def test_model_loaded_is_logged_exactly_once_at_info(head_loaders, offline_cache, caplog): + caplog.set_level(logging.DEBUG) + typer = TaxonomyTyper.from_pretrained("org/head", device="cpu", cache_dir=str(offline_cache)) + typer.type_spans(SECRET_ANSWER, "context", [{"start": 0, "end": 4}]) + loud = [r for r in caplog.records if r.levelno >= logging.INFO] + assert len(loud) == 1 + record = loud[0] + assert (record.levelno, record.name, record.event) == ( + logging.INFO, + "lettucedetect.detectors.taxonomy_head", + "model_loaded", + ) + assert record.args[:3] == ("org/head", SHA_HEAD, torch.device("cpu")) + assert SECRET_ANSWER not in caplog.text + + +def test_building_from_objects_logs_nothing_at_info(local_wordpiece_tokenizer, caplog): + caplog.set_level(logging.DEBUG) + TaxonomyTyper(_StubEncoder(), local_wordpiece_tokenizer) + assert [r for r in caplog.records if r.levelno >= logging.INFO] == [] + + +def test_loader_failure_for_a_hub_id_is_an_upstream_error(head_loaders): + _, tok_loader, _ = head_loaders + tok_loader.side_effect = OSError("secret detail") + with pytest.raises(UpstreamError) as exc: + TaxonomyTyper.from_pretrained("org/head") + assert (exc.value.code, exc.value.service) == ("model_load_failed", "huggingface") + assert "secret detail" not in str(exc.value) + assert isinstance(exc.value.__cause__, OSError) + + +def test_loader_failure_for_a_local_path_is_a_configuration_error(head_loaders, tmp_path): + _, _, model_loader = head_loaders + model_loader.side_effect = OSError("secret detail") + with pytest.raises(ConfigurationError) as exc: + TaxonomyTyper.from_pretrained(str(tmp_path)) + assert (exc.value.code, exc.value.param) == ("model_load_failed", "model_id") + assert "secret detail" not in str(exc.value) + assert isinstance(exc.value.__cause__, OSError) + + +# ---------------------------------------------------------------------- +# Offline behaviour matches the encoder's +# ---------------------------------------------------------------------- + + +def test_uncached_hub_head_offline_raises_upstream_error(offline_cache): + """With ``HF_HUB_OFFLINE=1`` and nothing cached the loader error is translated.""" + with pytest.raises(UpstreamError) as exc: + TaxonomyTyper.from_pretrained("nope/not-cached", cache_dir=str(offline_cache)) + assert (exc.value.code, exc.value.service) == ("model_load_failed", "huggingface") + assert isinstance(exc.value.__cause__, OSError) + + +def test_from_pretrained_neither_reads_nor_sets_the_offline_variable(head_loaders, monkeypatch): + monkeypatch.delenv("HF_HUB_OFFLINE", raising=False) + TaxonomyTyper.from_pretrained("org/head") + assert "HF_HUB_OFFLINE" not in os.environ + monkeypatch.setenv("HF_HUB_OFFLINE", "0") + TaxonomyTyper.from_pretrained("org/head") + assert os.environ["HF_HUB_OFFLINE"] == "0" + + +def test_a_typed_encoder_load_follows_the_cache_and_skips_the_revision( + local_wordpiece_tokenizer, offline_cache +): + """Both models load from the caller's cache; ``revision`` names only the encoder's repo.""" + tok_loader = MagicMock(return_value=local_wordpiece_tokenizer) + encoder_loader = MagicMock(return_value=_stub_model()) + head_loader = MagicMock(return_value=_StubEncoder()) + with ( + patch("transformers.AutoTokenizer.from_pretrained", tok_loader), + patch("transformers.AutoModelForTokenClassification.from_pretrained", encoder_loader), + patch("transformers.AutoModel.from_pretrained", head_loader), + ): + detector = EncoderDetector.from_pretrained( + "org/name", + device="cpu", + taxonomy_head="org/head", + include_taxonomy={"categories": CATS, "subcategories": SUBS}, + cache_dir=str(offline_cache), + revision="main", + token="t", # noqa: S106 + ) + head_loader.assert_called_once_with("org/head", cache_dir=str(offline_cache), token="t") # noqa: S106 + encoder_loader.assert_called_once_with( + "org/name", + cache_dir=str(offline_cache), + revision="main", + token="t", # noqa: S106 + ) + assert detector.model_version == SHA_MAIN + assert detector.typer.model_version == SHA_HEAD + assert (detector.typer.cat_names, detector.typer.sub_names) == (["pricing_claim"], ["currency"]) + + +@pytest.mark.parametrize( + ("include_taxonomy", "expected"), + [ + (True, (None, None)), + (["unsupported_addition"], (["unsupported_addition"], None)), + (CATS, (["pricing_claim"], None)), + ({"categories": CATS, "subcategories": SUBS}, (["pricing_claim"], ["currency"])), + ], + ids=["true", "list", "flat-dict", "nested-dict"], +) +def test_all_four_taxonomy_forms_reach_the_typer(include_taxonomy, expected, head_loaders): + typer_class = MagicMock() + with ( + patch("lettucedetect.detectors.taxonomy_head.TaxonomyTyper", typer_class), + patch("transformers.AutoModelForTokenClassification.from_pretrained") as model_loader, + ): + model_loader.return_value = _stub_model() + EncoderDetector.from_pretrained( + "org/name", device="cpu", taxonomy_head="org/head", include_taxonomy=include_taxonomy + ) + kwargs = typer_class.from_pretrained.call_args.kwargs + cats = None if kwargs["categories"] is None else list(kwargs["categories"]) + subs = None if kwargs["subcategories"] is None else list(kwargs["subcategories"]) + assert (cats, subs) == expected + + +# ---------------------------------------------------------------------- +# Concurrency +# ---------------------------------------------------------------------- + + +def test_concurrent_type_spans_calls_run_one_at_a_time(local_wordpiece_tokenizer): + """Worker threads (``adetect``) or detectors sharing one typer never overlap in the encoder.""" + state = {"active": 0, "max_active": 0} + guard = threading.Lock() + + class Slow(_StubEncoder): + def __call__(self, input_ids, attention_mask): + with guard: + state["active"] += 1 + state["max_active"] = max(state["max_active"], state["active"]) + time.sleep(0.02) + try: + return super().__call__(input_ids, attention_mask) + finally: + with guard: + state["active"] -= 1 + + typer = TaxonomyTyper(Slow(), local_wordpiece_tokenizer, categories=CATS, subcategories=SUBS) + state["max_active"] = 0 # ignore the label-embedding calls made at construction + + def run() -> list[dict]: + return typer.type_spans("the capital", "paris", [{"start": 0, "end": 3}]) + + with ThreadPoolExecutor(max_workers=8) as pool: + results = [f.result() for f in [pool.submit(run) for _ in range(8)]] + assert state["max_active"] == 1 + assert all(r[0]["category"] == "pricing_claim" for r in results) + + +def test_the_typing_lock_is_per_typer_and_reentrant(local_wordpiece_tokenizer): + first = TaxonomyTyper(_StubEncoder(), local_wordpiece_tokenizer) + second = TaxonomyTyper(_StubEncoder(), local_wordpiece_tokenizer) + assert first._get_scoring_lock() is first._get_scoring_lock() + assert first._get_scoring_lock() is not second._get_scoring_lock() + with first._get_scoring_lock(), first._get_scoring_lock(): + pass From 2529b51ec79faf06993e2701d27036b7258bd807 Mon Sep 17 00:00:00 2001 From: Levente Heizer-Sarkadi Date: Mon, 9 Nov 2026 15:31:05 +0100 Subject: [PATCH 28/60] feat: type spans in EncoderDetector.detect and meter the typer (#155) --- lettucedetect/detectors/encoder.py | 43 +++++- lettucedetect/detectors/taxonomy_head.py | 24 ++++ tests/test_encoder_detector_pytest.py | 174 +++++++++++++++++++++++ tests/test_golden_transformer_pytest.py | 23 +++ 4 files changed, 259 insertions(+), 5 deletions(-) diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py index ee4928d..9172c64 100644 --- a/lettucedetect/detectors/encoder.py +++ b/lettucedetect/detectors/encoder.py @@ -224,7 +224,9 @@ class EncoderDetector(BaseDetector): :param model: a token classification model. :param tokenizer: the model's fast tokenizer. - :param typer: optional span typer; accepted but not applied yet. + :param typer: optional span typer, for example a :class:`TaxonomyTyper`. With it every span + of ``detect`` carries ``category`` and ``subcategory``, and ``usage`` has a second + entry for the typer (unit ``spans``). :param config: options, ``EncoderConfig()`` when ``None``. :param model_id: id reported in ``usage``. :param model_version: version reported in ``usage``. @@ -286,7 +288,7 @@ def from_pretrained( :param model_id: Hugging Face id or local directory. :param device: device for the model; CUDA when available, else CPU, when ``None``. :param taxonomy_head: optional id or path of a label-conditioned typing head. It is - loaded, but spans are not typed until typed spans arrive. + loaded through ``TaxonomyTyper.from_pretrained`` and types the spans of ``detect``. :param include_taxonomy: label set for the typing head. :param model_version: version reported in ``usage`` for a local path. For a hub id the resolved commit is used and this is only the fallback. @@ -406,21 +408,36 @@ def _detect( if len(scored) == 1 else self._max_aggregate([group_tokens for group_tokens, _, _ in scored]) ) + span_items = self._spans_from_scored_tokens(tokens, answer) + typing_ms = 0.0 + if self.typer is not None and span_items: + # Typing runs outside the scoring lock: the typer serializes itself, and this keeps + # the encoder free for the next call. + typer_started = time.perf_counter() + span_items = self.typer.type_spans(answer, self._typer_context(request), span_items) + typing_ms = (time.perf_counter() - typer_started) * 1000 spans = [ DetectedSpan( - start=item["start"], end=item["end"], text=item["text"], score=item["confidence"] + start=item["start"], + end=item["end"], + text=item["text"], + score=item["confidence"], + category=item.get("category"), + subcategory=item.get("subcategory"), ) - for item in self._spans_from_scored_tokens(tokens, answer) + for item in span_items ] logger.debug( "detect finished: spans=%d answer_tokens=%d input_tokens=%d groups=%d " - "truncated=%s scoring_ms=%.1f", + "truncated=%s scoring_ms=%.1f typed=%s typing_ms=%.1f", len(spans), len(tokens), units["input_tokens"], len(scored), truncated, scoring_ms, + self.typer is not None, + typing_ms, ) token_scores = ( [ @@ -450,8 +467,24 @@ def _detect( else [] ) usage = [Usage(model_id=self.model_id, model_version=self.model_version, units=units)] + if self.typer is not None: + # The typer meters the spans it was given, before ``min_score`` filters them. + usage.append( + Usage( + model_id=getattr(self.typer, "model_id", None), + model_version=getattr(self.typer, "model_version", None), + units={"spans": len(span_items)}, + ) + ) return Detection(spans=spans, tokens=token_scores, usage=usage, warnings=warnings) + @staticmethod + def _typer_context(request: DetectRequest) -> str: + """Return the text the typer reads with the answer: joined sources, or the prompt.""" + if isinstance(request, SourcesInput): + return "\n".join(chunk.text for chunk in request.sources) + return request.prompt + def _score_tokens(self, prompt: str, answer: str) -> tuple[list[dict], int, int | None]: """Score the answer tokens of one (prompt, answer) pair. diff --git a/lettucedetect/detectors/taxonomy_head.py b/lettucedetect/detectors/taxonomy_head.py index 9f9c062..6f34f25 100644 --- a/lettucedetect/detectors/taxonomy_head.py +++ b/lettucedetect/detectors/taxonomy_head.py @@ -66,6 +66,30 @@ class TaxonomyTyper: Typing runs under one private lock, so concurrent calls on one typer (for example from ``adetect`` worker threads, or from several detectors sharing it) run one at a time. + Example, loading the typing head once at startup and giving it to an encoder:: + + from transformers import AutoModel, AutoTokenizer + + head_id = "KRLabsOrg/lettucedect-v2-taxonomy-head" + tokenizer = AutoTokenizer.from_pretrained(head_id) + encoder = AutoModel.from_pretrained(head_id).eval() + + typer = TaxonomyTyper( + encoder, + tokenizer, + max_length=1024, + model_id=head_id, + ) + detector = EncoderDetector(model, model_tokenizer, typer, model_id=model_id) + result = detector.detect(request) # every span has category and subcategory + + The typer reads its device from ``encoder.device``, so move the encoder before building it. + To let the typer load itself, and record the resolved commit as ``model_version`` and log + ``model_loaded``, use ``TaxonomyTyper.from_pretrained(head_id, device="cuda")``. Custom + labels work with both:: + + TaxonomyTyper(encoder, tokenizer, categories={"pricing_claim": "a price not in the context"}) + :param encoder: the label-conditioned encoder, ready for inference (it is not moved or switched to eval mode). :param tokenizer: the encoder's fast tokenizer. diff --git a/tests/test_encoder_detector_pytest.py b/tests/test_encoder_detector_pytest.py index 168b2ff..8e99272 100644 --- a/tests/test_encoder_detector_pytest.py +++ b/tests/test_encoder_detector_pytest.py @@ -500,3 +500,177 @@ def _tokenizer(self, local_wordpiece_tokenizer): def make_detector(self, on_call=None): """Build a detector whose stub model calls ``on_call`` in its forward pass.""" return _detector(self.tokenizer, on_call=on_call) + + +# -- typed spans and typer usage ------------------------------------------------------------ + +TYPER_ID, TYPER_VERSION = "stub-typer", "c0ffee" +ZERO_SPAN_REQUEST = PromptInput(prompt="the capital of france is paris .", answer="the") + + +class _Typer: + """A stub typer: tags each span from its text and context, and records its calls.""" + + model_id = TYPER_ID + model_version = TYPER_VERSION + + def __init__(self, delay: float = 0.0, error: Exception | None = None) -> None: + self.delay, self.error = delay, error + self.calls: list[tuple[str, str, int]] = [] + self.threads: list[int] = [] + + def type_spans(self, answer, context, spans): + self.threads.append(threading.get_ident()) + self.calls.append((answer, context, len(spans))) + if self.error is not None: + raise self.error + if self.delay: + time.sleep(self.delay) + for span in spans: + span["category"] = f"CAT[{span['text']}]" + span["subcategory"] = f"SUB[{len(context)}]" + return spans + + +def _typed(tokenizer, typer=None, **kwargs) -> EncoderDetector: + return EncoderDetector( + _stub_model(), + tokenizer, + typer if typer is not None else _Typer(), + config=EncoderConfig(max_length=512), + model_id="stub-encoder", + **kwargs, + ) + + +def test_every_span_is_typed_with_a_typer_and_untyped_without(local_wordpiece_tokenizer): + request = _sources(*PREDICT_INPUTS[0]) + typed = _typed(local_wordpiece_tokenizer).detect(request).spans + untyped = _detector(local_wordpiece_tokenizer).detect(request).spans + assert typed and len(typed) == len(untyped) + assert all(s.category == f"CAT[{s.text}]" and s.subcategory for s in typed) + assert all(s.category is None and s.subcategory is None for s in untyped) + # Typing adds the two labels and changes nothing else. + assert [s.model_dump(exclude={"category", "subcategory"}) for s in typed] == [ + s.model_dump(exclude={"category", "subcategory"}) for s in untyped + ] + + +def test_typer_reads_the_joined_sources_or_the_prompt(local_wordpiece_tokenizer): + typer = _Typer() + det = _typed(local_wordpiece_tokenizer, typer) + det.detect(_sources(["the capital", "of france"], "paris is the capital .")) + det.detect(PromptInput(prompt=PROMPTS[0], answer=ANSWERS[0])) + assert [(answer, context) for answer, context, _ in typer.calls] == [ + ("paris is the capital .", "the capital\nof france"), + (ANSWERS[0], PROMPTS[0]), + ] + + +def test_usage_has_the_encoder_and_the_typer_with_its_span_count(local_wordpiece_tokenizer): + result = _typed(local_wordpiece_tokenizer).detect(_sources(*PREDICT_INPUTS[0])) + encoder, typer = result.usage + assert (encoder.model_id, encoder.model_version) == ("stub-encoder", None) + assert (typer.model_id, typer.model_version) == (TYPER_ID, TYPER_VERSION) + assert typer.units == {"spans": len(result.spans)} and result.spans + + +def test_usage_has_one_entry_without_a_typer(local_wordpiece_tokenizer): + assert len(_detector(local_wordpiece_tokenizer).detect(_sources(*PREDICT_INPUTS[0])).usage) == 1 + + +def test_typer_usage_reports_zero_spans_when_nothing_is_flagged(local_wordpiece_tokenizer): + typer = _Typer() + result = _typed(local_wordpiece_tokenizer, typer).detect(ZERO_SPAN_REQUEST) + assert result.spans == [] + assert [u.model_id for u in result.usage] == ["stub-encoder", TYPER_ID] + assert result.usage[1].units == {"spans": 0} + assert typer.calls == [] # nothing to type, so the typer is not called + + +def test_a_typer_without_ids_is_metered_with_none(local_wordpiece_tokenizer): + class Bare: + def type_spans(self, answer, context, spans): + for span in spans: + span["category"], span["subcategory"] = "c", "s" + return spans + + typer_usage = _typed(local_wordpiece_tokenizer, Bare()).detect(_sources(*PREDICT_INPUTS[0])) + assert (typer_usage.usage[1].model_id, typer_usage.usage[1].model_version) == (None, None) + + +def test_the_typer_meters_spans_before_min_score_filters_them(local_wordpiece_tokenizer): + det = _typed(local_wordpiece_tokenizer) + request = TestEncoderDetectorContract.sources_request + everything = det.detect(request) + top = max(s.score for s in everything.spans) + kept = det.detect(request, min_score=top) + assert 0 < len(kept.spans) < len(everything.spans) + assert kept.usage[1].units == everything.usage[1].units == {"spans": len(everything.spans)} + assert all(s.category for s in kept.spans) + + +async def test_adetect_on_a_typed_detector_equals_detect(local_wordpiece_tokenizer): + typer = _Typer() + det = _typed(local_wordpiece_tokenizer, typer) + for request in ( + _sources(*PREDICT_INPUTS[0]), + PromptInput(prompt=PROMPTS[0], answer=ANSWERS[0]), + ZERO_SPAN_REQUEST, + ): + asynchronous = await det.adetect(request) + assert asynchronous == det.detect(request) + assert len(asynchronous.usage) == 2 + assert threading.get_ident() not in typer.threads[:1] # the first (async) call ran off-loop + + +async def test_a_slow_typer_does_not_block_the_event_loop(local_wordpiece_tokenizer): + det = _typed(local_wordpiece_tokenizer, _Typer(delay=0.3)) + ticks = 0 + + async def ticker(): + nonlocal ticks + while True: + await asyncio.sleep(0.01) + ticks += 1 + + task = asyncio.create_task(ticker()) + result = await det.adetect(_sources(*PREDICT_INPUTS[0])) + task.cancel() + assert result.spans and ticks >= 10 + + +def test_a_failing_typer_raises_instead_of_returning_untyped_spans(local_wordpiece_tokenizer): + det = _typed(local_wordpiece_tokenizer, _Typer(error=RuntimeError("boom"))) + with pytest.raises(RuntimeError, match="boom"): + det.detect(_sources(*PREDICT_INPUTS[0])) + + +def test_a_typed_call_logs_no_customer_text(local_wordpiece_tokenizer, caplog): + caplog.set_level(logging.DEBUG) + _typed(local_wordpiece_tokenizer).detect( + PromptInput(prompt="the capital of france is paris .", answer="paris is the capital") + ) + assert "paris is the capital" not in caplog.text + assert "france is paris" not in caplog.text + + +class TestTypedEncoderDetectorContract(TestEncoderDetectorContract): + """The detector contract suite, run against an EncoderDetector with a stub typer.""" + + def make_detector(self, on_call=None): + """Build a typed detector whose stub model calls ``on_call`` in its forward pass.""" + return EncoderDetector( + _stub_model(on_call=on_call), + self.tokenizer, + _Typer(), + config=EncoderConfig(max_length=512), + model_id="stub-encoder", + ) + + def test_every_span_is_typed(self): + """Every span of both request kinds carries both labels.""" + detector = self.make_detector() + for request in self._requests(): + spans = detector.detect(request).spans + assert spans and all(s.category and s.subcategory for s in spans) diff --git a/tests/test_golden_transformer_pytest.py b/tests/test_golden_transformer_pytest.py index 1cf38c6..cd84b14 100644 --- a/tests/test_golden_transformer_pytest.py +++ b/tests/test_golden_transformer_pytest.py @@ -16,6 +16,7 @@ import torch from lettucedetect.detectors.transformer import TransformerDetector +from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput from tests.golden import assert_golden pytestmark = pytest.mark.filterwarnings( @@ -159,3 +160,25 @@ def test_typed_spans(self, detector): "predict_prompt_batch": _predict_prompt_batch(detector, "spans"), }, ) + + def test_detect_types_spans_like_predict(self, detector): + """``detect`` and ``predict`` hand the typer the same context, so labels agree.""" + detector.typer = _StubTyper() + for context, answer, question in PREDICT_INPUTS: + request = SourcesInput( + sources=[Chunk(id=str(i), text=t) for i, t in enumerate(context)], + answer=answer, + question=question, + ) + typed = detector.predict(context, answer, question, output_format="spans") + spans = detector.detect(request).spans + assert typed + assert [(s.start, s.end, s.category, s.subcategory) for s in spans] == [ + (d["start"], d["end"], d["category"], d["subcategory"]) for d in typed + ] + for prompt, answer in zip(PROMPTS, ANSWERS, strict=True): + typed = detector.predict_prompt(prompt, answer, output_format="spans") + spans = detector.detect(PromptInput(prompt=prompt, answer=answer)).spans + assert [(s.category, s.subcategory) for s in spans] == [ + (d["category"], d["subcategory"]) for d in typed + ] From 580b2d8f01f2283088fc530537e65fab0f4777fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20=C3=81d=C3=A1m?= Date: Mon, 16 Nov 2026 14:05:03 +0100 Subject: [PATCH 29/60] fix: detect interface bugs from #192 and run the tests on stateless_core PRs (#195) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - EncoderDetector takes typer, config, model_id and model_version by keyword only, so a config passed third is no longer taken as the typer. - Detectors built on one tokenizer share one scoring lock. A fast tokenizer fails with 'Already borrowed' when two threads use it at once, also through two detectors. - Detection.tokens leaves out zero-width special tokens such as the trailing [SEP], and TokenScore rejects an end that is not after its start. - detect() raises InvalidInputError (invalid_request) for a request that is not a SourcesInput or a PromptInput. - make_cache_key accepts a kind of the caller's own. - predict() on a detector without token scores names output_format="spans" in its error. - CONTRIBUTING names the right deprecation test file, and the EncoderConfig.batch_size docstring says what detect does today. - The test workflow also runs on pull requests against stateless_core. Signed-off-by: Kovács Ádám --- .github/workflows/python-tests.yml | 2 +- CONTRIBUTING.md | 2 +- lettucedetect/detectors/base.py | 15 ++++++++- lettucedetect/detectors/encoder.py | 26 +++++++++++---- lettucedetect/detectors/response_cache.py | 21 +++++++------ lettucedetect/detectors/taxonomy_head.py | 2 +- lettucedetect/detectors/transformer.py | 2 +- lettucedetect/detectors/types.py | 6 ++++ tests/test_base_detector_pytest.py | 27 ++++++++++++++++ tests/test_encoder_detector_pytest.py | 35 ++++++++++++--------- tests/test_response_cache_pytest.py | 12 +++++-- tests/test_transformer_deprecated_pytest.py | 3 +- tests/test_types_pytest.py | 7 +++++ 13 files changed, 122 insertions(+), 38 deletions(-) diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index c116ce6..25bc364 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main] + branches: [main, stateless_core] jobs: lint: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c0b544..19fd5c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -83,7 +83,7 @@ are applications: they configure logging themselves and may print. mask `ConfigurationError`, `InvalidInputError` or bugs. - **`warnings.warn` is only for deprecations**, and uses `LettuceDetectDeprecationWarning`. The test suite treats that class as an error, so add each new deprecation to the catalogue in - `tests/test_deprecation.py`. + `tests/test_deprecation_pytest.py`. ### Logging diff --git a/lettucedetect/detectors/base.py b/lettucedetect/detectors/base.py index 436a43c..37926dd 100644 --- a/lettucedetect/detectors/base.py +++ b/lettucedetect/detectors/base.py @@ -87,9 +87,16 @@ def detect( :param include_tokens: also return token scores (needs ``supports_tokens``). :param include_detail: also return fact checker evidence (needs ``supports_detail``). :returns: the detection result. - :raises InvalidInputError: if ``min_score`` is outside ``[0, 1]``, or a flag is set that + :raises InvalidInputError: if ``request`` is not a ``SourcesInput`` or ``PromptInput`` + (``invalid_request``), ``min_score`` is outside ``[0, 1]``, or a flag is set that the detector does not support. """ + if not isinstance(request, (SourcesInput, PromptInput)): + raise InvalidInputError( + "request must be a SourcesInput or a PromptInput.", + code="invalid_request", + param="request", + ) if not 0.0 <= min_score <= 1.0: raise InvalidInputError( "min_score must be in [0, 1]; pass a value between 0.0 and 1.0.", @@ -267,6 +274,12 @@ def _predict_via_detect( ) -> list: """Answer a ``predict*`` call with :meth:`detect`, in the legacy dict format.""" self._check_legacy_arguments(output_format, min_confidence) + if output_format == "tokens" and not self.supports_tokens: + raise InvalidInputError( + 'This detector does not return token scores; call with output_format="spans".', + code="tokens_not_supported", + param="output_format", + ) detection = self.detect( request, min_score=min_confidence, include_tokens=output_format == "tokens" ) diff --git a/lettucedetect/detectors/encoder.py b/lettucedetect/detectors/encoder.py index 9172c64..341073c 100644 --- a/lettucedetect/detectors/encoder.py +++ b/lettucedetect/detectors/encoder.py @@ -5,6 +5,7 @@ import logging import threading import time +import weakref from pathlib import Path from typing import Any @@ -47,8 +48,12 @@ def _resolved_commit(model_id: str, loader_kwargs: dict[str, Any]) -> str | None return Path(cached).parent.name if isinstance(cached, str) else None -# Makes two racing first calls on one detector get the same scoring lock. +# Makes two racing first calls get the same scoring lock. _LOCK_GUARD = threading.Lock() +# One scoring lock per tokenizer, by id(tokenizer). A fast tokenizer fails with "Already borrowed" +# when two threads use it at once, also through two detectors. An entry lives as long as a +# detector holds its lock, and that detector holds the tokenizer, so an id is never reused. +_TOKENIZER_LOCKS: weakref.WeakValueDictionary[int, threading.RLock] = weakref.WeakValueDictionary() def _resolve_taxonomy( @@ -153,7 +158,8 @@ class EncoderConfig(BaseModel): ``invalid_language`` or ``invalid_batch_size`` and ``param`` set to the option. :param max_length: maximum number of tokens of prompt plus answer. - :param batch_size: number of requests scored together in one padded forward pass. + :param batch_size: number of prompts ``predict_prompt_batch`` scores together in one padded + forward pass. ``detect`` scores one request at a time. :param lang: language of the prompt template, one of the supported languages. """ @@ -241,8 +247,8 @@ def __init__( self, model: Any, # noqa: ANN401 tokenizer: Any, # noqa: ANN401 - typer: Any = None, # noqa: ANN401 *, + typer: Any = None, # noqa: ANN401 config: EncoderConfig | None = None, model_id: str | None = None, model_version: str | None = None, @@ -317,7 +323,7 @@ def from_pretrained( detector, model, tokenizer, - typer, + typer=typer, config=config, model_id=model_id, model_version=version, @@ -331,13 +337,19 @@ def from_pretrained( # ------------------------------------------------------------------ def _get_scoring_lock(self) -> threading.RLock: - """Return the scoring lock, creating it on first use (not in ``__init__``).""" + """Return the scoring lock, taking it on first use (not in ``__init__``). + + Detectors built on the same tokenizer share one lock. + """ lock = vars(self).get("_scoring_lock") if lock is None: with _LOCK_GUARD: lock = vars(self).get("_scoring_lock") if lock is None: - lock = threading.RLock() + lock = _TOKENIZER_LOCKS.get(id(self.tokenizer)) + if lock is None: + lock = threading.RLock() + _TOKENIZER_LOCKS[id(self.tokenizer)] = lock self._scoring_lock = lock return lock @@ -449,6 +461,8 @@ def _detect( flagged=t["pred"] == 1, ) for t in tokens + # Special tokens such as the trailing [SEP] are zero-width: not answer tokens. + if t["end"] > t["start"] ] if include_tokens else None diff --git a/lettucedetect/detectors/response_cache.py b/lettucedetect/detectors/response_cache.py index 1e0018b..a7d8338 100644 --- a/lettucedetect/detectors/response_cache.py +++ b/lettucedetect/detectors/response_cache.py @@ -6,8 +6,8 @@ New error codes (public API, do not rename): -- ``invalid_cache_kind``: ``kind`` of :func:`make_cache_key` is not ``"judge"``, ``"native"`` - or ``"verify"``. +- ``invalid_cache_kind``: ``kind`` of :func:`make_cache_key` is blank, is not a string or + contains ``=``. - ``invalid_ttl_seconds``: ``ttl_seconds`` is not a positive, finite number. """ @@ -20,14 +20,14 @@ import math import threading import time -from typing import Literal, Protocol, runtime_checkable +from typing import Protocol, runtime_checkable from lettucedetect.detectors.errors import InvalidInputError logger = logging.getLogger(__name__) -CacheKind = Literal["judge", "native", "verify"] -_KINDS = ("judge", "native", "verify") +CacheKind = str +"""What a cached reply is for. The library uses ``"judge"``, ``"native"`` and ``"verify"``.""" @runtime_checkable @@ -93,13 +93,16 @@ def make_cache_key( :param model: The model name. :param model_version: A version or deployment id of the model, or ``None``. :param temperature: The sampling temperature. - :param kind: ``"judge"``, ``"native"`` or ``"verify"``. + :param kind: what the reply is for. The library uses ``"judge"``, ``"native"`` and + ``"verify"``; a detector of your own passes its own name. :returns: A SHA-256 hex digest. - :raises InvalidInputError: ``kind`` is not one of the three values (``invalid_cache_kind``). + :raises InvalidInputError: ``kind`` is blank, is not a string or contains ``=`` + (``invalid_cache_kind``). """ - if kind not in _KINDS: + # "=" is reserved for the model_version part, so a kind can never read as a version. + if not isinstance(kind, str) or not kind.strip() or "=" in kind: raise InvalidInputError( - f"kind must be one of {', '.join(_KINDS)}.", + "kind must be a non-blank string without '='.", code="invalid_cache_kind", param="kind", ) diff --git a/lettucedetect/detectors/taxonomy_head.py b/lettucedetect/detectors/taxonomy_head.py index 6f34f25..e9ffbbc 100644 --- a/lettucedetect/detectors/taxonomy_head.py +++ b/lettucedetect/detectors/taxonomy_head.py @@ -80,7 +80,7 @@ class TaxonomyTyper: max_length=1024, model_id=head_id, ) - detector = EncoderDetector(model, model_tokenizer, typer, model_id=model_id) + detector = EncoderDetector(model, model_tokenizer, typer=typer, model_id=model_id) result = detector.detect(request) # every span has category and subcategory The typer reads its device from ``encoder.device``, so move the encoder before building it. diff --git a/lettucedetect/detectors/transformer.py b/lettucedetect/detectors/transformer.py index 76c554f..3963066 100644 --- a/lettucedetect/detectors/transformer.py +++ b/lettucedetect/detectors/transformer.py @@ -82,7 +82,7 @@ def __init__( super().__init__( model, tokenizer, - typer, + typer=typer, config=EncoderConfig(max_length=max_length, batch_size=batch_size, lang=lang), model_id=model_path, model_version=version, diff --git a/lettucedetect/detectors/types.py b/lettucedetect/detectors/types.py index 020456a..37ab225 100644 --- a/lettucedetect/detectors/types.py +++ b/lettucedetect/detectors/types.py @@ -112,6 +112,12 @@ class TokenScore(BaseModel): score: float = Field(ge=0.0, le=1.0) flagged: bool + @model_validator(mode="after") + def _validate_offsets_in_order(self) -> TokenScore: + if self.end <= self.start: + raise ValueError("end must be greater than start") + return self + class Usage(BaseModel): """What one model or service did during a call. diff --git a/tests/test_base_detector_pytest.py b/tests/test_base_detector_pytest.py index 98f50b4..dad343e 100644 --- a/tests/test_base_detector_pytest.py +++ b/tests/test_base_detector_pytest.py @@ -200,3 +200,30 @@ def test_default_hook_raises_not_implemented(): """The base class itself, which has no hook and no legacy predict, raises NotImplementedError.""" with pytest.raises(NotImplementedError): BaseDetector().detect(REQUEST) + + +@pytest.mark.parametrize("request_", [{"sources": [], "answer": "a"}, "abc", None]) +def test_a_request_that_is_not_a_request_model_raises_a_typed_error(request_): + # A dict, a string and None raise InvalidInputError before the detector runs. + detector = FakeDetector() + with pytest.raises(InvalidInputError) as info: + detector.detect(request_) + assert (info.value.code, info.value.param) == ("invalid_request", "request") + assert detector.calls == [] + + +class _DetectOnly(BaseDetector): + """Detector with ``_detect`` only and no token scores.""" + + def _detect(self, request, *, include_tokens, include_detail): + return _result().model_copy(update={"tokens": None}) + + +def test_predict_on_a_detector_without_tokens_names_the_spans_format(): + # predict defaults to "tokens"; the error names the argument the caller can change. + detector = _DetectOnly() + with pytest.raises(InvalidInputError) as info: + detector.predict([], "abcdefghij") + assert (info.value.code, info.value.param) == ("tokens_not_supported", "output_format") + assert 'output_format="spans"' in str(info.value) + assert len(detector.predict([], "abcdefghij", output_format="spans")) == 3 diff --git a/tests/test_encoder_detector_pytest.py b/tests/test_encoder_detector_pytest.py index 8e99272..ce22aea 100644 --- a/tests/test_encoder_detector_pytest.py +++ b/tests/test_encoder_detector_pytest.py @@ -84,6 +84,18 @@ def test_construction_is_offline_and_leaves_cwd_empty( boom.assert_not_called() +def test_everything_after_the_tokenizer_is_keyword_only(local_wordpiece_tokenizer): + # A config passed third must not be taken as the typer. + with pytest.raises(TypeError): + EncoderDetector(_stub_model(), local_wordpiece_tokenizer, EncoderConfig(max_length=512)) + + +def test_detectors_on_one_tokenizer_share_the_scoring_lock(local_wordpiece_tokenizer): + # A fast tokenizer fails with "Already borrowed" when two threads use it at once. + first, second = _detector(local_wordpiece_tokenizer), _detector(local_wordpiece_tokenizer) + assert first._get_scoring_lock() is second._get_scoring_lock() + + def test_config_defaults(): config = EncoderConfig() assert (config.max_length, config.batch_size, config.lang) == (4096, 16, "en") @@ -161,7 +173,8 @@ def _as_old_tokens(detection) -> list[dict]: def _round_tokens(tokens: list[dict]) -> list[dict]: - return [{**t, "prob": round(t["prob"], 6)} for t in tokens] + """Round the golden ``predict`` tokens and leave out [SEP], which ``detect`` does not return.""" + return [{**t, "prob": round(t["prob"], 6)} for t in tokens if t["token"] != "[SEP]"] # noqa: S105 def test_tokens_equal_golden_output(local_wordpiece_tokenizer): @@ -191,17 +204,11 @@ def test_token_offsets_lie_in_the_answer_and_spans_cover_flagged_tokens(local_wo result = det.detect(request, include_tokens=True) previous_end = 0 for t in result.tokens: - assert 0 <= t.start <= t.end <= len(request.answer) - assert t.start >= previous_end or t.start == t.end - if t.start != t.end: - assert request.answer[t.start : t.end] == t.token - previous_end = t.end - assert result.tokens[-1].token == "[SEP]" # noqa: S105 - assert (result.tokens[-1].start, result.tokens[-1].end) == ( - len(request.answer), - len(request.answer), - ) - flagged = {(t.start, t.end) for t in result.tokens if t.flagged and t.start != t.end} + # Every token is a part of the answer: no zero-width special token such as [SEP]. + assert previous_end <= t.start < t.end <= len(request.answer) + assert request.answer[t.start : t.end] == t.token + previous_end = t.end + flagged = {(t.start, t.end) for t in result.tokens if t.flagged} for span in result.spans: assert any(s >= span.start and e <= span.end for s, e in flagged) @@ -536,7 +543,7 @@ def _typed(tokenizer, typer=None, **kwargs) -> EncoderDetector: return EncoderDetector( _stub_model(), tokenizer, - typer if typer is not None else _Typer(), + typer=typer if typer is not None else _Typer(), config=EncoderConfig(max_length=512), model_id="stub-encoder", **kwargs, @@ -663,7 +670,7 @@ def make_detector(self, on_call=None): return EncoderDetector( _stub_model(on_call=on_call), self.tokenizer, - _Typer(), + typer=_Typer(), config=EncoderConfig(max_length=512), model_id="stub-encoder", ) diff --git a/tests/test_response_cache_pytest.py b/tests/test_response_cache_pytest.py index ac4ac80..048f393 100644 --- a/tests/test_response_cache_pytest.py +++ b/tests/test_response_cache_pytest.py @@ -66,10 +66,16 @@ def test_a_version_cannot_forge_a_kind(self): "p", "m", None, 0.0, "native" ) - def test_unknown_kind_raises_a_typed_error(self): - """Unknown kind raises a typed error.""" + def test_a_kind_of_your_own_gets_its_own_key(self): + """A detector outside the library passes its own kind and gets a key of its own.""" + own = make_cache_key("p", "m", None, 0.0, "fact_check") + assert own not in {make_cache_key("p", "m", None, 0.0, k) for k in ("judge", "native")} + + @pytest.mark.parametrize("kind", ["", " ", "model_version=v1", None, 3]) + def test_invalid_kind_raises_a_typed_error(self, kind): + """A blank kind, a kind with ``=`` (it could read as a version) and a non-string raise.""" with pytest.raises(InvalidInputError) as info: - make_cache_key("p", "m", None, 0.0, "other") # type: ignore[arg-type] + make_cache_key("p", "m", None, 0.0, kind) assert info.value.code == "invalid_cache_kind" assert info.value.param == "kind" diff --git a/tests/test_transformer_deprecated_pytest.py b/tests/test_transformer_deprecated_pytest.py index 6cf97d1..dfe0b4d 100644 --- a/tests/test_transformer_deprecated_pytest.py +++ b/tests/test_transformer_deprecated_pytest.py @@ -14,7 +14,7 @@ from lettucedetect.detectors import _deprecation as dep from lettucedetect.detectors._deprecation import LettuceDetectDeprecationWarning -from lettucedetect.detectors.encoder import EncoderConfig, EncoderDetector +from lettucedetect.detectors.encoder import _TOKENIZER_LOCKS, EncoderConfig, EncoderDetector from lettucedetect.detectors.factory import make_detector from lettucedetect.detectors.transformer import TransformerDetector from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput @@ -215,6 +215,7 @@ def forward(input_ids=None, attention_mask=None, **kwargs): ] state["max"] = 0 det.__dict__.pop("_scoring_lock", None) # race the first creation again + _TOKENIZER_LOCKS.pop(id(det.tokenizer), None) created, real = [], threading.RLock diff --git a/tests/test_types_pytest.py b/tests/test_types_pytest.py index 1a95b5a..6914633 100644 --- a/tests/test_types_pytest.py +++ b/tests/test_types_pytest.py @@ -139,3 +139,10 @@ def test_detailed_result_accepts_json_string_keys(): restored = DetailedResult.model_validate_json(_detail().model_dump_json()) assert restored.fact_check_results == {0: False} assert restored.triplets.context == [["Barcelona", "north", "coast", "Madrid"]] + + +@pytest.mark.parametrize(("start", "end"), [(3, 3), (5, 2)]) +def test_token_score_rejects_offsets_that_are_empty_or_reversed(start, end): + # A token is a part of the answer, so its end lies after its start, as for a Span. + with pytest.raises(ValidationError): + TokenScore(token="x", start=start, end=end, score=0.5, flagged=False) # noqa: S106 From 7c719085f65558820ae416501720ef5627b98d5e Mon Sep 17 00:00:00 2001 From: Suleyman Furkan Atas Date: Wed, 18 Nov 2026 08:58:55 +0100 Subject: [PATCH 30/60] feat: add VelaDetector and VelaConfig for in-process Vela 2.0 models (#118) (#193) * feat: add VelaDetector and VelaConfig for in-process Vela 2.0 models (#118) * fix: join the question into Vela's source and keep span labels (#118) --- docs/code-hallucination/results_vela.md | 80 ++++ lettucedetect/detectors/__init__.py | 3 + lettucedetect/detectors/vela.py | 482 ++++++++++++++++++++ mkdocs.yml | 1 + pyproject.toml | 9 +- scripts/evaluate_span_model.py | 45 +- tests/test_vela_detector_pytest.py | 528 ++++++++++++++++++++++ tests/test_vela_from_pretrained_pytest.py | 185 ++++++++ 8 files changed, 1327 insertions(+), 6 deletions(-) create mode 100644 docs/code-hallucination/results_vela.md create mode 100644 lettucedetect/detectors/vela.py create mode 100644 tests/test_vela_detector_pytest.py create mode 100644 tests/test_vela_from_pretrained_pytest.py diff --git a/docs/code-hallucination/results_vela.md b/docs/code-hallucination/results_vela.md new file mode 100644 index 0000000..4fea737 --- /dev/null +++ b/docs/code-hallucination/results_vela.md @@ -0,0 +1,80 @@ +# Vela 2.0 0.3B through `VelaDetector` + +[Vela 2.0](https://huggingface.co/collections/vllm-sr/vela-20) reports hallucination example-F1 on +the same 10,698-example test set as our v2 models +([EVALUATION.md](https://huggingface.co/vllm-sr/Vela-2.0-0.3B/blob/main/EVALUATION.md)). +This note reproduces the 0.3B number with LettuceDetect's own evaluator, so the +results can be compared directly with the +[mmBERT-base](model_card_v2_mmbert_base.md) and [Qwen-2b](model_card_v2_qwen.md) model cards. + +## Setup + +- **Model:** `vllm-sr/Vela-2.0-0.3B`, loaded with `VelaDetector.from_pretrained`, which runs the + inference code from the model repository as is. +- **Question:** Vela's documented hallucination span question (`VelaConfig()` defaults) at Vela's + calibrated threshold. +- **Data:** the test splits of `KRLabsOrg/lettucedetect-code-hallucination` and + `KRLabsOrg/lettucedetect-prose-hallucination`, 10,698 rows. +- **Input:** each row goes in as `SourcesInput`, with its `question` and its `context` as the one + source. `VelaDetector` joins them into one context for Vela, + `User request: \n\n`, the format Vela was trained on. RAGTruth rows have no + question or context, so their `prompt` is the source. +- **Metrics:** `scripts/span_eval_metrics.py`, the same char-overlap span-F1, example-F1 and IoU + as the v2 model cards. Vela's headline number is **example-F1**. + +```bash +pip install -e ".[vela]" datasets +python scripts/evaluate_span_model.py \ + --method vela \ + --model-path vllm-sr/Vela-2.0-0.3B \ + --revision \ + --dataset KRLabsOrg/lettucedetect-code-hallucination \ + --dataset KRLabsOrg/lettucedetect-prose-hallucination \ + --split test +``` + +## Results (test split, 10,698 samples) + +| | example-F1 | +|---|--:| +| Vela 2.0 0.3B, reported by Vela | 0.848 | +| Vela 2.0 0.3B, this evaluation | 0.847 | + +| dataset | n | span_F1 | span_P | span_R | ex_F1 | IoU | +|---|--:|--:|--:|--:|--:|--:| +| **ALL** | 10698 | **0.629** | 0.587 | 0.677 | 0.847 | 0.592 | +| acl | 440 | 0.467 | 0.550 | 0.405 | 0.744 | 0.458 | +| code-agent | 2015 | 0.473 | 0.495 | 0.452 | 0.750 | 0.463 | +| readme | 641 | 0.649 | 0.651 | 0.646 | 0.823 | 0.636 | +| tool-output | 617 | 0.513 | 0.594 | 0.452 | 0.744 | 0.540 | +| wikipedia | 1388 | 0.650 | 0.628 | 0.674 | 0.880 | 0.684 | +| psiloqa | 2897 | 0.725 | 0.621 | 0.869 | 0.959 | 0.627 | +| ragtruth | 2700 | 0.491 | 0.532 | 0.455 | 0.707 | 0.628 | + +The target is the reported example-F1 within ±0.01; the result is 0.0006 below it. The RAGTruth +example-F1 (0.707) also matches Vela's reported RAGTruth F1 for the 0.3B (0.706). + +## How the question is sent + +Vela's state can hold the question as a separate `request` part or inside the context. The same +test set, every row sent as `SourcesInput`, with four ways of building the state: + +| Question and sources sent as | ALL ex_F1 | ALL span_F1 | rows failed (`input_too_long`) | +|---|--:|--:|--:| +| **one source, `User request: \n\n`** (used) | **0.847** | **0.629** | 0 | +| one source, `\n\n` | 0.844 | 0.620 | 0 | +| one source, the encoder's prompt (`PromptUtils.format_context`) | 0.840 | 0.588 | 0 | +| a separate `request` part and the sources as `source` | 0.830 | 0.604 | 586 | + +With a separate `request`, Vela fits an input into its token window by cutting the request, the +first part it does not score, so long sources could not be cut and 586 rows failed. With one +source, a long input is cut instead. + +## Notes + +- The inference code comes from the model repository and is used directly. A new commit there can + change both the code and the scores, so a rerun may not match these numbers exactly. +- Inputs over the model's 8,192-token budget have their context cut by Vela. `VelaDetector` reports + those rows with the `input_truncated` warning. The reply cannot tell a cut input from one that + fits exactly, so an exact fit is reported too. + \ No newline at end of file diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index 64042b5..11bb66c 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -33,6 +33,7 @@ TokenScore, Usage, ) +from lettucedetect.detectors.vela import VelaConfig, VelaDetector __all__ = [ "BaseDetector", @@ -61,6 +62,8 @@ "TransformerDetector", "UpstreamError", "Usage", + "VelaConfig", + "VelaDetector", "_make_detector", "make_cache_key", ] diff --git a/lettucedetect/detectors/vela.py b/lettucedetect/detectors/vela.py new file mode 100644 index 0000000..e035355 --- /dev/null +++ b/lettucedetect/detectors/vela.py @@ -0,0 +1,482 @@ +"""Detector backed by a Vela 2.0 model that answers the SystemOne hallucination span question.""" + +from __future__ import annotations + +import importlib.util +import logging +import numbers +import threading +import time +from pathlib import Path +from typing import Any + +import torch +import transformers +from packaging.version import Version +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator +from transformers import AutoModel + +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.encoder import ( + _finish_load, + _log_model_loaded, + _model_load_error, + _resolved_commit, +) +from lettucedetect.detectors.errors import ( + ConfigurationError, + InvalidInputError, + LettuceDetectError, + UpstreamError, +) +from lettucedetect.detectors.types import ( + DetectedSpan, + Detection, + DetectRequest, + ResultWarning, + SourcesInput, + Usage, +) + +logger = logging.getLogger(__name__) + +__all__ = ["VelaConfig", "VelaDetector"] + +# Id of the span question in the SystemOne request and reply. +_QUESTION_ID = "halu" + +# The hallucination question as Vela documents it (``halu_schema`` in the model's calibration.json). +_DEFAULT_INSTRUCTIONS = "Which spans of the answer are not supported by the context?" +_DEFAULT_CRITERIA = {"unsupported": "a claim not supported by the context"} + +# How Vela's hallucination question was trained to see a question: in front of the context, as +# "User request: \n\n" (``detect_hallucination`` in the model's code). +_REQUEST_PREFIX = "User request: " + +# Oldest transformers any Vela 2.0 model card suggests; the decoders ask for more (see the extra). +_MIN_TRANSFORMERS = "4.57" +_RUNTIME_PACKAGES = ("safetensors", "tokenizers") +_EXTRA_HINT = "pip install 'lettucedetect[vela]'" + + +def _missing_dependency(what: str) -> ConfigurationError: + """Build the error for a missing or too old runtime package; the caller chains the cause.""" + return ConfigurationError( + f"Vela needs {what}. Install the runtime with: {_EXTRA_HINT}", + code="missing_dependency", + ) + + +def _transformers_version() -> str: + """Return the installed transformers version.""" + return transformers.__version__ + + +def _check_runtime() -> None: + """Raise :class:`ConfigurationError` if a package the Vela remote code needs is missing. + + :raises ConfigurationError: (``missing_dependency``) transformers is too old or a package is + not installed. + """ + if Version(_transformers_version()) < Version(_MIN_TRANSFORMERS): + raise _missing_dependency(f"transformers>={_MIN_TRANSFORMERS}") + for package in _RUNTIME_PACKAGES: + if importlib.util.find_spec(package) is None: + raise _missing_dependency(f"the {package} package") + + +def _invalid_output(message: str) -> UpstreamError: + """Build the error for a reply that does not have the SystemOne span shape.""" + return UpstreamError( + f"Vela returned an unreadable reply: {message}. Check that the model speaks SystemOne.", + code="invalid_model_output", + service="vela", + ) + + +def _is_int(value: object) -> bool: + """Whether ``value`` is an integer (NumPy integers included) and not a bool.""" + return isinstance(value, numbers.Integral) and not isinstance(value, bool) + + +def _is_number(value: object) -> bool: + """Whether ``value`` is a real number (NumPy floats included) and not a bool.""" + return isinstance(value, numbers.Real) and not isinstance(value, bool) + + +class VelaConfig(BaseModel): + """Options of a :class:`VelaDetector`. + + The defaults are the hallucination question Vela was trained with; changing the wording can + change the scores. An invalid option raises :class:`ConfigurationError` with the code + ``invalid_config`` and ``param`` set to the option. + + :param instructions: the span question asked about the answer. + :param criteria: span labels and their descriptions, at least one. With more than one, each + span's ``category`` is the label it matched; with one, ``category`` is ``None``. + :param threshold: probability above which Vela returns a span, in ``[0, 1]``. ``None`` uses + the model's calibrated threshold. ``min_score`` of ``detect`` filters on top of it. + :param max_length: the model's input budget in tokens. It does not change the model; a reply + that used the whole budget is reported with the ``input_truncated`` warning. The reply + cannot tell a cut input from one that fits exactly or a long answer scored in windows, + so those are reported too. + """ + + model_config = ConfigDict(frozen=True, extra="forbid", hide_input_in_errors=True) + + instructions: str = Field(default=_DEFAULT_INSTRUCTIONS, min_length=1) + criteria: dict[str, str] = Field(default_factory=lambda: dict(_DEFAULT_CRITERIA), min_length=1) + threshold: float | None = Field(default=None, ge=0.0, le=1.0) + max_length: int = Field(default=8192, gt=0) + + @model_validator(mode="wrap") + @classmethod + def _raise_configuration_error(cls, data: Any, handler: Any) -> VelaConfig: # noqa: ANN401 + try: + config = handler(data) + except ValidationError as exc: + first = exc.errors(include_input=False, include_url=False)[0] + param = str(first["loc"][0]) if first["loc"] else None + raise ConfigurationError( + f"Invalid VelaConfig option {param!r}; see the VelaConfig docstring.", + code="invalid_config", + param=param, + ) from exc + if not config.instructions.strip(): + raise ConfigurationError( + "VelaConfig.instructions must not be blank.", + code="invalid_config", + param="instructions", + ) + if any(not key.strip() or not value.strip() for key, value in config.criteria.items()): + raise ConfigurationError( + "VelaConfig.criteria must not have blank labels or descriptions.", + code="invalid_config", + param="criteria", + ) + return config + + +class VelaDetector(BaseDetector): + r"""Detect hallucinations with a Vela 2.0 model the caller already holds. + + Vela answers typed SystemOne questions about a request, a context and an answer. This detector + asks one span question, "which spans of the answer are not supported by the context?", and + returns Vela's spans with their probability as score. Any model with a + ``system_one(state=..., questions=...)`` method that speaks SystemOne works. + + The state sent to the model has two SystemOne keys, ``source`` and ``answer``: + + * ``SourcesInput``: ``"User request: \n\n"``, the non-blank sources joined + with blank lines. Either the question or the sources may be left out, but not both. + * ``PromptInput``: the prompt. A LettuceDetect prompt holds the request and the context. + + The question goes into ``source`` because that is how Vela's hallucination question was + trained. Measured on the 10,698-example test set with every row sent as ``SourcesInput``, the + 0.3B scores an example-F1 of 0.847 with this join, 0.844 with the question and the sources + joined by a blank line, and 0.840 with the encoder's prompt (``PromptUtils.format_context``). + With the question as a separate ``request`` part it scored 0.830, and 586 rows failed: Vela + fits an input into its token window by cutting the first part it does not score, which was + then the request, so long sources could not be cut. With one ``source`` a long input is cut + and reported with the ``input_truncated`` warning. That warning also marks an input that fits + exactly or a long answer scored in windows, since the reply cannot tell them apart. + + With more than one criterion in the config, each span's ``category`` is the label Vela matched. + + Construction downloads nothing, reads no environment variable and writes no file. Calls run + under one private lock, so concurrent calls on one instance run one at a time. + + Vela ships its code in the model repository, so loading needs ``trust_remote_code=True``. + :meth:`from_pretrained` sets it; pin ``revision`` to a commit you have reviewed. + + Example:: + + detector = VelaDetector.from_pretrained("vllm-sr/Vela-2.0-0.3B", revision="") + result = detector.detect( + SourcesInput( + question="When does it ship?", + sources=[Chunk(id="doc-1", text="Ships Friday.")], + answer="Ships Monday.", + ), + min_score=0.5, + ) + + :param model: a loaded Vela model, or any object with a system_one(state=..., questions=...) method.. + :param config: options, ``VelaConfig()`` when ``None``. + :param model_id: id reported in ``usage``. + :param model_version: version reported in ``usage``. + """ + + supports_tokens = False + supports_detail = False + model_id: str | None = None + model_version: str | None = None + + def __init__( + self, + model: Any, # noqa: ANN401 + *, + config: VelaConfig | None = None, + model_id: str | None = None, + model_version: str | None = None, + ) -> None: + """Build the detector from a loaded model.""" + self.config = config if config is not None else VelaConfig() + self.model = model + self.model_id = model_id + self.model_version = model_version + # Scoring lock is created here, not lazily as in EncoderDetector: from_pretrained + # calls cls(), so __init__ always runs and no first-call race exists. A plain Lock is + # enough because only _detect takes it, once per call. + self._scoring_lock = threading.Lock() + logger.debug( + "vela detector built: model_id=%s criteria=%d threshold=%s max_length=%d", + model_id, + len(self.config.criteria), + self.config.threshold, + self.config.max_length, + ) + + @classmethod + def from_pretrained( + cls, + model_id: str, + *, + revision: str | None = None, + device: torch.device | str | None = None, + config: VelaConfig | None = None, + model_version: str | None = None, + **loader_kwargs: Any, # noqa: ANN401 + ) -> VelaDetector: + """Load the Vela model for ``model_id`` and build the detector. + + This is the one place where a model name becomes a model. It may download, unless the + caller set ``HF_HUB_OFFLINE`` (this method neither reads nor sets it). The model's own + code runs with ``trust_remote_code=True``, so pin ``revision`` to a reviewed commit. + + :param model_id: Hugging Face id or local directory. + :param revision: branch, tag or commit of the model repository; pin a commit. + :param device: device for the model; CUDA when available, else CPU, when ``None``. + :param config: options, ``VelaConfig()`` when ``None``. + :param model_version: version reported in ``usage`` for a local path. For a hub id the + resolved commit is used and this is only the fallback. + :param loader_kwargs: passed to ``AutoModel.from_pretrained``, for example ``cache_dir``. + :raises ConfigurationError: (``missing_dependency``) the ``vela`` extra is not installed; + (``model_load_failed``) a local model could not be loaded. + :raises UpstreamError: (``model_load_failed``) a hub model could not be loaded. + """ + _check_runtime() + is_local = Path(model_id).is_dir() + kwargs = {**loader_kwargs, "revision": revision, "trust_remote_code": True} + started = time.perf_counter() + try: + model = AutoModel.from_pretrained(model_id, **kwargs) + except ImportError as exc: + raise _missing_dependency("a package its model code imports") from exc + except OSError as exc: + raise _model_load_error(model_id, is_local) from exc + device, _ = _finish_load(model, device, None, None, None) + # Vela builds its inference engine on first use; build it now so a call does not. + getattr(model, "vela2_engine", None) + version = model_version + if not is_local: + version = _resolved_commit(model_id, kwargs) or model_version + detector = cls(model, config=config, model_id=model_id, model_version=version) + _log_model_loaded(model_id, version, device, started, module_logger=logger) + return detector + + # ------------------------------------------------------------------ + # Detection + # ------------------------------------------------------------------ + + def _detect( + self, request: DetectRequest, *, include_tokens: bool, include_detail: bool + ) -> Detection: + """Ask Vela the span question and return its spans, usage and warnings. + + :param request: the sources (or prompt) and the answer to check. + :param include_tokens: unused, there are no token scores. + :param include_detail: unused, there is no detail. + :returns: the detection result. + :raises InvalidInputError: (``empty_context``) the request has no context to check against; + (``input_too_long``) Vela could not cut the input into its token window. + :raises UpstreamError: (``invalid_model_output``) Vela rejected the request, or the reply + does not have the span shape. + """ + answer = request.answer + units: dict[str, int] = {"answer_chars": len(answer)} + if isinstance(request, SourcesInput): + units["sources"] = len(request.sources) + units["source_chars"] = sum(len(chunk.text) for chunk in request.sources) + else: + units["source_chars"] = len(request.prompt) + state = self._state(request) + if not answer.strip(): + # Vela rejects an empty answer part, and there is nothing to flag in it. + logger.debug("detect skipped: the answer is blank") + return Detection(usage=[self._usage(units)]) + + requested = time.perf_counter() + with self._scoring_lock: + started = time.perf_counter() + logger.debug( + "detect started: kind=%s model_id=%s lock_wait_ms=%.1f", + request.kind, + self.model_id, + (started - requested) * 1000, + ) + try: + reply = self.model.system_one(state=state, questions=self._questions()) + except LettuceDetectError: + # A model that already raises typed errors (InvalidInputError is a ValueError) + # passes them through as they are. + raise + except ValueError as exc: + # Vela raises its SystemOneError (a ValueError) for a request it rejects. Its + # message may quote the input, so it is chained but never repeated. + if getattr(exc, "type", None) == "too_long": + # With one source part Vela can cut the input, so this is left for questions + # that alone do not fit the window. + raise InvalidInputError( + "The input does not fit the model's token window; pass a shorter input.", + code="input_too_long", + param="request", + ) from exc + raise UpstreamError( + "Vela rejected the request. Check that the model speaks SystemOne.", + code="invalid_model_output", + service="vela", + ) from exc + scoring_ms = (time.perf_counter() - started) * 1000 + + if not isinstance(reply, dict): + raise _invalid_output("the reply is not an object") + spans = self._parse_spans(reply, answer) + input_tokens = self._input_tokens(reply) + warnings: list[ResultWarning] = [] + if input_tokens is not None: + units["input_tokens"] = input_tokens + # Vela cuts one part of the input until the sequence is exactly max_length tokens, and + # scores a long answer in windows whose tokens add up past it. An input that fits + # exactly is reported too: the reply has no way to tell the two apart. + if input_tokens >= self.config.max_length: + # The reply counts tokens after the cut, so the input's size is logged in chars. + logger.warning( + "input_truncated: the input was cut to max_length=%d tokens " + "(source_chars=%d answer_chars=%d)", + self.config.max_length, + units["source_chars"], + units["answer_chars"], + ) + warnings.append( + ResultWarning( + code="input_truncated", + message=( + "The input reached the model's token budget, so part of it may not " + "have been scored. An input that fits exactly, or a long answer " + "scored in windows, is reported the same way." + ), + ) + ) + logger.debug( + "detect finished: spans=%d input_tokens=%s truncated=%s scoring_ms=%.1f", + len(spans), + input_tokens, + bool(warnings), + scoring_ms, + ) + return Detection(spans=spans, usage=[self._usage(units)], warnings=warnings) + + def _usage(self, units: dict[str, int]) -> Usage: + """Return the usage entry of the Vela model.""" + return Usage(model_id=self.model_id, model_version=self.model_version, units=units) + + @staticmethod + def _state(request: DetectRequest) -> dict[str, str]: + r"""Return the SystemOne state for a request: ``source`` and ``answer``. + + For ``SourcesInput`` the source is ``"User request: \n\n"``. A blank + question or blank sources are left out, since Vela rejects an empty part. + + :raises InvalidInputError: (``empty_context``) there is neither a question nor a source. + """ + if isinstance(request, SourcesInput): + parts = [] + if request.question and request.question.strip(): + parts.append(_REQUEST_PREFIX + request.question) + parts.extend(chunk.text for chunk in request.sources if chunk.text.strip()) + source = "\n\n".join(parts) + else: + source = request.prompt if request.prompt.strip() else "" + if not source: + raise InvalidInputError( + "The request has no context to check the answer against; pass non-empty " + "sources, a question or a prompt.", + code="empty_context", + param="request", + ) + return {"source": source, "answer": request.answer} + + def _questions(self) -> dict[str, dict[str, Any]]: + """Return the SystemOne questions: the one span question, which targets the answer.""" + question: dict[str, Any] = { + "type": "span", + "instructions": self.config.instructions, + "criteria": dict(self.config.criteria), + } + if self.config.threshold is not None: + question["threshold"] = self.config.threshold + return {_QUESTION_ID: question} + + def _parse_spans(self, reply: dict[str, Any], answer: str) -> list[DetectedSpan]: + """Map Vela's ``{label, start, end, text, probability}`` spans to detected spans. + + The span text is taken from the answer, so it always matches the offsets. With more than + one criterion the label goes into ``category``; with one it says nothing and is dropped. + + :raises UpstreamError: (``invalid_model_output``) a span is missing or malformed. + """ + labelled = len(self.config.criteria) > 1 + spans_by_question = reply.get("spans") + items = spans_by_question.get(_QUESTION_ID) if isinstance(spans_by_question, dict) else None + if not isinstance(items, list): + raise _invalid_output("it has no span list for the hallucination question") + spans = [] + for index, item in enumerate(items): + if not isinstance(item, dict): + raise _invalid_output(f"spans[{index}] is not an object") + start, end, probability = item.get("start"), item.get("end"), item.get("probability") + if not (_is_int(start) and _is_int(end) and 0 <= start < end <= len(answer)): + raise _invalid_output(f"spans[{index}] has offsets outside the answer") + if not (_is_number(probability) and 0.0 <= probability <= 1.0): + raise _invalid_output(f"spans[{index}] has a probability outside [0, 1]") + category = None + if labelled: + category = item.get("label") + if not isinstance(category, str) or category not in self.config.criteria: + raise _invalid_output(f"spans[{index}] has a label that is not a criterion") + start, end = int(start), int(end) + spans.append( + DetectedSpan( + start=start, + end=end, + text=answer[start:end], + score=float(probability), + category=category, + ) + ) + return spans + + @staticmethod + def _input_tokens(reply: dict[str, Any]) -> int | None: + """Return ``usage.input_tokens`` of the reply, ``None`` when the model does not report it. + + :raises UpstreamError: (``invalid_model_output``) the count is not a non-negative integer. + """ + usage = reply.get("usage") + value = usage.get("input_tokens") if isinstance(usage, dict) else None + if value is None: + return None + if not _is_int(value) or value < 0: + raise _invalid_output("usage.input_tokens is not a non-negative integer") + return int(value) diff --git a/mkdocs.yml b/mkdocs.yml index cd88d07..92f7f13 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -99,6 +99,7 @@ nav: - Generative (Qwen-2b): code-hallucination/model_card_v2_qwen.md - Encoder (mmBERT-base): code-hallucination/model_card_v2_mmbert_base.md - Taxonomy Head: code-hallucination/model_card_v2_taxonomy_head.md + - Vela 2.0 0.3B Evaluation: code-hallucination/results_vela.md - Research: - TinyLettuce: TINYLETTUCE.md - Multilingual (EuroBERT): EUROBERT.md diff --git a/pyproject.toml b/pyproject.toml index 470fe60..da00cce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dependencies = [ "scikit-learn>=1.6.1", "numpy>=2.2.2", "openai>=1.66.3", + "packaging>=20.0", "pydantic>=2.0", "rag-fact-checker", "typing_extensions>=4.5.0", @@ -52,6 +53,11 @@ api = [ bedrock = [ "boto3>=1.34", ] +vela = [ + "transformers>=5.17", + "safetensors", + "tokenizers", +] docs = [ "mkdocs-material>=9.0", "mkdocstrings[python]>=0.24", @@ -70,7 +76,8 @@ lettucedetect = ["prompts/*.txt", "prompts/*.json"] testpaths = ["tests"] python_files = "test_*_pytest.py" asyncio_mode = "auto" -addopts = "-v --tb=short --strict-markers" +addopts = '-v --tb=short --strict-markers -m "not model_download"' +markers = ["model_download: downloads a real model; run with -m model_download"] filterwarnings = ["error::lettucedetect.detectors._deprecation.LettuceDetectDeprecationWarning"] [tool.ruff] diff --git a/scripts/evaluate_span_model.py b/scripts/evaluate_span_model.py index 5a5d2dd..cdceaee 100755 --- a/scripts/evaluate_span_model.py +++ b/scripts/evaluate_span_model.py @@ -10,6 +10,15 @@ --dataset KRLabsOrg/lettucedetect-code-hallucination \ --dataset KRLabsOrg/lettucedetect-prose-hallucination \ --split test [--by language] [--limit N] + + # A Vela 2.0 model through VelaDetector; pin the revision of its remote code. Each row goes in + # as a SourcesInput: its question and context, or its prompt as the source when it has + # neither (RAGTruth). + python scripts/evaluate_span_model.py \ + --method vela --model-path vllm-sr/Vela-2.0-0.3B --revision \ + --dataset KRLabsOrg/lettucedetect-code-hallucination \ + --dataset KRLabsOrg/lettucedetect-prose-hallucination \ + --split test """ from __future__ import annotations @@ -26,6 +35,7 @@ from span_eval_metrics import print_metrics_table # noqa: E402 from lettucedetect.datasets.hallucination_dataset import HallucinationSample # noqa: E402 +from lettucedetect.detectors.vela import VelaDetector # noqa: E402 from lettucedetect.models.inference import HallucinationDetector # noqa: E402 @@ -48,6 +58,8 @@ def load_samples( task_type=r.get("task_type", ""), dataset=r.get("dataset", name), language=r.get("language", "en"), + context=r.get("context"), + question=r.get("question"), ) ) if limit and len(out) >= limit: @@ -59,6 +71,15 @@ def main() -> None: """CLI entry point.""" ap = argparse.ArgumentParser(description="Per-source span-detector evaluation.") ap.add_argument("--model-path", required=True) + ap.add_argument( + "--method", + choices=["transformer", "vela"], + default="transformer", + help="transformer: a LettuceDetect encoder; vela: a Vela 2.0 model via VelaDetector.", + ) + ap.add_argument( + "--revision", default=None, help="Model revision; pin a commit for --method vela." + ) ap.add_argument("--dataset", action="append", default=[], required=True) ap.add_argument("--split", default="test") ap.add_argument("--by", choices=["dataset", "language"], default="dataset") @@ -69,10 +90,15 @@ def main() -> None: ap.add_argument("--trust-remote-code", action="store_true") args = ap.parse_args() - kw = {"max_length": args.max_length, "trust_remote_code": args.trust_remote_code} - if args.device: - kw["device"] = args.device - detector = HallucinationDetector(method="transformer", model_path=args.model_path, **kw) + if args.method == "vela": + detector = VelaDetector.from_pretrained( + args.model_path, revision=args.revision, device=args.device + ) + else: + kw = {"max_length": args.max_length, "trust_remote_code": args.trust_remote_code} + if args.device: + kw["device"] = args.device + detector = HallucinationDetector(method="transformer", model_path=args.model_path, **kw) samples = load_samples(args.dataset, args.split, args.limit, args.only) # Predict each sample ONCE; metrics are computed from the cached spans. @@ -80,7 +106,16 @@ def main() -> None: rows = [] for s in tqdm(samples, desc="predict"): - pred = detector.predict_prompt(s.prompt, s.answer, output_format="spans") + if args.method == "vela": + # SourcesInput, the path a service calls. A row without question and context + # (RAGTruth) has only its prompt, which then is the source. + if s.context or s.question: + sources = [s.context] if s.context else [] + else: + sources = [s.prompt] + pred = detector.predict(sources, s.answer, s.question, output_format="spans") + else: + pred = detector.predict_prompt(s.prompt, s.answer, output_format="spans") rows.append((getattr(s, args.by), s.labels, pred)) print_metrics_table(rows) diff --git a/tests/test_vela_detector_pytest.py b/tests/test_vela_detector_pytest.py new file mode 100644 index 0000000..1ba3ba3 --- /dev/null +++ b/tests/test_vela_detector_pytest.py @@ -0,0 +1,528 @@ +"""Tests for ``VelaDetector`` and ``VelaConfig``: offline, with a fake SystemOne model.""" + +from __future__ import annotations + +import asyncio +import os +import threading +import time +from collections.abc import Callable +from typing import Any + +import numpy as np +import pytest +from pydantic import ValidationError + +from lettucedetect.detectors import VelaConfig, VelaDetector +from lettucedetect.detectors.errors import ConfigurationError, InvalidInputError, UpstreamError +from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput +from tests.detector_contract import DetectorContract + +ANSWER = "The capital of France is Berlin, and about 3 million people live there." +SOURCES = SourcesInput( + sources=[ + Chunk(id="s1", text="Paris is the capital of France."), + Chunk(id="s2", text="Paris has two million people."), + ], + answer=ANSWER, + question="What is the capital of France?", +) +PROMPT = PromptInput( + prompt="Answer from the context: Paris is the capital of France.", answer=ANSWER +) + +# (word, probability): the fake flags each word found in the answer. +FLAGGED = [("France", 0.3), ("Berlin", 0.9), ("3 million", 0.6)] + + +class FakeVela: + """Stand-in for a Vela model: flags fixed words of the answer like ``system_one`` does.""" + + def __init__( + self, + on_call: Callable[[], None] | None = None, + input_tokens: int | None = 120, + reply: dict[str, Any] | None = None, + ) -> None: + """Keep the hook, the reported token count and an optional fixed reply.""" + self.on_call = on_call + self.input_tokens = input_tokens + self.reply = reply + self.calls: list[tuple[dict, dict]] = [] + self._active = 0 + self._guard = threading.Lock() + self.overlapped = False + + def system_one(self, state: dict, questions: dict) -> dict: + """Answer the span question over ``state["answer"]``.""" + with self._guard: + self._active += 1 + self.overlapped = self.overlapped or self._active > 1 + try: + self.calls.append((state, questions)) + if self.on_call: + self.on_call() + if self.reply is not None: + return self.reply + answer = state["answer"] + spans = [] + for word, probability in FLAGGED: + start = answer.find(word) + if start >= 0: + spans.append( + { + "label": "unsupported", + "start": start, + "end": start + len(word), + "text": word, + "probability": probability, + } + ) + reply: dict[str, Any] = { + "model": "vllm-sr/Vela-2.0-0.3B", + "answers": { + "halu": {"type": "noul", "noul": max([0.0] + [s["probability"] for s in spans])} + }, + "spans": {"halu": spans}, + "thresholds": {"halu": 0.55}, + } + if self.input_tokens is not None: + reply["usage"] = {"input_tokens": self.input_tokens, "output_tokens": 0} + return reply + finally: + with self._guard: + self._active -= 1 + + +def _detector(model: FakeVela | None = None, **config: object) -> VelaDetector: + return VelaDetector( + model or FakeVela(), + config=VelaConfig(**config) if config else None, + model_id="vllm-sr/Vela-2.0-0.3B", + model_version="abc123", + ) + + +class TestVelaDetectorContract(DetectorContract): + """The shared detector contract holds for ``VelaDetector``.""" + + sources_request = SOURCES + prompt_request = PROMPT + + def make_detector(self, on_call=None): # noqa: D102 + return _detector(FakeVela(on_call=on_call)) + + +# -- config ------------------------------------------------------------------------------- + + +def test_config_defaults_are_velas_documented_question(): + config = VelaConfig() + assert config.instructions == "Which spans of the answer are not supported by the context?" + assert config.criteria == {"unsupported": "a claim not supported by the context"} + assert config.threshold is None + assert config.max_length == 8192 + + +def test_config_is_frozen(): + with pytest.raises(ValidationError): + VelaConfig().threshold = 0.5 + + +@pytest.mark.parametrize( + ("kwargs", "param"), + [ + ({"threshold": 1.5}, "threshold"), + ({"threshold": -0.1}, "threshold"), + ({"max_length": 0}, "max_length"), + ({"instructions": ""}, "instructions"), + ({"instructions": " "}, "instructions"), + ({"criteria": {}}, "criteria"), + ({"criteria": {"unsupported": " "}}, "criteria"), + ({"criteria": {" ": "a claim"}}, "criteria"), + ({"unknown": 1}, "unknown"), + ], +) +def test_config_errors_carry_code_and_param(kwargs, param): + with pytest.raises(ConfigurationError) as exc: + VelaConfig(**kwargs) + assert exc.value.code == "invalid_config" + assert exc.value.param == param + + +# -- request mapping ---------------------------------------------------------------------- + + +def test_sources_with_a_question_are_sent_as_one_source_in_velas_training_format(): + model = FakeVela() + _detector(model).detect(SOURCES) + state, questions = model.calls[0] + assert state == { + "source": ( + "User request: What is the capital of France?\n\n" + "Paris is the capital of France.\n\nParis has two million people." + ), + "answer": ANSWER, + } + assert questions == { + "halu": { + "type": "span", + "instructions": "Which spans of the answer are not supported by the context?", + "criteria": {"unsupported": "a claim not supported by the context"}, + } + } + + +def test_sources_without_a_question_are_sent_as_they_are(): + model = FakeVela() + request = SourcesInput( + sources=[Chunk(id="s1", text="Ships Friday."), Chunk(id="s2", text=" ")], + answer="Ships Monday.", + question=" ", + ) + _detector(model).detect(request) + assert model.calls[0][0] == {"source": "Ships Friday.", "answer": "Ships Monday."} + + +def test_prompt_is_sent_as_the_context(): + model = FakeVela() + _detector(model).detect(PROMPT) + assert model.calls[0][0] == {"source": PROMPT.prompt, "answer": ANSWER} + + +def test_threshold_and_custom_question_are_passed_only_when_set(): + model = FakeVela() + _detector( + model, + instructions="Which claims are made up?", + criteria={"made_up": "invented"}, + threshold=0.4, + ).detect(PROMPT) + assert model.calls[0][1] == { + "halu": { + "type": "span", + "instructions": "Which claims are made up?", + "criteria": {"made_up": "invented"}, + "threshold": 0.4, + } + } + + +# -- span mapping ------------------------------------------------------------------------- + + +def test_spans_map_offsets_probability_and_answer_text(): + spans = _detector().detect(SOURCES).spans + assert [(s.start, s.end, s.text, s.score) for s in spans] == [ + (ANSWER.index("France"), ANSWER.index("France") + 6, "France", 0.3), + (ANSWER.index("Berlin"), ANSWER.index("Berlin") + 6, "Berlin", 0.9), + (ANSWER.index("3 million"), ANSWER.index("3 million") + 9, "3 million", 0.6), + ] + assert all(s.category is None and s.subcategory is None for s in spans) + + +TWO_CRITERIA = {"unsupported": "a claim not in the context", "contradicted": "contradicts it"} + + +def test_with_several_criteria_the_label_is_the_category(): + reply = { + "spans": { + "halu": [ + _span_item(label="contradicted", start=0, end=3), + _span_item(label="unsupported", start=4, end=11), + ] + } + } + spans = _detector(FakeVela(reply=reply), criteria=TWO_CRITERIA).detect(SOURCES).spans + assert [(s.text, s.category) for s in spans] == [ + ("The", "contradicted"), + ("capital", "unsupported"), + ] + + +@pytest.mark.parametrize("label", ["made_up", None, 3, ["unsupported"]]) +def test_with_several_criteria_an_unknown_label_raises_upstream_error(label): + reply = {"spans": {"halu": [_span_item(label=label)]}} + with pytest.raises(UpstreamError) as exc: + _detector(FakeVela(reply=reply), criteria=TWO_CRITERIA).detect(SOURCES) + assert exc.value.code == "invalid_model_output" + + +def test_span_text_comes_from_the_answer_and_numpy_numbers_are_accepted(): + reply = { + "spans": { + "halu": [ + { + "label": "unsupported", + "start": np.int64(25), + "end": np.int64(31), + "text": "something else", + "probability": np.float32(0.75), + } + ] + } + } + span = _detector(FakeVela(reply=reply)).detect(SOURCES).spans[0] + assert (span.start, span.end, span.text) == (25, 31, "Berlin") + assert span.score == pytest.approx(0.75) + assert type(span.start) is int + + +def test_min_score_filters_velas_spans(): + spans = _detector().detect(SOURCES, min_score=0.5).spans + assert [s.text for s in spans] == ["Berlin", "3 million"] + + +def _span_item(**overrides: object) -> dict: + item = {"label": "unsupported", "start": 0, "end": 3, "text": "The", "probability": 0.9} + return {**item, **overrides} + + +@pytest.mark.parametrize( + "reply", + [ + {}, + {"spans": None}, + {"spans": {}}, + {"spans": {"other": []}}, + {"spans": {"halu": "Berlin"}}, + {"spans": {"halu": ["Berlin"]}}, + {"spans": {"halu": [_span_item(start=None)]}}, + {"spans": {"halu": [_span_item(start=True, end=3)]}}, + {"spans": {"halu": [_span_item(start=3, end=3)]}}, + {"spans": {"halu": [_span_item(start=-1)]}}, + {"spans": {"halu": [_span_item(end=len(ANSWER) + 1)]}}, + {"spans": {"halu": [_span_item(start=0.0)]}}, + {"spans": {"halu": [_span_item(probability=1.2)]}}, + {"spans": {"halu": [_span_item(probability=float("nan"))]}}, + {"spans": {"halu": [_span_item(probability="0.9")]}}, + {"spans": {"halu": []}, "usage": {"input_tokens": -1}}, + {"spans": {"halu": []}, "usage": {"input_tokens": "12"}}, + ], +) +def test_malformed_replies_raise_upstream_error(reply): + with pytest.raises(UpstreamError) as exc: + _detector(FakeVela(reply=reply)).detect(SOURCES) + assert exc.value.code == "invalid_model_output" + assert exc.value.service == "vela" + assert ANSWER not in exc.value.message + + +def test_a_reply_that_is_not_an_object_raises_upstream_error(): + with pytest.raises(UpstreamError) as exc: + _detector(FakeVela(reply=["not", "a", "dict"])).detect(SOURCES) # type: ignore[arg-type] + assert exc.value.code == "invalid_model_output" + + +# -- blank input -------------------------------------------------------------------------- + + +@pytest.mark.parametrize("answer", ["", " \n"]) +def test_blank_answer_returns_no_spans_without_calling_the_model(answer): + model = FakeVela() + result = _detector(model).detect(SourcesInput(sources=SOURCES.sources, answer=answer)) + assert model.calls == [] + assert result.spans == [] + assert result.usage[0].units == {"answer_chars": len(answer), "sources": 2, "source_chars": 60} + + +@pytest.mark.parametrize( + "request_", + [ + SourcesInput(sources=[], answer=ANSWER), + SourcesInput(sources=[Chunk(id="s1", text=" ")], answer=ANSWER), + PromptInput(prompt=" \n ", answer=ANSWER), + ], +) +def test_blank_context_raises_invalid_input_error(request_): + model = FakeVela() + with pytest.raises(InvalidInputError) as exc: + _detector(model).detect(request_) + assert (exc.value.code, exc.value.param) == ("empty_context", "request") + assert model.calls == [] + + +@pytest.mark.parametrize("sources", [[], [Chunk(id="s1", text=" ")]]) +def test_question_without_sources_is_sent_as_the_source(sources): + model = FakeVela() + _detector(model).detect(SourcesInput(sources=sources, answer=ANSWER, question="Where?")) + assert model.calls[0][0] == {"source": "User request: Where?", "answer": ANSWER} + + +class _SystemOneError(ValueError): + """Stand-in for Vela's ``SystemOneError``, which carries a ``type``.""" + + def __init__(self, type_: str) -> None: + super().__init__("questions: the questions alone do not fit the 8192-token window") + self.type = type_ + + +def _raise(error: Exception) -> Callable[[], None]: + def hook() -> None: + raise error + + return hook + + +def test_input_that_does_not_fit_raises_invalid_input_error(): + error = _SystemOneError("too_long") + with pytest.raises(InvalidInputError) as exc: + _detector(FakeVela(on_call=_raise(error))).detect(SOURCES) + assert (exc.value.code, exc.value.param) == ("input_too_long", "request") + assert exc.value.__cause__ is error + + +def test_other_model_errors_raise_upstream_error_without_their_message(): + error = _SystemOneError("value_error") + with pytest.raises(UpstreamError) as exc: + _detector(FakeVela(on_call=_raise(error))).detect(SOURCES) + assert (exc.value.code, exc.value.service) == ("invalid_model_output", "vela") + assert exc.value.__cause__ is error + assert str(error) not in exc.value.message + + +def test_typed_errors_from_the_model_pass_through(): + # A model that raises LettuceDetect's own errors, such as an HTTP client: InvalidInputError + # is also a ValueError and must not be wrapped as a rejected request. + error = InvalidInputError("too long", code="input_too_long", param="request") + with pytest.raises(InvalidInputError) as exc: + _detector(FakeVela(on_call=_raise(error))).detect(SOURCES) + assert exc.value is error + + +# -- usage and warnings ------------------------------------------------------------------- + + +def test_usage_units_for_sources(): + usage = _detector().detect(SOURCES).usage + assert len(usage) == 1 + assert usage[0].model_id == "vllm-sr/Vela-2.0-0.3B" + assert usage[0].model_version == "abc123" + assert usage[0].units == { + "answer_chars": len(ANSWER), + "sources": 2, + "source_chars": 60, + "input_tokens": 120, + } + + +def test_usage_units_for_prompt_have_no_sources(): + units = _detector().detect(PROMPT).usage[0].units + assert units == { + "answer_chars": len(ANSWER), + "source_chars": len(PROMPT.prompt), + "input_tokens": 120, + } + + +def test_usage_has_no_input_tokens_when_the_model_does_not_report_them(): + units = _detector(FakeVela(input_tokens=None)).detect(PROMPT).usage[0].units + assert "input_tokens" not in units + + +@pytest.mark.parametrize(("input_tokens", "truncated"), [(8191, False), (8192, True), (9500, True)]) +def test_input_truncated_when_the_model_used_its_whole_budget(input_tokens, truncated, caplog): + # SOURCES has a question: long sources next to one are cut and warned about, not rejected. + result = _detector(FakeVela(input_tokens=input_tokens)).detect(SOURCES) + assert [w.code for w in result.warnings] == (["input_truncated"] if truncated else []) + if truncated: + # The reply cannot tell a cut input from an exact fit, and the warning says so. + assert "fits exactly" in result.warnings[0].message + records = [r for r in caplog.records if r.getMessage().startswith("input_truncated")] + assert len(records) == (1 if truncated else 0) + assert ANSWER not in caplog.text + + +def test_input_truncated_follows_the_configured_budget(): + result = _detector(FakeVela(input_tokens=600), max_length=512).detect(SOURCES) + assert [w.code for w in result.warnings] == ["input_truncated"] + + +def test_no_warning_when_the_model_does_not_report_input_tokens(): + assert _detector(FakeVela(input_tokens=None)).detect(SOURCES).warnings == [] + + +# -- side effects and concurrency --------------------------------------------------------- + + +class _RecordingEnviron(dict): + """A stand-in for ``os.environ`` that records every key read.""" + + def __init__(self, *args: object) -> None: + super().__init__(*args) + self.read: list[str] = [] + + def __getitem__(self, key: str) -> str: + self.read.append(key) + return super().__getitem__(key) + + def get(self, key: str, default: Any = None) -> Any: # noqa: ANN401 + self.read.append(key) + return super().get(key, default) + + def __contains__(self, key: object) -> bool: + self.read.append(str(key)) + return super().__contains__(key) + + +def test_a_call_reads_no_environment_variable(monkeypatch): + detector = _detector() + environ = _RecordingEnviron(os.environ) + monkeypatch.setattr(os, "environ", environ) + detector.detect(SOURCES) + detector.detect(PROMPT) + assert environ.read == [] + + +async def test_concurrent_detect_and_adetect_calls_match_sequential_results(): + model = FakeVela(on_call=lambda: time.sleep(0.002)) + detector = _detector(model) + requests = [] + for i in range(12): + answer = ["Berlin it is.", "About 3 million.", "France, Berlin, 3 million.", "Nothing."][ + i % 4 + ] + if i % 2: + requests.append(PromptInput(prompt=f"Context number {i}.", answer=answer)) + else: + requests.append( + SourcesInput(sources=[Chunk(id=str(i), text=f"Source {i}.")], answer=answer) + ) + expected = [detector.detect(r) for r in requests] + loop = asyncio.get_running_loop() + sync_results = [loop.run_in_executor(None, detector.detect, r) for r in requests[::2]] + async_results = [detector.adetect(r) for r in requests[1::2]] + results = await asyncio.gather(*sync_results, *async_results) + assert list(results) == expected[::2] + expected[1::2] + assert not model.overlapped + + +def test_same_input_gives_the_same_result_after_other_input(): + detector = _detector() + first = detector.detect(SOURCES) + detector.detect(PromptInput(prompt="Something else entirely.", answer="Berlin.")) + assert detector.detect(SOURCES) == first + + +@pytest.mark.parametrize( + ("flag", "code"), + [("include_tokens", "tokens_not_supported"), ("include_detail", "detail_not_supported")], +) +def test_tokens_and_detail_are_not_supported(flag, code): + model = FakeVela() + with pytest.raises(InvalidInputError) as exc: + _detector(model).detect(SOURCES, **{flag: True}) + assert (exc.value.code, exc.value.param) == (code, flag) + assert model.calls == [] + + +def test_predict_returns_legacy_spans(): + spans = _detector().predict( + ["Paris is the capital of France."], + ANSWER, + "What?", + output_format="spans", + min_confidence=0.5, + ) + assert [s["text"] for s in spans] == ["Berlin", "3 million"] + assert spans[0]["confidence"] == 0.9 diff --git a/tests/test_vela_from_pretrained_pytest.py b/tests/test_vela_from_pretrained_pytest.py new file mode 100644 index 0000000..6ecd314 --- /dev/null +++ b/tests/test_vela_from_pretrained_pytest.py @@ -0,0 +1,185 @@ +"""Tests for ``VelaDetector.from_pretrained``: offline with a fake loader, plus one real-model test.""" + +from __future__ import annotations + +import logging +import socket +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from lettucedetect.detectors.errors import ConfigurationError, UpstreamError +from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput +from lettucedetect.detectors.vela import VelaConfig, VelaDetector +from tests.test_vela_detector_pytest import FakeVela + +REQUEST = PromptInput(prompt="The capital of France is Paris.", answer="It is Berlin.") +SHA_MAIN = "a" * 40 +SHA_V1 = "b" * 40 +SECRET_PROMPT = "ZEBRA-PROMPT-TEXT" # noqa: S105 +SECRET_ANSWER = "ZEBRA-ANSWER-TEXT Berlin" # noqa: S105 + +# The Vela 2.0 0.3B commit the real-model test runs against. +VELA_03B = "vllm-sr/Vela-2.0-0.3B" +VELA_03B_REVISION = "d6f03aa9baca4f9017fa8f8e9c2764d3bed3f409" + + +@pytest.fixture +def loader(): + """Patch ``AutoModel.from_pretrained`` to return a fake model; yield the model and the mock.""" + model = MagicMock() + model.system_one.side_effect = FakeVela().system_one + model_loader = MagicMock(return_value=model) + with patch("lettucedetect.detectors.vela.AutoModel.from_pretrained", model_loader): + yield model, model_loader + + +@pytest.fixture +def offline_cache(tmp_path, monkeypatch): + """Build a Hugging Face cache with ``org/name`` at two revisions, with the network blocked.""" + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + + def no_network(*args: object, **kwargs: object) -> None: + raise AssertionError("network used") + + monkeypatch.setattr(socket.socket, "connect", no_network) + repo = tmp_path / "hub" / "models--org--name" + for sha in (SHA_MAIN, SHA_V1): + (repo / "snapshots" / sha).mkdir(parents=True) + (repo / "snapshots" / sha / "config.json").write_text("{}") + (repo / "refs").mkdir() + (repo / "refs" / "main").write_text(SHA_MAIN) + (repo / "refs" / "v1").write_text(SHA_V1) + return tmp_path / "hub" + + +def test_loads_with_trust_remote_code_and_revision_and_moves_the_model(loader): + model, model_loader = loader + detector = VelaDetector.from_pretrained( + "org/name", + revision="v1", + device="cpu", + config=VelaConfig(threshold=0.4), + local_files_only=True, + trust_remote_code=False, + ) + model_loader.assert_called_once_with( + "org/name", local_files_only=True, revision="v1", trust_remote_code=True + ) + model.to.assert_called_once_with(torch.device("cpu")) + model.eval.assert_called_once_with() + assert detector.model is model + assert detector.model_id == "org/name" + assert detector.config.threshold == 0.4 + assert [s.text for s in detector.detect(REQUEST).spans] == ["Berlin"] + + +def test_hub_id_reports_the_resolved_commit(loader, offline_cache): + detector = VelaDetector.from_pretrained("org/name", cache_dir=str(offline_cache)) + assert detector.model_version == SHA_MAIN + assert detector.detect(REQUEST).usage[0].model_version == SHA_MAIN + + +def test_hub_id_follows_the_requested_revision(loader, offline_cache): + detector = VelaDetector.from_pretrained( + "org/name", revision="v1", model_version="mine", cache_dir=str(offline_cache) + ) + assert detector.model_version == SHA_V1 + + +def test_callers_version_is_the_fallback_when_nothing_is_cached(loader, offline_cache): + kwargs = {"cache_dir": str(offline_cache)} + assert VelaDetector.from_pretrained("other/model", **kwargs).model_version is None + assert ( + VelaDetector.from_pretrained("other/model", model_version="v7", **kwargs).model_version + == "v7" + ) + + +def test_local_path_uses_the_callers_version_and_no_cache_lookup(loader, tmp_path): + boom = MagicMock(side_effect=AssertionError("cache consulted")) + with patch("lettucedetect.detectors.encoder.try_to_load_from_cache", boom): + detector = VelaDetector.from_pretrained(str(tmp_path), model_version="2026-11") + assert detector.model_version == "2026-11" + boom.assert_not_called() + + +def test_model_loaded_is_logged_exactly_once_at_info(loader, offline_cache, caplog): + caplog.set_level(logging.DEBUG) + detector = VelaDetector.from_pretrained("org/name", device="cpu", cache_dir=str(offline_cache)) + detector.detect(PromptInput(prompt=SECRET_PROMPT, answer=SECRET_ANSWER)) + loud = [r for r in caplog.records if r.levelno >= logging.INFO] + assert len(loud) == 1 + record = loud[0] + assert (record.name, record.event) == ("lettucedetect.detectors.vela", "model_loaded") + assert record.args[:3] == ("org/name", SHA_MAIN, torch.device("cpu")) + assert SECRET_PROMPT not in caplog.text + assert SECRET_ANSWER not in caplog.text + + +def test_old_transformers_raises_missing_dependency(loader): + _, model_loader = loader + with ( + patch("lettucedetect.detectors.vela._transformers_version", return_value="4.48.3"), + pytest.raises(ConfigurationError) as exc, + ): + VelaDetector.from_pretrained("org/name") + assert exc.value.code == "missing_dependency" + assert "lettucedetect[vela]" in exc.value.message + model_loader.assert_not_called() + + +def test_missing_runtime_package_raises_missing_dependency(loader): + with ( + patch("lettucedetect.detectors.vela.importlib.util.find_spec", return_value=None), + pytest.raises(ConfigurationError) as exc, + ): + VelaDetector.from_pretrained("org/name") + assert exc.value.code == "missing_dependency" + assert "lettucedetect[vela]" in exc.value.message + + +def test_import_error_from_the_model_code_raises_missing_dependency(loader): + _, model_loader = loader + model_loader.side_effect = ImportError("requires the following packages: fla") + with pytest.raises(ConfigurationError) as exc: + VelaDetector.from_pretrained("org/name") + assert exc.value.code == "missing_dependency" + assert "lettucedetect[vela]" in exc.value.message + assert isinstance(exc.value.__cause__, ImportError) + + +def test_loader_failure_for_a_hub_id_is_an_upstream_error(loader): + _, model_loader = loader + model_loader.side_effect = OSError("not found") + with pytest.raises(UpstreamError) as exc: + VelaDetector.from_pretrained("org/name") + assert exc.value.code == "model_load_failed" + + +def test_loader_failure_for_a_local_path_is_a_configuration_error(loader, tmp_path): + _, model_loader = loader + model_loader.side_effect = OSError("no weights") + with pytest.raises(ConfigurationError) as exc: + VelaDetector.from_pretrained(str(tmp_path)) + assert exc.value.code == "model_load_failed" + + +@pytest.mark.model_download +def test_real_vela_03b_flags_the_unsupported_day(): + detector = VelaDetector.from_pretrained(VELA_03B, revision=VELA_03B_REVISION, device="cpu") + request = SourcesInput( + question="When does it ship?", + sources=[Chunk(id="doc-1", text="Ships Friday.")], + answer="Ships Monday.", + ) + result = detector.detect(request, min_score=0.5) + assert any("Monday" in span.text for span in result.spans) + for span in result.spans: + assert request.answer[span.start : span.end] == span.text + usage = result.usage[0] + assert (usage.model_id, usage.model_version) == (VELA_03B, VELA_03B_REVISION) + assert usage.units["sources"] == 1 + assert usage.units["input_tokens"] > 0 + assert result.warnings == [] From 15fd151c6e6c3cb1cccdf9051244bd89e3e5370d Mon Sep 17 00:00:00 2001 From: Suleyman Furkan Atas Date: Thu, 19 Nov 2026 12:47:30 +0100 Subject: [PATCH 31/60] feat: add VelaDetector HTTP mode and when-to-choose-Vela docs (#118) (#194) * feat: add VelaDetector HTTP mode and when-to-choose-Vela docs (#118) * fix: declare httpx and add VelaDetector.close (#118) --- docs/guide/detection-methods.md | 52 ++++- lettucedetect/detectors/vela.py | 69 +++++- lettucedetect/detectors/vela_client.py | 211 +++++++++++++++++ pyproject.toml | 1 + tests/test_vela_client_pytest.py | 306 +++++++++++++++++++++++++ 5 files changed, 634 insertions(+), 5 deletions(-) create mode 100644 lettucedetect/detectors/vela_client.py create mode 100644 tests/test_vela_client_pytest.py diff --git a/docs/guide/detection-methods.md b/docs/guide/detection-methods.md index b900004..db2f16e 100644 --- a/docs/guide/detection-methods.md +++ b/docs/guide/detection-methods.md @@ -1,6 +1,6 @@ # Detection Methods -LettuceDetect supports three ways to detect hallucinations, each with different trade-offs. +LettuceDetect supports four ways to detect hallucinations, each with different trade-offs. ## Transformer (Recommended) @@ -112,3 +112,53 @@ detector = HallucinationDetector(method="rag_fact_checker", model_path="gpt-4o-m **How it works:** Extracts (subject, predicate, object) claims from the answer, then checks each claim against the context. **When to use:** When you want claim-level granularity and structured verification results. + +## Vela 2.0 + +[Vela 2.0](https://huggingface.co/collections/vllm-sr/vela-20) models (a 0.3B encoder; 0.8B, 4B and 9B decoders) answer typed SystemOne questions about a request, a context and an answer. `VelaDetector` asks the hallucination span question and returns the unsupported spans of the answer with their probability as score. + +**How it works:** The question and the sources go to Vela as one context, in the format it was trained on (`User request: ` followed by the sources). An input over the 8,192-token window is cut, and the result carries the `input_truncated` warning instead of failing. + +Run the model in-process. Its code ships in the model repository and runs with `trust_remote_code=True`, so pin `revision` to a commit you have reviewed: + +```python +from lettucedetect.detectors import Chunk, SourcesInput, VelaDetector + +detector = VelaDetector.from_pretrained("vllm-sr/Vela-2.0-0.3B", revision="") +result = detector.detect( + SourcesInput( + question="When does it ship?", + sources=[Chunk(id="doc-1", text="Ships Friday.")], + answer="Ships Monday.", + ), + min_score=0.5, +) +``` + +Or call a SystemOne server (`POST /v1/systemone`), such as the `vela2_serve.py` script in the model repository. The URL and the key come from the caller; nothing is read from the environment: + +```python +detector = VelaDetector.from_server( + "http://127.0.0.1:8001", model="vllm-sr/Vela-2.0-0.3B", api_key="" +) +``` + +Call `detector.close()`, or use the detector in a `with` block, to close its HTTP connections when it is no longer needed. + +A rejected key raises `ConfigurationError`. A timeout, a connection error, a rate limit, a server error or an unreadable reply raises `UpstreamError`, with `retryable` set when a retry can help. Install the in-process runtime with `pip install 'lettucedetect[vela]'`; the server mode needs no extra. + +### When to choose Vela + +Hallucination example-F1 on the 10,698-example test set and on RAGTruth, as reported by Vela ([EVALUATION.md](https://huggingface.co/vllm-sr/Vela-2.0-4B/blob/main/EVALUATION.md)); the 0.3B number is reproduced in [Vela 2.0 0.3B results](../code-hallucination/results_vela.md): + +| Model | 10,698 examples | RAGTruth | +|---|--:|--:| +| Vela 2.0 0.3B (encoder, CPU) | 0.848 | 0.706 | +| Vela 2.0 4B | 0.874 | 0.770 | +| Vela 2.0 9B | 0.885 | 0.774 | +| lettucedect-v2-mmbert-base | 0.869 | 0.743 | +| lettucedect-v2-qwen-2b | 0.921 | 0.817 | + +**Choose Vela** when one model should answer more than hallucination: the same Vela call can also return PII spans and prompt-attack and safety scores (not yet exposed by `VelaDetector`), or when you need a CPU model with an 8,192-token window between the encoder and generative lines. + +**Choose the LettuceDetect models** for the best hallucination F1, and when you need typed categories: they label each span with the hallucination taxonomy, while Vela returns one `unsupported` label. diff --git a/lettucedetect/detectors/vela.py b/lettucedetect/detectors/vela.py index e035355..b298d2f 100644 --- a/lettucedetect/detectors/vela.py +++ b/lettucedetect/detectors/vela.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import importlib.util import logging import numbers @@ -37,6 +38,7 @@ SourcesInput, Usage, ) +from lettucedetect.detectors.vela_client import SystemOneClient logger = logging.getLogger(__name__) @@ -183,11 +185,14 @@ class VelaDetector(BaseDetector): With more than one criterion in the config, each span's ``category`` is the label Vela matched. - Construction downloads nothing, reads no environment variable and writes no file. Calls run - under one private lock, so concurrent calls on one instance run one at a time. + Construction downloads nothing, reads no environment variable and writes no file. Calls to a + local model run under one private lock, so concurrent calls on one instance run one at a time. Vela ships its code in the model repository, so loading needs ``trust_remote_code=True``. :meth:`from_pretrained` sets it; pin ``revision`` to a commit you have reviewed. + :meth:`from_server` calls a SystemOne server instead, such as the ``vela2_serve.py`` script in + the model repository; nothing is loaded in-process then. Call :meth:`close`, or use the + detector in a ``with`` block, to close its HTTP connections when it is no longer needed. Example:: @@ -201,6 +206,10 @@ class VelaDetector(BaseDetector): min_score=0.5, ) + served = VelaDetector.from_server( + "http://127.0.0.1:8001", model="vllm-sr/Vela-2.0-0.3B", api_key="" + ) + :param model: a loaded Vela model, or any object with a system_one(state=..., questions=...) method.. :param config: options, ``VelaConfig()`` when ``None``. :param model_id: id reported in ``usage``. @@ -227,8 +236,10 @@ def __init__( self.model_version = model_version # Scoring lock is created here, not lazily as in EncoderDetector: from_pretrained # calls cls(), so __init__ always runs and no first-call race exists. A plain Lock is - # enough because only _detect takes it, once per call. + # enough because only _detect takes it, once per call. A model that says it is + # thread_safe, such as SystemOneClient, is called without it. self._scoring_lock = threading.Lock() + self._lock_calls = not getattr(model, "thread_safe", False) logger.debug( "vela detector built: model_id=%s criteria=%d threshold=%s max_length=%d", model_id, @@ -285,6 +296,54 @@ def from_pretrained( _log_model_loaded(model_id, version, device, started, module_logger=logger) return detector + @classmethod + def from_server( + cls, + base_url: str, + *, + model: str, + api_key: str | None = None, + timeout: float = 30.0, + config: VelaConfig | None = None, + model_version: str | None = None, + ) -> VelaDetector: + """Build a detector that calls a SystemOne server (``POST /v1/systemone``). + + No request is sent here, and nothing is read from the environment: the URL and the key + come from the caller. The server does not report which commit of the model it runs, so + ``usage`` carries the caller's ``model_version``. The detector holds an HTTP connection + pool; call :meth:`close` or use it in a ``with`` block when it is no longer needed. + + :param base_url: the server's base URL, for example ``http://127.0.0.1:8001``. + :param model: the model name the server serves; also the ``model_id`` in ``usage``. + :param api_key: sent as ``Authorization: Bearer ``; ``None`` sends no header. + :param timeout: seconds to wait for the server, per request. + :param config: options, ``VelaConfig()`` when ``None``. + :param model_version: version reported in ``usage``. + :raises ConfigurationError: (``invalid_config``) ``base_url`` or ``model`` is blank, or + ``timeout`` is not positive. + """ + client = SystemOneClient(base_url, model=model, api_key=api_key, timeout=timeout) + return cls(client, config=config, model_id=model, model_version=model_version) + + def close(self) -> None: + """Close the model's connections, if it has any. + + A detector from :meth:`from_server` closes its HTTP client; for a local model this does + nothing. Calling it more than once is safe. + """ + close = getattr(self.model, "close", None) + if callable(close): + close() + + def __enter__(self) -> VelaDetector: + """Return the detector, for use in a ``with`` block.""" + return self + + def __exit__(self, *exc_info: object) -> None: + """Close the model's connections at the end of a ``with`` block.""" + self.close() + # ------------------------------------------------------------------ # Detection # ------------------------------------------------------------------ @@ -302,6 +361,8 @@ def _detect( (``input_too_long``) Vela could not cut the input into its token window. :raises UpstreamError: (``invalid_model_output``) Vela rejected the request, or the reply does not have the span shape. + A detector from :meth:`from_server` also raises the errors of + :meth:`SystemOneClient.system_one`. """ answer = request.answer units: dict[str, int] = {"answer_chars": len(answer)} @@ -317,7 +378,7 @@ def _detect( return Detection(usage=[self._usage(units)]) requested = time.perf_counter() - with self._scoring_lock: + with self._scoring_lock if self._lock_calls else contextlib.nullcontext(): started = time.perf_counter() logger.debug( "detect started: kind=%s model_id=%s lock_wait_ms=%.1f", diff --git a/lettucedetect/detectors/vela_client.py b/lettucedetect/detectors/vela_client.py new file mode 100644 index 0000000..718ae04 --- /dev/null +++ b/lettucedetect/detectors/vela_client.py @@ -0,0 +1,211 @@ +"""HTTP client for a SystemOne server, so :class:`VelaDetector` can use a served Vela model. + +A SystemOne server, such as the ``vela2_serve.py`` script in each Vela model repository, answers +``POST /v1/systemone`` with the reply a local model's ``system_one`` returns. :class:`SystemOneClient` +has that same ``system_one(state=..., questions=...)`` method, so the detector uses it in place of +a model. Every failure of the call is raised as a typed error from :mod:`.errors`. +""" + +from __future__ import annotations + +import logging +from typing import Any + +import httpx + +from lettucedetect.detectors.errors import ConfigurationError, InvalidInputError, UpstreamError + +logger = logging.getLogger(__name__) + +__all__ = ["SystemOneClient"] + +_PATH = "/v1/systemone" +_SERVICE = "vela" + + +def _retry_after(response: httpx.Response) -> float | None: + """Return the ``Retry-After`` header in seconds, or ``None`` when it is absent or a date.""" + try: + return float(response.headers["retry-after"]) + except (KeyError, ValueError): + return None + + +def _rejected_field(response: httpx.Response) -> str | None: + """Return the field a 422 reply names, the last item of ``detail[0].loc`` (``["body", "model"]``).""" + try: + return str(response.json()["detail"][0]["loc"][-1]) + except (ValueError, KeyError, IndexError, TypeError): + return None + + +def _status_error( + response: httpx.Response, +) -> ConfigurationError | InvalidInputError | UpstreamError: + """Build the error for a reply whose status is not 2xx. + + The message names the status only: the server's body can echo the request, so it never + goes into the error. + """ + status = response.status_code + if status in (401, 403): + return ConfigurationError( + f"The SystemOne server rejected the API key (HTTP {status}); check api_key.", + code="invalid_api_key", + param="api_key", + ) + if status == 413: + # The server's "too_long": the same error as a local model that cannot fit the input. + return InvalidInputError( + "The input does not fit the model's token window; pass shorter sources.", + code="input_too_long", + param="request", + ) + if status == 422 and _rejected_field(response) == "model": + return ConfigurationError( + "The SystemOne server does not serve this model; check model.", + code="model_not_served", + param="model", + ) + if status == 429: + return UpstreamError( + "The SystemOne server is rate limiting requests (HTTP 429); retry later.", + code="rate_limited", + service=_SERVICE, + retryable=True, + retry_after=_retry_after(response), + ) + if status >= 500: + return UpstreamError( + f"The SystemOne server failed (HTTP {status}); retry later.", + code="server_error", + service=_SERVICE, + retryable=True, + retry_after=_retry_after(response), + ) + return UpstreamError( + f"The SystemOne server rejected the request (HTTP {status}).", + code="request_rejected", + service=_SERVICE, + ) + + +class SystemOneClient: + """Call a SystemOne server with the ``system_one`` method of a local Vela model. + + The caller passes everything: the client reads no environment variable, including the proxy + and certificate settings httpx would otherwise pick up. One client is safe to share between + threads, so :class:`VelaDetector` does not serialize calls through it. + + :param base_url: the server's base URL, for example ``http://127.0.0.1:8001``. + :param model: the model name the server serves, sent with every request. + :param api_key: sent as ``Authorization: Bearer ``; ``None`` sends no header. + :param timeout: seconds to wait for the server, per request. + :param http_client: an ``httpx.Client`` to use instead of building one, for example with a + custom transport. Its base URL, headers and timeout are the caller's to set, so + ``base_url`` and ``timeout`` are not applied to it, and passing ``api_key`` with it raises + :class:`ConfigurationError`: set the ``Authorization`` header on the client instead. + """ + + # Read by VelaDetector: calls through this client need no scoring lock. + thread_safe = True + + def __init__( + self, + base_url: str, + *, + model: str, + api_key: str | None = None, + timeout: float = 30.0, + http_client: httpx.Client | None = None, + ) -> None: + """Build the client; no request is sent.""" + if not base_url.strip(): + raise ConfigurationError( + "base_url must not be blank.", code="invalid_config", param="base_url" + ) + if not model.strip(): + raise ConfigurationError( + "model must not be blank.", code="invalid_config", param="model" + ) + if timeout <= 0: + raise ConfigurationError( + "timeout must be greater than 0.", code="invalid_config", param="timeout" + ) + if http_client is not None and api_key is not None: + # The key would not reach a client the caller built, and the server would answer + # 401 with no hint why. + raise ConfigurationError( + "api_key is not applied to a given http_client; set the Authorization header " + "on the http_client instead.", + code="invalid_config", + param="api_key", + ) + self.model = model + if http_client is None: + headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} + http_client = httpx.Client( + base_url=base_url, headers=headers, timeout=timeout, trust_env=False + ) + self._http = http_client + + def system_one(self, *, state: dict[str, str], questions: dict[str, Any]) -> dict[str, Any]: + """Send one SystemOne request and return the server's reply. + + :param state: the SystemOne state, for example ``request``, ``source`` and ``answer``. + :param questions: the SystemOne questions by id. + :returns: the reply object, in the shape a local model's ``system_one`` returns. + :raises ConfigurationError: (``invalid_api_key``) the server rejected the key; + (``model_not_served``) the server does not serve ``model``. + :raises InvalidInputError: (``input_too_long``) the input does not fit the model's window. + :raises UpstreamError: (``timeout``, ``connection_failed``, ``rate_limited``, + ``server_error``, ``request_rejected``) the call failed; (``invalid_model_output``) + the reply is not a JSON object. + """ + body = {"state": state, "model": self.model, "questions": questions} + try: + response = self._http.post(_PATH, json=body) + except httpx.TimeoutException as exc: + raise UpstreamError( + "The SystemOne server did not answer in time; retry or raise timeout.", + code="timeout", + service=_SERVICE, + retryable=True, + ) from exc + except httpx.TransportError as exc: + raise UpstreamError( + "Could not connect to the SystemOne server; check base_url and the network.", + code="connection_failed", + service=_SERVICE, + retryable=True, + ) from exc + if not response.is_success: + logger.debug("systemone request failed: status=%d", response.status_code) + raise _status_error(response) + try: + reply = response.json() + except ValueError as exc: + raise UpstreamError( + "The SystemOne server returned a reply that is not JSON.", + code="invalid_model_output", + service=_SERVICE, + ) from exc + if not isinstance(reply, dict): + raise UpstreamError( + "The SystemOne server returned a reply that is not a JSON object.", + code="invalid_model_output", + service=_SERVICE, + ) + return reply + + def close(self) -> None: + """Close the HTTP connections.""" + self._http.close() + + def __enter__(self) -> SystemOneClient: + """Return the client, for use in a ``with`` block.""" + return self + + def __exit__(self, *exc_info: object) -> None: + """Close the HTTP connections at the end of a ``with`` block.""" + self.close() diff --git a/pyproject.toml b/pyproject.toml index da00cce..a05eec2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dependencies = [ "scikit-learn>=1.6.1", "numpy>=2.2.2", "openai>=1.66.3", + "httpx>=0.28", "packaging>=20.0", "pydantic>=2.0", "rag-fact-checker", diff --git a/tests/test_vela_client_pytest.py b/tests/test_vela_client_pytest.py new file mode 100644 index 0000000..315dcc6 --- /dev/null +++ b/tests/test_vela_client_pytest.py @@ -0,0 +1,306 @@ +"""Tests for ``SystemOneClient`` and ``VelaDetector.from_server``: offline, on a mock transport.""" + +from __future__ import annotations + +import asyncio +import json +import os +import time +from collections.abc import Callable + +import httpx +import pytest + +from lettucedetect.detectors import VelaDetector, vela_client +from lettucedetect.detectors.errors import ConfigurationError, InvalidInputError, UpstreamError +from lettucedetect.detectors.types import Chunk, PromptInput, SourcesInput +from lettucedetect.detectors.vela_client import SystemOneClient +from tests.detector_contract import DetectorContract +from tests.test_vela_detector_pytest import ( + PROMPT, + SOURCES, + FakeVela, + _RecordingEnviron, +) + +BASE_URL = "http://vela.test" +MODEL = "vllm-sr/Vela-2.0-0.3B" +API_KEY = "ZEBRA-KEY" +SECRET = "ZEBRA-ANSWER-TEXT" # noqa: S105 +STATE = {"source": "Ships Friday.", "answer": "Ships Monday."} +QUESTIONS = {"halu": {"type": "span"}} + +Handler = Callable[[httpx.Request], httpx.Response] + + +def _served(model: FakeVela) -> Handler: + """Return a handler that answers ``/v1/systemone`` like ``vela2_serve.py`` with ``model``.""" + + def handle(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + return httpx.Response(200, json=model.system_one(body["state"], body["questions"])) + + return handle + + +def _client(handler: Handler, api_key: str | None = API_KEY) -> SystemOneClient: + """Build a client whose requests go to ``handler`` instead of the network.""" + headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} + http = httpx.Client(base_url=BASE_URL, headers=headers, transport=httpx.MockTransport(handler)) + return SystemOneClient(BASE_URL, model=MODEL, http_client=http) + + +@pytest.fixture +def mock_transport(monkeypatch): + """Route every ``httpx.Client`` that ``SystemOneClient`` builds to a handler set by the test. + + Yields a dict; the test puts its handler under ``"handler"`` and reads the keyword arguments + the client was built with from ``"kwargs"``. + """ + route: dict[str, object] = {"handler": _served(FakeVela())} + real_client = httpx.Client + + def build(**kwargs: object) -> httpx.Client: + route["kwargs"] = kwargs + return real_client(**kwargs, transport=httpx.MockTransport(lambda r: route["handler"](r))) + + monkeypatch.setattr(vela_client.httpx, "Client", build) + return route + + +def _served_detector(model: FakeVela | None = None) -> VelaDetector: + return VelaDetector( + _client(_served(model or FakeVela())), model_id=MODEL, model_version="abc123" + ) + + +class TestServedVelaDetectorContract(DetectorContract): + """The shared detector contract holds for a ``VelaDetector`` that calls a server.""" + + sources_request = SOURCES + prompt_request = PROMPT + + def make_detector(self, on_call=None): # noqa: D102 + return _served_detector(FakeVela(on_call=on_call)) + + +# -- the request ---------------------------------------------------------------------------- + + +def test_request_is_a_systemone_post_with_state_model_and_questions(): + seen: list[httpx.Request] = [] + + def handle(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json={"spans": {"halu": []}}) + + reply = _client(handle).system_one(state=STATE, questions=QUESTIONS) + assert reply == {"spans": {"halu": []}} + (request,) = seen + assert (request.method, request.url.path) == ("POST", "/v1/systemone") + assert json.loads(request.content) == {"state": STATE, "model": MODEL, "questions": QUESTIONS} + + +def test_from_server_sends_the_key_and_trusts_no_environment(mock_transport): + seen: list[httpx.Request] = [] + mock_transport["handler"] = lambda r: seen.append(r) or _served(FakeVela())(r) + detector = VelaDetector.from_server(BASE_URL, model=MODEL, api_key=API_KEY, timeout=5.0) + detector.detect(SOURCES) + assert seen[0].headers["authorization"] == f"Bearer {API_KEY}" + assert str(seen[0].url) == f"{BASE_URL}/v1/systemone" + assert mock_transport["kwargs"]["trust_env"] is False + assert mock_transport["kwargs"]["timeout"] == 5.0 + + +def test_no_key_sends_no_authorization_header(mock_transport): + seen: list[httpx.Request] = [] + mock_transport["handler"] = lambda r: seen.append(r) or _served(FakeVela())(r) + VelaDetector.from_server(BASE_URL, model=MODEL).detect(SOURCES) + assert "authorization" not in seen[0].headers + + +@pytest.mark.parametrize( + ("kwargs", "param"), + [({"base_url": " "}, "base_url"), ({"model": ""}, "model"), ({"timeout": 0}, "timeout")], +) +def test_invalid_options_raise_configuration_error(kwargs, param): + options = {"base_url": BASE_URL, "model": MODEL, **kwargs} + with pytest.raises(ConfigurationError) as exc: + VelaDetector.from_server(options.pop("base_url"), **options) + assert (exc.value.code, exc.value.param) == ("invalid_config", param) + + +# -- errors --------------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("response", "error", "code", "retryable", "retry_after"), + [ + ( + httpx.Response(401, json={"detail": "Missing or invalid API key"}), + ConfigurationError, + "invalid_api_key", + None, + None, + ), + (httpx.Response(403), ConfigurationError, "invalid_api_key", None, None), + ( + httpx.Response( + 422, json={"detail": [{"loc": ["body", "model"], "msg": "no", "type": "x"}]} + ), + ConfigurationError, + "model_not_served", + None, + None, + ), + ( + httpx.Response(413, json={"detail": [{"loc": [], "msg": SECRET, "type": "too_long"}]}), + InvalidInputError, + "input_too_long", + None, + None, + ), + ( + httpx.Response(429, headers={"Retry-After": "7"}), + UpstreamError, + "rate_limited", + True, + 7.0, + ), + (httpx.Response(429), UpstreamError, "rate_limited", True, None), + (httpx.Response(503, text=SECRET), UpstreamError, "server_error", True, None), + ( + httpx.Response( + 422, json={"detail": [{"loc": ["body", "state"], "msg": SECRET, "type": "x"}]} + ), + UpstreamError, + "request_rejected", + False, + None, + ), + (httpx.Response(404), UpstreamError, "request_rejected", False, None), + (httpx.Response(200, text="not json"), UpstreamError, "invalid_model_output", False, None), + ( + httpx.Response(200, json=["a", "list"]), + UpstreamError, + "invalid_model_output", + False, + None, + ), + ], +) +def test_failed_replies_raise_typed_errors(response, error, code, retryable, retry_after): + detector = VelaDetector(_client(lambda r: response), model_id=MODEL) + with pytest.raises(error) as exc: + detector.detect(SourcesInput(sources=[Chunk(id="s", text=SECRET)], answer=SECRET)) + assert exc.value.code == code + if error is UpstreamError: + assert exc.value.service == "vela" + assert (exc.value.retryable, exc.value.retry_after) == (retryable, retry_after) + if error is ConfigurationError: + assert exc.value.param == ("model" if code == "model_not_served" else "api_key") + assert SECRET not in str(exc.value) + assert API_KEY not in str(exc.value) + + +@pytest.mark.parametrize( + ("raised", "code"), + [ + (httpx.ReadTimeout("timed out"), "timeout"), + (httpx.ConnectTimeout("timed out"), "timeout"), + (httpx.ConnectError("refused"), "connection_failed"), + (httpx.RemoteProtocolError("closed"), "connection_failed"), + ], +) +def test_transport_failures_raise_retryable_upstream_errors(raised, code): + def handle(request: httpx.Request) -> httpx.Response: + raise raised + + with pytest.raises(UpstreamError) as exc: + _client(handle).system_one(state=STATE, questions=QUESTIONS) + assert (exc.value.code, exc.value.service, exc.value.retryable) == (code, "vela", True) + assert exc.value.__cause__ is raised + + +# -- the detector over a server ------------------------------------------------------------- + + +def test_served_spans_and_usage_match_the_local_model(): + local = VelaDetector(FakeVela(), model_id=MODEL, model_version="abc123") + assert _served_detector().detect(SOURCES) == local.detect(SOURCES) + assert _served_detector().detect(PROMPT) == local.detect(PROMPT) + + +def test_from_server_reports_the_model_name_and_the_callers_version(mock_transport): + detector = VelaDetector.from_server(BASE_URL, model=MODEL, model_version="2026-11") + usage = detector.detect(SOURCES).usage[0] + assert (usage.model_id, usage.model_version) == (MODEL, "2026-11") + + +def test_served_input_truncated_is_reported(): + result = _served_detector(FakeVela(input_tokens=8192)).detect(SOURCES) + assert [w.code for w in result.warnings] == ["input_truncated"] + + +def test_a_served_call_reads_no_environment_variable(monkeypatch, mock_transport): + environ = _RecordingEnviron(os.environ) + monkeypatch.setattr(os, "environ", environ) + detector = VelaDetector.from_server(BASE_URL, model=MODEL, api_key=API_KEY) + detector.detect(SOURCES) + detector.detect(PROMPT) + assert environ.read == [] + + +async def test_concurrent_served_calls_run_in_parallel_and_match_sequential_results(): + model = FakeVela(on_call=lambda: time.sleep(0.02)) + detector = _served_detector(model) + requests = [ + PromptInput(prompt=f"Context number {i}.", answer=["Berlin.", "3 million.", "No."][i % 3]) + for i in range(8) + ] + expected = [detector.detect(r) for r in requests] + loop = asyncio.get_running_loop() + sync_results = [loop.run_in_executor(None, detector.detect, r) for r in requests[::2]] + async_results = [detector.adetect(r) for r in requests[1::2]] + results = await asyncio.gather(*sync_results, *async_results) + assert list(results) == expected[::2] + expected[1::2] + # The client is thread-safe, so the detector takes no scoring lock around it. + assert model.overlapped + + +def test_local_models_still_run_one_call_at_a_time(): + assert VelaDetector(FakeVela())._lock_calls is True + assert _served_detector()._lock_calls is False + + +def test_close_closes_the_http_client(): + client = _client(_served(FakeVela())) + with client: + pass + assert client._http.is_closed + + +def test_detector_close_closes_the_client_from_server(mock_transport): + detector = VelaDetector.from_server(BASE_URL, model=MODEL) + detector.detect(SOURCES) + detector.close() + assert detector.model._http.is_closed + detector.close() # a second close is harmless + + +def test_detector_in_a_with_block_closes_the_client(mock_transport): + with VelaDetector.from_server(BASE_URL, model=MODEL) as detector: + detector.detect(SOURCES) + assert detector.model._http.is_closed + + +def test_close_on_a_local_model_does_nothing(): + VelaDetector(FakeVela()).close() + + +def test_api_key_with_a_given_http_client_raises_configuration_error(): + http = httpx.Client(base_url=BASE_URL, transport=httpx.MockTransport(_served(FakeVela()))) + with pytest.raises(ConfigurationError) as exc: + SystemOneClient(BASE_URL, model=MODEL, api_key=API_KEY, http_client=http) + assert (exc.value.code, exc.value.param) == ("invalid_config", "api_key") + assert API_KEY not in exc.value.message From 7ded6d1858b571bfd8ff6510e6316a84a8fff376 Mon Sep 17 00:00:00 2001 From: Suleyman Furkan Atas Date: Sun, 22 Nov 2026 15:18:09 +0100 Subject: [PATCH 32/60] feat: get triplets and fact-check results from RAGFactCheckerDetector.detect (#169) (#196) * feat: add RAGFactCheckerDetector.detect with injected fact checker and merge fix (#170) * feat: return triplets via include_detail and route predict* through detect (#171) --- lettucedetect/detectors/base.py | 16 +- lettucedetect/detectors/rag_fact_checker.py | 327 ++++++++++++--- tests/fixtures/golden/rag_basic_detailed.json | 16 +- ...d.json => rag_merge_overlap_detailed.json} | 12 +- ...pans.json => rag_merge_overlap_spans.json} | 6 +- ...ens.json => rag_merge_overlap_tokens.json} | 0 .../rag_single_word_match_detailed.json | 8 +- tests/test_golden_rag_fact_checker_pytest.py | 28 +- .../test_rag_fact_checker_detector_pytest.py | 394 ++++++++++++++++++ 9 files changed, 702 insertions(+), 105 deletions(-) rename tests/fixtures/golden/{rag_merge_overlap_text_shorter_than_offsets_detailed.json => rag_merge_overlap_detailed.json} (91%) rename tests/fixtures/golden/{rag_merge_overlap_text_shorter_than_offsets_spans.json => rag_merge_overlap_spans.json} (83%) rename tests/fixtures/golden/{rag_merge_overlap_text_shorter_than_offsets_tokens.json => rag_merge_overlap_tokens.json} (100%) create mode 100644 tests/test_rag_fact_checker_detector_pytest.py diff --git a/lettucedetect/detectors/base.py b/lettucedetect/detectors/base.py index 37926dd..8ffd6e9 100644 --- a/lettucedetect/detectors/base.py +++ b/lettucedetect/detectors/base.py @@ -117,9 +117,19 @@ def detect( ) result = self._detect(request, include_tokens=include_tokens, include_detail=include_detail) if min_score > 0.0: - result = result.model_copy( - update={"spans": [s for s in result.spans if s.score >= min_score]} - ) + keep = [span.score >= min_score for span in result.spans] + update: dict[str, object] = { + "spans": [span for span, kept in zip(result.spans, keep, strict=True) if kept] + } + if result.detail is not None and result.detail.span_triplets: + # span_triplets is parallel to spans, so it is filtered with them. + triplets = result.detail.span_triplets + update["detail"] = result.detail.model_copy( + update={ + "span_triplets": [t for t, kept in zip(triplets, keep, strict=True) if kept] + } + ) + result = result.model_copy(update=update) return result async def adetect( diff --git a/lettucedetect/detectors/rag_fact_checker.py b/lettucedetect/detectors/rag_fact_checker.py index c5b87d0..606b9c8 100644 --- a/lettucedetect/detectors/rag_fact_checker.py +++ b/lettucedetect/detectors/rag_fact_checker.py @@ -1,42 +1,236 @@ -"""Simple RAGFactChecker detector wrapper for lettuceDetect factory pattern.""" +"""RAGFactChecker detector: hallucinated spans from triplet fact checking.""" from __future__ import annotations +import logging +import threading +import time from typing import Any +from pydantic import ValidationError + from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import ConfigurationError, InvalidInputError, UpstreamError +from lettucedetect.detectors.types import ( + Chunk, + DetailedResult, + DetectedSpan, + Detection, + DetectRequest, + PromptInput, + ResultWarning, + SourcesInput, + Triplets, + Usage, +) +_LEGACY_FORMATS = ("tokens", "spans", "detailed") + +logger = logging.getLogger(__name__) -class RAGFactCheckerDetector(BaseDetector): - """Simple wrapper around RAGFactChecker for lettuceDetect's factory pattern. - This provides a minimal adapter between lettuceDetect's detector interface - and our clean RAGFactChecker wrapper. +class RAGFactCheckerDetector(BaseDetector): + """Detect hallucinations by extracting triplets and fact checking them against the sources. + + The span scores are fixed values, not model probabilities: 0.9 when a hallucinated triplet + is found in the answer as a phrase, 0.7 when only one of its words is found. A result with + spans carries a ``synthetic_score`` warning that says so. + + Pass ``fact_checker`` to use the detector without an API key, for example in tests:: + + detector = RAGFactCheckerDetector(fact_checker=my_fact_checker) + result = detector.detect(SourcesInput(sources=[...], answer="...")) + + :param openai_api_key: OpenAI API key; unused when ``fact_checker`` is passed. + :param model: OpenAI model (default ``"gpt-4o"``); also the ``model_id`` in ``usage``. + :param base_url: optional base URL of the API, for example ``"http://localhost:1234/v1"``. + :param temperature: sampling temperature (default ``0.0``). + :param fact_checker: an object with ``detect_hallucinations(context, answer, question)`` + (and ``detect_hallucinations_batch`` for the batch method). When passed, nothing is built + and the environment is not read. When omitted, ``RAGFactChecker`` is built from the + arguments above, for backward compatibility (it lives outside this package). + :param max_concurrency: the most ``detect``, ``adetect``, ``predict`` and ``predict_prompt`` + calls that run the fact checker at once on this instance (default 30). + :param kwargs: ignored, kept for backward compatibility. + :raises ConfigurationError: (``invalid_config``) ``max_concurrency`` is not an integer >= 1. """ + supports_tokens = False + supports_detail = True + def __init__( self, openai_api_key: str | None = None, model: str = "gpt-4o", base_url: str | None = None, temperature: float = 0.0, - **kwargs, - ): - """Initialize the RAGFactChecker detector. - - :param openai_api_key: OpenAI API key - :param model: OpenAI model to use (default: "gpt-4o") - :param base_url: Optional base URL for API (e.g., "http://localhost:1234/v1" for local servers) - :param temperature: Temperature for model sampling (default: 0.0 for deterministic outputs) - :param kwargs: Additional arguments (ignored for simplicity) - :return: RAGFactChecker instance + *, + fact_checker: Any = None, # noqa: ANN401 + max_concurrency: int = 30, + **kwargs: Any, # noqa: ANN401 + ) -> None: + """Build the detector; see the class docstring for the arguments.""" + if ( + isinstance(max_concurrency, bool) + or not isinstance(max_concurrency, int) + or max_concurrency < 1 + ): + raise ConfigurationError( + "max_concurrency must be an integer >= 1; pass for example max_concurrency=30.", + code="invalid_config", + param="max_concurrency", + ) + self.model_id = model + self.max_concurrency = max_concurrency + if fact_checker is None: + # Kept for backward compatibility; pass fact_checker= to skip building a client. + from lettucedetect.ragfactchecker import RAGFactChecker + + fact_checker = RAGFactChecker( + openai_api_key=openai_api_key, + model=model, + base_url=base_url, + temperature=temperature, + ) + self.rag = fact_checker + # The LLM calls happen inside the fact checker and can't be counted from outside, so the + # bound is on whole fact-check calls. + self._semaphore = threading.BoundedSemaphore(max_concurrency) + + def _detect( + self, request: DetectRequest, *, include_tokens: bool, include_detail: bool + ) -> Detection: + """Fact check the answer and return its hallucinated spans. + + :param request: the sources (or prompt) and the answer to check. + :param include_tokens: unused, ``detect`` rejects it (``supports_tokens`` is ``False``). + :param include_detail: whether to fill ``Detection.detail`` with the triplets, the + fact-check results and the source triplet of each span. + :returns: the detection result. + :raises UpstreamError: (``invalid_model_output``) ``include_detail`` is set and the fact + checker returned triplets or results of an unexpected shape. """ - from lettucedetect.ragfactchecker import RAGFactChecker + answer = request.answer + if isinstance(request, SourcesInput): + context = [chunk.text for chunk in request.sources] + question = request.question + else: + context = [request.prompt] + question = None + units = { + "sources": len(context), + "source_chars": sum(len(text) for text in context), + "answer_chars": len(answer), + } + + requested = time.perf_counter() + with self._semaphore: + started = time.perf_counter() + logger.debug( + "detect started: kind=%s sources=%d model_id=%s wait_ms=%.1f", + request.kind, + units["sources"], + self.model_id, + (started - requested) * 1000, + ) + result = self.rag.detect_hallucinations(context, answer, question) + check_ms = (time.perf_counter() - started) * 1000 - # Use our simple, clean wrapper internally - self.rag = RAGFactChecker( - openai_api_key=openai_api_key, model=model, base_url=base_url, temperature=temperature + raw_spans = self._convert_to_spans(answer, result) + spans = [ + DetectedSpan( + start=item["start"], end=item["end"], text=item["text"], score=item["confidence"] + ) + for item in raw_spans + ] + detail = self._detail(result, raw_spans) if include_detail else None + warnings = ( + [ + ResultWarning( + code="synthetic_score", + message=( + "Scores are fixed values (0.9 for a full match, 0.7 for a partial " + "match), not model probabilities." + ), + ) + ] + if spans + else [] ) + logger.debug("detect finished: spans=%d check_ms=%.1f", len(spans), check_ms) + return Detection( + spans=spans, + detail=detail, + usage=[Usage(model_id=self.model_id, model_version=None, units=units)], + warnings=warnings, + ) + + @staticmethod + def _detail(result: dict[str, Any], raw_spans: list[dict[str, Any]]) -> DetailedResult: + """Build the evidence of one fact check; ``span_triplets`` is parallel to the spans.""" + try: + return DetailedResult( + triplets=Triplets( + answer=result.get("answer_triplets", []), + context=result.get("context_triplets", []), + hallucinated=result.get("hallucinated_triplets", []), + ), + fact_check_results=result.get("fact_check_results", {}), + span_triplets=[item.get("triplet") for item in raw_spans], + ) + except ValidationError as exc: + raise UpstreamError( + "The fact checker returned triplets or results of an unexpected shape.", + code="invalid_model_output", + service="rag_fact_checker", + ) from exc + + @staticmethod + def _check_rag_arguments(output_format: str, min_confidence: float) -> None: + """Validate the arguments the ``predict*`` methods share.""" + if output_format not in _LEGACY_FORMATS: + raise InvalidInputError( + f"Invalid output format '{output_format}'. " + "RAGFactChecker supports 'tokens', 'spans', or 'detailed'", + code="unsupported_output_format", + param="output_format", + ) + if not 0.0 <= min_confidence <= 1.0: + raise InvalidInputError( + "min_confidence must be in [0, 1]; pass a value between 0.0 and 1.0.", + code="invalid_min_score", + param="min_confidence", + ) + + def _legacy_output( + self, request: DetectRequest, output_format: str, min_confidence: float + ) -> list[dict[str, Any]] | dict[str, Any]: + """Answer a ``predict*`` call with :meth:`detect`, in the legacy dict format.""" + detection = self.detect(request, include_detail=True) + detail = detection.detail + assert detail is not None # noqa: S101 - detect fills it when asked + if output_format == "tokens": + return self._convert_to_tokens( + request.answer, {"hallucinated_triplets": detail.triplets.hallucinated} + ) + spans = [ + { + "start": span.start, + "end": span.end, + "text": span.text, + "confidence": span.score, + "triplet": triplet, + } + for span, triplet in zip(detection.spans, detail.span_triplets, strict=True) + ] + if output_format == "detailed": + # Detailed output is not filtered by min_confidence. + return { + "spans": spans, + "triplets": detail.triplets.model_dump(), + "fact_check_results": dict(detail.fact_check_results), + } + return self._filter_spans_by_confidence(spans, output_format, min_confidence) def predict( self, @@ -47,7 +241,7 @@ def predict( min_confidence: float = 0.0, **kwargs, ) -> list[dict[str, Any]] | dict[str, Any]: - """Predict hallucinations using RAGFactChecker. + """Predict hallucinations using RAGFactChecker, through :meth:`detect`. :param context: List of context documents :param answer: Answer text to check for hallucinations @@ -59,33 +253,16 @@ def predict( :param kwargs: Additional arguments :return: List of predictions in lettuceDetect format, or dict for detailed format + :raises InvalidInputError: (``unsupported_output_format``) for an unknown + ``output_format``; (``invalid_min_score``) for ``min_confidence`` outside ``[0, 1]``. """ - if output_format not in ["tokens", "spans", "detailed"]: - raise ValueError( - f"Invalid output format '{output_format}'. " - "RAGFactChecker supports 'tokens', 'spans', or 'detailed'" - ) - self._validate_min_confidence(min_confidence) - - # Use our simple wrapper's detection method - result = self.rag.detect_hallucinations(context, answer, question) - - # Convert to lettuceDetect's expected format - if output_format == "detailed": - return { - "spans": self._convert_to_spans(answer, result), - "triplets": { - "answer": result.get("answer_triplets", []), - "context": result.get("context_triplets", []), - "hallucinated": result.get("hallucinated_triplets", []), - }, - "fact_check_results": result.get("fact_check_results", {}), - } - elif output_format == "spans": - spans = self._convert_to_spans(answer, result) - return self._filter_spans_by_confidence(spans, output_format, min_confidence) - else: # tokens - return self._convert_to_tokens(answer, result) + self._check_rag_arguments(output_format, min_confidence) + request = SourcesInput( + sources=[Chunk(id=str(i), text=text) for i, text in enumerate(context)], + answer=answer, + question=question, + ) + return self._legacy_output(request, output_format, min_confidence) def predict_prompt( self, @@ -93,11 +270,14 @@ def predict_prompt( answer: str, output_format: str = "tokens", min_confidence: float = 0.0, - ) -> list[dict[str, Any]]: - """Predict using a single prompt string as context.""" - return self.predict( - [prompt], answer, output_format=output_format, min_confidence=min_confidence - ) + ) -> list[dict[str, Any]] | dict[str, Any]: + """Predict using a single prompt string as context, through :meth:`detect`. + + :raises InvalidInputError: as :meth:`predict`. + """ + self._check_rag_arguments(output_format, min_confidence) + request = PromptInput(prompt=prompt, answer=answer) + return self._legacy_output(request, output_format, min_confidence) def predict_prompt_batch( self, @@ -106,10 +286,30 @@ def predict_prompt_batch( output_format: str = "tokens", min_confidence: float = 0.0, ) -> list[list[dict[str, Any]]]: - """Batch prediction using RAGFactChecker's batch processing.""" + """Batch prediction using RAGFactChecker's batch processing. + + :raises InvalidInputError: (``length_mismatch``) for lists of different lengths; + (``invalid_min_score``) for ``min_confidence`` outside ``[0, 1]``; + (``unsupported_output_format``) for anything but ``"tokens"`` or ``"spans"``. + """ if len(prompts) != len(answers): - raise ValueError("Number of prompts must match number of answers") - self._validate_min_confidence(min_confidence) + raise InvalidInputError( + "Number of prompts must match number of answers", + code="length_mismatch", + param="answers", + ) + if not 0.0 <= min_confidence <= 1.0: + raise InvalidInputError( + "min_confidence must be in [0, 1]; pass a value between 0.0 and 1.0.", + code="invalid_min_score", + param="min_confidence", + ) + if output_format not in ("tokens", "spans"): + raise InvalidInputError( + f"Unknown output format: {output_format}", + code="unsupported_output_format", + param="output_format", + ) contexts = [[prompt] for prompt in prompts] # Convert prompts to context lists rag_results = self.rag.detect_hallucinations_batch(contexts, answers) @@ -119,13 +319,11 @@ def predict_prompt_batch( for i, (answer, rag_result) in enumerate(zip(answers, rag_results)): if output_format == "tokens": converted = self._convert_to_tokens(answer, rag_result) - elif output_format == "spans": + else: # spans converted = self._convert_to_spans(answer, rag_result) converted = self._filter_spans_by_confidence( converted, output_format, min_confidence ) - else: - raise ValueError(f"Unknown output format: {output_format}") converted_results.append(converted) return converted_results @@ -215,10 +413,12 @@ def _convert_to_spans(self, answer: str, rag_result: dict[str, Any]) -> list[dic break # Merge overlapping spans - return self._merge_overlapping_spans(spans) + return self._merge_overlapping_spans(spans, answer) - def _merge_overlapping_spans(self, spans: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Merge overlapping spans to avoid duplicates.""" + def _merge_overlapping_spans( + self, spans: list[dict[str, Any]], answer: str + ) -> list[dict[str, Any]]: + """Merge overlapping spans to avoid duplicates; the merged text is cut from ``answer``.""" if not spans: return spans @@ -231,11 +431,12 @@ def _merge_overlapping_spans(self, spans: list[dict[str, Any]]) -> list[dict[str # Check if spans overlap if current["start"] <= last["end"]: - # Merge spans - extend the end and combine triplets + # Merge spans - extend the end + end = max(last["end"], current["end"]) merged[-1] = { "start": last["start"], - "end": max(last["end"], current["end"]), - "text": last["text"], # Keep original text + "end": end, + "text": answer[last["start"] : end], "confidence": max(last["confidence"], current["confidence"]), "triplet": last.get("triplet", current.get("triplet")), } diff --git a/tests/fixtures/golden/rag_basic_detailed.json b/tests/fixtures/golden/rag_basic_detailed.json index 799d091..892cde7 100644 --- a/tests/fixtures/golden/rag_basic_detailed.json +++ b/tests/fixtures/golden/rag_basic_detailed.json @@ -2,8 +2,8 @@ "predict": [ { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { @@ -49,8 +49,8 @@ }, { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { @@ -98,8 +98,8 @@ "predict_prompt": [ { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { @@ -145,8 +145,8 @@ }, { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json b/tests/fixtures/golden/rag_merge_overlap_detailed.json similarity index 91% rename from tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json rename to tests/fixtures/golden/rag_merge_overlap_detailed.json index 6eadfe1..37926c6 100644 --- a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_detailed.json +++ b/tests/fixtures/golden/rag_merge_overlap_detailed.json @@ -2,15 +2,15 @@ "predict": [ { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { "confidence": 0.9, "end": 20, "start": 0, - "text": "France", + "text": "France is 69 million", "triplet": [ "France", "is", @@ -56,15 +56,15 @@ "predict_prompt": [ { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { "confidence": 0.9, "end": 20, "start": 0, - "text": "France", + "text": "France is 69 million", "triplet": [ "France", "is", diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json b/tests/fixtures/golden/rag_merge_overlap_spans.json similarity index 83% rename from tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json rename to tests/fixtures/golden/rag_merge_overlap_spans.json index f426b23..ab9d482 100644 --- a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_spans.json +++ b/tests/fixtures/golden/rag_merge_overlap_spans.json @@ -5,7 +5,7 @@ "confidence": 0.9, "end": 20, "start": 0, - "text": "France", + "text": "France is 69 million", "triplet": [ "France", "is", @@ -20,7 +20,7 @@ "confidence": 0.9, "end": 20, "start": 0, - "text": "France", + "text": "France is 69 million", "triplet": [ "France", "is", @@ -35,7 +35,7 @@ "confidence": 0.9, "end": 20, "start": 0, - "text": "France", + "text": "France is 69 million", "triplet": [ "France", "is", diff --git a/tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json b/tests/fixtures/golden/rag_merge_overlap_tokens.json similarity index 100% rename from tests/fixtures/golden/rag_merge_overlap_text_shorter_than_offsets_tokens.json rename to tests/fixtures/golden/rag_merge_overlap_tokens.json diff --git a/tests/fixtures/golden/rag_single_word_match_detailed.json b/tests/fixtures/golden/rag_single_word_match_detailed.json index ccb4cf8..4e6d424 100644 --- a/tests/fixtures/golden/rag_single_word_match_detailed.json +++ b/tests/fixtures/golden/rag_single_word_match_detailed.json @@ -2,8 +2,8 @@ "predict": [ { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { @@ -53,8 +53,8 @@ "predict_prompt": [ { "fact_check_results": { - "0": "contradiction", - "1": "entailment" + "0": false, + "1": true }, "spans": [ { diff --git a/tests/test_golden_rag_fact_checker_pytest.py b/tests/test_golden_rag_fact_checker_pytest.py index 7c9fa86..beadf01 100644 --- a/tests/test_golden_rag_fact_checker_pytest.py +++ b/tests/test_golden_rag_fact_checker_pytest.py @@ -1,12 +1,8 @@ """Golden (characterization) tests pinning today's ``RAGFactCheckerDetector`` output. -The detector is built without its constructor (which needs an OpenAI key) and given a fake fact -checker that returns fixed triplets and results, so the tests are network-free. Recordings live in +The detector is given a fake fact checker that returns fixed triplets and results, so the tests +are network-free. Recordings live in ``tests/fixtures/golden/rag__.json``. - -``rag_merge_overlap_text_shorter_than_offsets_*`` records a defect: ``_merge_overlapping_spans`` -extends ``end`` but keeps the first span's ``text``, so ``text`` is shorter than ``end - start``. -The pull request that fixes it updates exactly those fixtures as an intended change. """ from __future__ import annotations @@ -27,7 +23,7 @@ def _result(hallucinated: list[list[str]]) -> dict: "answer_triplets": [["France", "population", "69 million"], ["Paris", "is", "capital"]], "context_triplets": [["France", "population", "67 million"]], "hallucinated_triplets": hallucinated, - "fact_check_results": {"0": "contradiction", "1": "entailment"}, + "fact_check_results": {0: False, 1: True}, } @@ -39,8 +35,8 @@ def _result(hallucinated: list[list[str]]) -> dict: ], # The fourth element is only found by the single-word fallback, so confidence is 0.7. "single_word_match": [(ANSWER_3, _result([["Barcelona", "north", "coast", "Madrid"]]))], - # Both triplets match at the same start; merging keeps the first, shorter, text. - "merge_overlap_text_shorter_than_offsets": [ + # Both triplets match at the same start; the merged text covers both. + "merge_overlap": [ (ANSWER_4, _result([["France", "is", "unknown"], ["France", "is", "69 million"]])) ], } @@ -63,9 +59,7 @@ def detect_hallucinations_batch(self, contexts, answers) -> list[dict]: def _detector(case: str) -> RAGFactCheckerDetector: - detector = RAGFactCheckerDetector.__new__(RAGFactCheckerDetector) # skip the API-key __init__ - detector.rag = FakeFactChecker(dict(CASES[case])) - return detector + return RAGFactCheckerDetector(fact_checker=FakeFactChecker(dict(CASES[case]))) def _record(case: str, output_format: str) -> dict: @@ -108,10 +102,8 @@ def test_single_word_match_has_lower_confidence(): assert [span["confidence"] for span in spans] == [0.7] -def test_merge_leaves_text_shorter_than_offsets(): - """Documents the defect the recording pins: merged ``text`` is shorter than its offsets.""" - spans = _detector("merge_overlap_text_shorter_than_offsets").predict( - ["c"], ANSWER_4, output_format="spans" - ) +def test_merged_text_equals_answer_between_offsets(): + """A merged span's ``text`` is the answer between its offsets.""" + spans = _detector("merge_overlap").predict(["c"], ANSWER_4, output_format="spans") assert len(spans) == 1 - assert len(spans[0]["text"]) < spans[0]["end"] - spans[0]["start"] + assert spans[0]["text"] == ANSWER_4[spans[0]["start"] : spans[0]["end"]] diff --git a/tests/test_rag_fact_checker_detector_pytest.py b/tests/test_rag_fact_checker_detector_pytest.py new file mode 100644 index 0000000..7d50bdd --- /dev/null +++ b/tests/test_rag_fact_checker_detector_pytest.py @@ -0,0 +1,394 @@ +"""Tests for ``RAGFactCheckerDetector.detect`` with an injected, network-free fact checker.""" + +from __future__ import annotations + +import asyncio +import threading +import time +from collections.abc import Callable +from unittest.mock import patch + +import pytest + +from lettucedetect.detectors.errors import ConfigurationError, InvalidInputError, UpstreamError +from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector +from lettucedetect.detectors.types import ( + Chunk, + DetailedResult, + PromptInput, + SourcesInput, + Triplets, +) +from tests.detector_contract import DetectorContract +from tests.test_golden_rag_fact_checker_pytest import ANSWER_4, CASES + +RAG_FACT_CHECKER = "lettucedetect.ragfactchecker.RAGFactChecker" + +ANSWER = ( + "The population of France is 69 million according to the report, " + "and Madrid is mentioned as the largest city in the region." +) +SOURCES = SourcesInput( + sources=[ + Chunk(id="s1", text="France has a population of about 67 million people."), + Chunk(id="s2", text="Paris is the capital and largest city of France."), + ], + answer=ANSWER, + question="How many people live in France?", +) +PROMPT = PromptInput( + prompt="Answer from the context: France has a population of about 67 million.", answer=ANSWER +) +# A phrase match ("69 million", 0.9) and a single-word fallback match ("Madrid", 0.7). +RESULT = { + "answer_triplets": [["France", "population", "69 million"]], + "context_triplets": [["France", "population", "67 million"]], + "hallucinated_triplets": [ + ["France", "population", "69 million"], + ["Barcelona", "north", "coast", "Madrid"], + ], + "fact_check_results": {0: False}, +} + + +class FakeFactChecker: + """Returns a fixed result per answer and records every call; never touches the network.""" + + def __init__(self, results: dict[str, dict], on_call: Callable[[], None] | None = None) -> None: + """Keep the results and the hook to call once per fact check.""" + self.results = results + self.on_call = on_call + self.calls: list[tuple[list[str], str, str | None]] = [] + self.thread_ids: list[int] = [] + + def detect_hallucinations(self, context, answer, question=None) -> dict: + """Return the fixed result for ``answer``.""" + self.calls.append((list(context), answer, question)) + self.thread_ids.append(threading.get_ident()) + if self.on_call: + self.on_call() + return self.results[answer] + + def detect_hallucinations_batch(self, contexts, answers) -> list[dict]: + """Return the fixed results for ``answers``, in order.""" + return [self.results[answer] for answer in answers] + + +def _detector(results: dict[str, dict] | None = None, **kwargs) -> RAGFactCheckerDetector: + fake = FakeFactChecker(results if results is not None else {ANSWER: RESULT}) + return RAGFactCheckerDetector(fact_checker=fake, **kwargs) + + +class TestRAGFactCheckerDetectorContract(DetectorContract): + """The detector contract holds with a fake fact checker.""" + + sources_request = SOURCES + prompt_request = PROMPT + + def make_detector(self, on_call=None): # noqa: D102 + return RAGFactCheckerDetector(fact_checker=FakeFactChecker({ANSWER: RESULT}, on_call)) + + +# -- constructor ----------------------------------------------------------------------------- + + +def test_injected_fact_checker_builds_nothing_and_reads_no_environment(monkeypatch): + """With ``fact_checker`` passed, RAGFactChecker is not built and no API key is needed.""" + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with patch(RAG_FACT_CHECKER, side_effect=AssertionError("RAGFactChecker was built")): + detector = _detector() + assert detector.detect(SOURCES).spans + + +def test_without_fact_checker_builds_rag_fact_checker_from_the_old_arguments(): + """Without ``fact_checker``, RAGFactChecker is built from the old arguments, as before.""" + with patch(RAG_FACT_CHECKER) as built: + detector = RAGFactCheckerDetector("key", "gpt-4o-mini", "http://local/v1", 0.2) + built.assert_called_once_with( + openai_api_key="key", model="gpt-4o-mini", base_url="http://local/v1", temperature=0.2 + ) + assert detector.rag is built.return_value + + +def test_model_id_is_model(): + """``model_id`` is the ``model`` argument.""" + assert _detector().model_id == "gpt-4o" + assert _detector(model="gpt-4o-mini").model_id == "gpt-4o-mini" + + +def test_max_concurrency_defaults_to_30(): + """The default bound on concurrent ``detect`` calls is 30.""" + assert _detector().max_concurrency == 30 + + +@pytest.mark.parametrize("value", [0, -1, 1.5, True, "2"]) +def test_invalid_max_concurrency_raises_configuration_error(value): + """``max_concurrency`` below 1 (or not an integer) raises ``ConfigurationError``.""" + with patch(RAG_FACT_CHECKER, side_effect=AssertionError("built before validating")): + with pytest.raises(ConfigurationError) as exc: + RAGFactCheckerDetector(max_concurrency=value) + assert exc.value.code == "invalid_config" + assert exc.value.param == "max_concurrency" + + +# -- detect ---------------------------------------------------------------------------------- + + +def test_detect_passes_context_question_and_answer_to_the_fact_checker(): + """Sources become the context list; a prompt becomes a one-item context without question.""" + detector = _detector() + detector.detect(SOURCES) + detector.detect(PROMPT) + assert detector.rag.calls == [ + ([c.text for c in SOURCES.sources], ANSWER, SOURCES.question), + ([PROMPT.prompt], ANSWER, None), + ] + + +def test_scores_are_0_9_for_a_full_match_and_0_7_for_a_partial_match(): + """The fixed scores of today's ``confidence`` are kept.""" + spans = _detector().detect(SOURCES).spans + assert {(s.text, s.score) for s in spans} == {("69 million", 0.9), ("Madrid", 0.7)} + + +def test_merged_span_text_equals_the_answer_between_its_offsets(): + """Overlapping matches merge into one span whose text covers the merged offsets.""" + detector = _detector(dict(CASES["merge_overlap"])) + spans = detector.detect(PromptInput(prompt="p", answer=ANSWER_4)).spans + assert len(spans) == 1 + assert spans[0].text == ANSWER_4[spans[0].start : spans[0].end] == "France is 69 million" + + +def test_one_synthetic_score_warning_when_there_are_spans(): + """A result with spans has exactly one ``synthetic_score`` warning.""" + warnings = _detector().detect(SOURCES).warnings + assert [w.code for w in warnings] == ["synthetic_score"] + + +def test_no_warning_when_there_are_no_spans(): + """A result without spans has no ``synthetic_score`` warning.""" + clean = {**RESULT, "hallucinated_triplets": []} + detection = _detector({ANSWER: clean}).detect(SOURCES) + assert detection.spans == [] + assert detection.warnings == [] + + +def test_min_score_filtering_keeps_the_warning_from_the_unfiltered_result(): + """``min_score`` drops low spans; the warning reports the scoring, so it stays.""" + detection = _detector().detect(SOURCES, min_score=0.8) + assert [s.score for s in detection.spans] == [0.9] + assert [w.code for w in detection.warnings] == ["synthetic_score"] + + +def test_usage_has_one_entry_with_sources_and_char_counts(): + """``usage`` has one entry: model id, no version, sources and character counts.""" + detector = _detector() + (usage,) = detector.detect(SOURCES).usage + assert usage.model_id == "gpt-4o" + assert usage.model_version is None + assert usage.units == { + "sources": 2, + "source_chars": sum(len(c.text) for c in SOURCES.sources), + "answer_chars": len(ANSWER), + } + (prompt_usage,) = detector.detect(PROMPT).usage + assert prompt_usage.units == { + "sources": 1, + "source_chars": len(PROMPT.prompt), + "answer_chars": len(ANSWER), + } + + +def test_include_detail_returns_triplets_results_and_a_triplet_per_span(): + """``include_detail=True`` returns the evidence; ``span_triplets`` is parallel to the spans.""" + detection = _detector().detect(SOURCES, include_detail=True) + assert detection.detail == DetailedResult( + triplets=Triplets( + answer=RESULT["answer_triplets"], + context=RESULT["context_triplets"], + hallucinated=RESULT["hallucinated_triplets"], + ), + fact_check_results={0: False}, + span_triplets=[ + ["France", "population", "69 million"], + ["Barcelona", "north", "coast", "Madrid"], + ], + ) + assert [s.text for s in detection.spans] == ["69 million", "Madrid"] + + +def test_without_include_detail_detail_is_none(): + """``detail`` is ``None`` unless asked for.""" + assert _detector().detect(SOURCES).detail is None + + +def test_min_score_keeps_span_triplets_parallel_to_spans(): + """Spans dropped by ``min_score`` take their source triplet with them.""" + detection = _detector().detect(SOURCES, min_score=0.8, include_detail=True) + assert [s.text for s in detection.spans] == ["69 million"] + assert detection.detail.span_triplets == [["France", "population", "69 million"]] + + +def test_malformed_fact_check_results_raise_upstream_error_only_with_detail(): + """A reply that does not fit ``DetailedResult`` raises ``UpstreamError``; spans still work.""" + malformed = {**RESULT, "fact_check_results": {"0": "contradiction"}} + detector = _detector({ANSWER: malformed}) + with pytest.raises(UpstreamError) as exc: + detector.detect(SOURCES, include_detail=True) + assert exc.value.code == "invalid_model_output" + assert detector.detect(SOURCES).spans + + +def test_include_tokens_raises_tokens_not_supported(): + """The detector has no token scores.""" + with pytest.raises(InvalidInputError) as exc: + _detector().detect(SOURCES, include_tokens=True) + assert exc.value.code == "tokens_not_supported" + assert exc.value.param == "include_tokens" + + +# -- legacy predict* methods ----------------------------------------------------------------- + + +@pytest.mark.parametrize("output_format", ["tokens", "spans", "detailed"]) +def test_predict_and_predict_prompt_go_through_detect(output_format): + """``predict`` and ``predict_prompt`` call ``detect`` once per call.""" + detector = _detector() + with patch.object(detector, "detect", wraps=detector.detect) as detect: + detector.predict(["context"], ANSWER, output_format=output_format) + detector.predict_prompt("prompt", ANSWER, output_format=output_format) + assert detect.call_count == 2 + + +def test_predict_spans_carry_the_source_triplet(): + """Legacy spans keep their ``triplet`` key.""" + spans = _detector().predict(["context"], ANSWER, output_format="spans") + assert [(s["text"], s["triplet"]) for s in spans] == [ + ("69 million", ["France", "population", "69 million"]), + ("Madrid", ["Barcelona", "north", "coast", "Madrid"]), + ] + + +@pytest.mark.parametrize( + ("kwargs", "code", "param"), + [ + ({"output_format": "bad"}, "unsupported_output_format", "output_format"), + ({"min_confidence": 1.5}, "invalid_min_score", "min_confidence"), + ({"min_confidence": -0.1}, "invalid_min_score", "min_confidence"), + ], +) +def test_predict_and_predict_prompt_raise_invalid_input_error(kwargs, code, param): + """Bad legacy arguments raise ``InvalidInputError`` before the fact checker runs.""" + detector = _detector() + for call in ( + lambda: detector.predict(["context"], ANSWER, **kwargs), + lambda: detector.predict_prompt("prompt", ANSWER, **kwargs), + ): + with pytest.raises(InvalidInputError) as exc: + call() + assert (exc.value.code, exc.value.param) == (code, param) + assert detector.rag.calls == [] + + +@pytest.mark.parametrize( + ("args", "kwargs", "code"), + [ + ((["p", "p"], [ANSWER]), {}, "length_mismatch"), + ((["p"], [ANSWER]), {"min_confidence": 2.0}, "invalid_min_score"), + ((["p"], [ANSWER]), {"output_format": "detailed"}, "unsupported_output_format"), + ], +) +def test_predict_prompt_batch_raises_invalid_input_error(args, kwargs, code): + """Bad batch arguments raise ``InvalidInputError`` before the fact checker runs.""" + detector = _detector() + with patch.object(detector.rag, "detect_hallucinations_batch") as batch: + with pytest.raises(InvalidInputError) as exc: + detector.predict_prompt_batch(*args, **kwargs) + assert exc.value.code == code + batch.assert_not_called() + + +def test_max_concurrency_bounds_concurrent_predict_calls(): + """``predict`` and ``predict_prompt`` share the bound through ``detect``.""" + lock = threading.Lock() + active = peak = 0 + + def count() -> None: + nonlocal active, peak + with lock: + active += 1 + peak = max(peak, active) + time.sleep(0.02) + with lock: + active -= 1 + + detector = RAGFactCheckerDetector( + fact_checker=FakeFactChecker({ANSWER: RESULT}, on_call=count), max_concurrency=1 + ) + threads = [ + threading.Thread(target=detector.predict, args=(["context"], ANSWER)) for _ in range(4) + ] + [ + threading.Thread(target=detector.predict_prompt, args=("prompt", ANSWER)) for _ in range(4) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert len(detector.rag.calls) == 8 + assert peak == 1 + + +# -- adetect and concurrency ----------------------------------------------------------------- + + +async def test_adetect_equals_detect_and_calls_the_fact_checker_from_a_worker_thread(): + """``adetect`` returns what ``detect`` returns, and runs the fact checker off the caller's thread.""" + detector = _detector() + result = await detector.adetect(SOURCES) + assert detector.rag.thread_ids[-1] != threading.get_ident() + assert result == detector.detect(SOURCES) + + +def test_a_failing_fact_check_frees_its_concurrency_slot(): + """An error from the fact checker releases the slot, so the next call still runs.""" + calls = 0 + + def fail_once() -> None: + nonlocal calls + calls += 1 + if calls == 1: + raise RuntimeError("fact checker failed") + + detector = RAGFactCheckerDetector( + fact_checker=FakeFactChecker({ANSWER: RESULT}, on_call=fail_once), max_concurrency=1 + ) + with pytest.raises(RuntimeError): + detector.detect(SOURCES) + assert detector.detect(SOURCES).spans + + +async def test_max_concurrency_bounds_concurrent_detect_and_adetect_calls(): + """With ``max_concurrency=2``, the fact checker never runs more than twice at once.""" + lock = threading.Lock() + active = peak = 0 + + def count() -> None: + nonlocal active, peak + with lock: + active += 1 + peak = max(peak, active) + time.sleep(0.03) + with lock: + active -= 1 + + detector = RAGFactCheckerDetector( + fact_checker=FakeFactChecker({ANSWER: RESULT}, on_call=count), max_concurrency=2 + ) + threads = [threading.Thread(target=detector.detect, args=(SOURCES,)) for _ in range(8)] + for thread in threads: + thread.start() + await asyncio.gather(*(detector.adetect(PROMPT) for _ in range(8))) + for thread in threads: + thread.join() + assert len(detector.rag.calls) == 16 + assert peak == 2 From 647ef06a198401988f34f640e1d2300cd02947c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20=C3=81d=C3=A1m?= Date: Sun, 22 Nov 2026 15:24:40 +0100 Subject: [PATCH 33/60] feat: raise typed errors from OpenAIClient and BedrockClient (#157) --- lettucedetect/detectors/llm_client.py | 84 +++++++++++++++++++++------ tests/test_llm_client_pytest.py | 83 ++++++++++++++++++++++++-- 2 files changed, 144 insertions(+), 23 deletions(-) diff --git a/lettucedetect/detectors/llm_client.py b/lettucedetect/detectors/llm_client.py index 220d5aa..bb42037 100644 --- a/lettucedetect/detectors/llm_client.py +++ b/lettucedetect/detectors/llm_client.py @@ -13,6 +13,8 @@ import os from abc import ABC, abstractmethod +from lettucedetect.detectors.errors import ConfigurationError, UpstreamError + logger = logging.getLogger(__name__) @@ -224,6 +226,16 @@ def complete( ... +def _openai_unavailable(reason: str) -> UpstreamError: + """Build the error for an OpenAI call that may succeed when retried.""" + return UpstreamError( + f"The OpenAI API did not answer: {reason}. Retry later.", + code="upstream_unavailable", + service="openai", + retryable=True, + ) + + class OpenAIClient(LLMClient): """LLM client backed by the OpenAI chat completions API.""" @@ -248,23 +260,51 @@ def complete( temperature: float, schema: dict, ) -> str: - """Run a completion via ``chat.completions`` with a strict JSON schema.""" - resp = self._client.chat.completions.create( - model=model, - messages=[ - {"role": "system", "content": system}, - {"role": "user", "content": user}, - ], - response_format={ - "type": "json_schema", - "json_schema": { - "name": "hallucination_detection", - "schema": schema, - "strict": True, + """Run a completion via ``chat.completions`` with a strict JSON schema. + + :raises ConfigurationError: (``authentication_failed``) the API key was rejected; + (``quota_exceeded``) the account has no quota left. + :raises UpstreamError: (``upstream_unavailable``) the request timed out, the connection + failed, the rate limit was hit or the server failed. + """ + import openai + + try: + resp = self._client.chat.completions.create( + model=model, + messages=[ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + response_format={ + "type": "json_schema", + "json_schema": { + "name": "hallucination_detection", + "schema": schema, + "strict": True, + }, }, - }, - temperature=temperature, - ) + temperature=temperature, + ) + except openai.AuthenticationError as exc: + raise ConfigurationError( + "The OpenAI API rejected the credentials; check the API key.", + code="authentication_failed", + ) from exc + except openai.RateLimitError as exc: + # OpenAI reports an exhausted quota as a 429 with this code; waiting does not fix it. + if exc.code == "insufficient_quota": + raise ConfigurationError( + "The OpenAI account has no quota left; check its plan and billing.", + code="quota_exceeded", + ) from exc + raise _openai_unavailable("the rate limit was hit") from exc + except openai.APITimeoutError as exc: + raise _openai_unavailable("the request timed out") from exc + except openai.APIConnectionError as exc: + raise _openai_unavailable("the connection failed") from exc + except openai.InternalServerError as exc: + raise _openai_unavailable("the server failed") from exc return resp.choices[0].message.content @@ -300,7 +340,10 @@ def complete( temperature: float, schema: dict, ) -> str: - """Run a completion via ``converse`` with a forced tool call for structured output.""" + """Run a completion via ``converse`` with a forced tool call for structured output. + + :raises UpstreamError: (``empty_response``) the reply has no tool call. + """ resp = self._client.converse( modelId=model, system=[{"text": system}], @@ -324,8 +367,11 @@ def complete( for block in resp["output"]["message"]["content"]: if "toolUse" in block: return json.dumps(block["toolUse"]["input"]) - logger.warning("Bedrock response contained no tool-use block; returning empty result") - return "" + raise UpstreamError( + "The Bedrock reply has no tool call; retry, or use a model that supports tool use.", + code="empty_response", + service="bedrock", + ) def make_llm_client(provider: str, **kwargs) -> LLMClient: diff --git a/tests/test_llm_client_pytest.py b/tests/test_llm_client_pytest.py index 3e4a315..6b2309d 100644 --- a/tests/test_llm_client_pytest.py +++ b/tests/test_llm_client_pytest.py @@ -13,9 +13,12 @@ import sys import types +import httpx +import openai import pytest from lettucedetect.datasets.taxonomy import CATEGORY_DEFINITIONS +from lettucedetect.detectors.errors import ConfigurationError, UpstreamError from lettucedetect.detectors.llm import LLMDetector from lettucedetect.detectors.llm_client import ( BedrockClient, @@ -640,6 +643,76 @@ def fake_create(**kwargs): assert json_schema["schema"] is PLAIN_SCHEMA +def _openai_status_error(cls: type, status: int, code: str | None = None) -> Exception: + """Build an OpenAI status error as the SDK does, from a response and its body.""" + response = httpx.Response(status, request=httpx.Request("POST", "http://test/v1")) + return cls("provider message", response=response, body={"code": code}) + + +_REQUEST = httpx.Request("POST", "http://test/v1") + +# (error raised by the SDK, expected class, expected code) +OPENAI_ERRORS = [ + ( + _openai_status_error(openai.AuthenticationError, 401), + ConfigurationError, + "authentication_failed", + ), + ( + _openai_status_error(openai.RateLimitError, 429, "insufficient_quota"), + ConfigurationError, + "quota_exceeded", + ), + ( + _openai_status_error(openai.RateLimitError, 429, "rate_limit_exceeded"), + UpstreamError, + "upstream_unavailable", + ), + (openai.APITimeoutError(request=_REQUEST), UpstreamError, "upstream_unavailable"), + (openai.APIConnectionError(request=_REQUEST), UpstreamError, "upstream_unavailable"), + ( + _openai_status_error(openai.InternalServerError, 500), + UpstreamError, + "upstream_unavailable", + ), +] + + +class TestOpenAIClientErrors: + """OpenAIClient.complete turns the SDK's errors into typed errors.""" + + @pytest.mark.parametrize(("raised", "expected", "code"), OPENAI_ERRORS) + def test_sdk_error_is_mapped_and_chained(self, raised, expected, code): + """Each SDK error class maps to its class and code, with the SDK error as the cause.""" + client = OpenAIClient(api_key="test-key") + + def fake_create(**kwargs): + raise raised + + client._client.chat.completions.create = fake_create + + with pytest.raises(expected) as exc: + client.complete("sys", "user", "gpt-test", 0.0, PLAIN_SCHEMA) + assert type(exc.value) is expected + assert exc.value.code == code + assert exc.value.__cause__ is raised + assert "provider message" not in str(exc.value) + + def test_other_sdk_errors_propagate(self): + """An SDK error that is neither of the above (a bad request) is raised as it is.""" + client = OpenAIClient(api_key="test-key") + raised = _openai_status_error(openai.BadRequestError, 400) + + def fake_create(**kwargs): + raise raised + + client._client.chat.completions.create = fake_create + + with pytest.raises(openai.BadRequestError) as exc: + client.complete("sys", "user", "gpt-test", 0.0, PLAIN_SCHEMA) + assert exc.value is raised + + def _make_bedrock_client_with_fake(fake_runtime) -> BedrockClient: """Build a BedrockClient bypassing __init__ (which imports boto3).""" client = BedrockClient.__new__(BedrockClient) @@ -705,10 +778,12 @@ def test_complete_with_text_block_before_tool_use(self): result = client.complete("s", "u", "m", 0.0, PLAIN_SCHEMA) assert json.loads(result) == {"hallucination_list": ["Y"]} - def test_complete_without_tool_use_returns_empty_string(self): - """complete() returns an empty string when no toolUse block is present.""" + def test_complete_without_tool_use_raises_empty_response(self): + """complete() raises UpstreamError (empty_response) when no toolUse block is present.""" response = {"output": {"message": {"content": [{"text": "no tool call here"}]}}} client = _make_bedrock_client_with_fake(_FakeBedrockRuntime(response)) - result = client.complete("s", "u", "m", 0.0, PLAIN_SCHEMA) - assert result == "" + with pytest.raises(UpstreamError) as exc: + client.complete("s", "u", "m", 0.0, PLAIN_SCHEMA) + assert exc.value.code == "empty_response" + assert "no tool call here" not in str(exc.value) From 66a1e79ca8ce2e7c7a139c6b9b47d40f8aa01067 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20=C3=81d=C3=A1m?= Date: Sun, 22 Nov 2026 15:28:59 +0100 Subject: [PATCH 34/60] feat: add LLMJudgeDetector with LLMJudgeConfig and visible failures (#158) --- lettucedetect/detectors/__init__.py | 3 + lettucedetect/detectors/_llm_shared.py | 176 +++++++ lettucedetect/detectors/llm_judge.py | 400 ++++++++++++++++ tests/test_llm_judge_detector_pytest.py | 590 ++++++++++++++++++++++++ 4 files changed, 1169 insertions(+) create mode 100644 lettucedetect/detectors/_llm_shared.py create mode 100644 lettucedetect/detectors/llm_judge.py create mode 100644 tests/test_llm_judge_detector_pytest.py diff --git a/lettucedetect/detectors/__init__.py b/lettucedetect/detectors/__init__.py index 11bb66c..4ea3d71 100644 --- a/lettucedetect/detectors/__init__.py +++ b/lettucedetect/detectors/__init__.py @@ -12,6 +12,7 @@ from lettucedetect.detectors.factory import make_detector as _make_detector from lettucedetect.detectors.file_cache import FileCache from lettucedetect.detectors.llm import LLMDetector +from lettucedetect.detectors.llm_judge import LLMJudgeConfig, LLMJudgeDetector from lettucedetect.detectors.rag_fact_checker import RAGFactCheckerDetector from lettucedetect.detectors.response_cache import ( InMemoryCache, @@ -49,6 +50,8 @@ "InMemoryCache", "InvalidInputError", "LLMDetector", + "LLMJudgeConfig", + "LLMJudgeDetector", "LettuceDetectDeprecationWarning", "LettuceDetectError", "PromptInput", diff --git a/lettucedetect/detectors/_llm_shared.py b/lettucedetect/detectors/_llm_shared.py new file mode 100644 index 0000000..e52a8b4 --- /dev/null +++ b/lettucedetect/detectors/_llm_shared.py @@ -0,0 +1,176 @@ +"""Steps shared by the LLM-backed detectors. + +Everything except :func:`complete` is a pure function: no client, no cache and no thread. +""" + +from __future__ import annotations + +import logging +import numbers +import re +import threading +from typing import Any + +from lettucedetect.datasets.taxonomy import CATEGORY_DEFINITIONS, SUBCATEGORY_DEFINITIONS +from lettucedetect.detectors.errors import UpstreamError +from lettucedetect.detectors.llm_client import LLMClient +from lettucedetect.detectors.types import DetectedSpan + +# The only logger that may carry customer text, the raw reply included. +content_logger = logging.getLogger("lettucedetect.content") + +Labels = dict[str, Any] +"""Label names mapped to their descriptions (``None`` or empty for a label without one).""" + + +def resolve_taxonomy( + include_taxonomy: bool | list[str] | dict[str, Any], +) -> tuple[Labels | None, Labels | None]: + """Turn the four ``include_taxonomy`` forms into category and subcategory labels. + + :param include_taxonomy: ``True`` for the unified taxonomy, a list of category names, a flat + ``{category: description}`` dict, or ``{"categories": {...}, "subcategories": {...}}``. + :returns: the categories and the subcategories, each ``None`` when there are none. + """ + if isinstance(include_taxonomy, bool): + if not include_taxonomy: + return None, None + return dict(CATEGORY_DEFINITIONS), dict(SUBCATEGORY_DEFINITIONS) + if isinstance(include_taxonomy, dict): + if ( + include_taxonomy + and set(include_taxonomy) <= {"categories", "subcategories"} + and all(isinstance(value, dict) for value in include_taxonomy.values()) + ): + return ( + dict(include_taxonomy.get("categories") or {}) or None, + dict(include_taxonomy.get("subcategories") or {}) or None, + ) + return dict(include_taxonomy) or None, None + return {name: CATEGORY_DEFINITIONS.get(name) for name in include_taxonomy} or None, None + + +def unparseable_response(what: str) -> UpstreamError: + """Build the error for a reply that does not have the expected JSON shape. + + :param what: the shape that was expected, without any text of the reply. + """ + return UpstreamError( + f"The LLM reply is not {what}. Retry, or use a model that follows the response schema.", + code="unparseable_response", + service="llm", + ) + + +def span_score(item: dict[str, Any]) -> float | None: + """Return the model's ``confidence`` of an item, or ``None`` if it is not a number in [0, 1].""" + confidence = item.get("confidence") + if ( + isinstance(confidence, numbers.Real) + and not isinstance(confidence, bool) + and 0.0 <= confidence <= 1.0 + ): + return float(confidence) + return None + + +def locate_items( + items: list[Any], answer: str, min_score: float = 0.0 +) -> tuple[list[dict[str, Any]], int, int]: + """Locate the items of a reply in the answer. + + An item is a string, or an object with ``text`` and optionally ``confidence``, ``reasoning``, + ``category``, ``subcategory`` and ``is_hallucination``. Each item takes the first verbatim + match that overlaps no earlier item. An item the model rejected (``is_hallucination`` is + false) or scored below ``min_score`` still takes its match, so a later repeated item keeps + its place, and is then left out. + + :param items: the items of the reply, in answer order. + :param answer: the answer the items were copied from. + :param min_score: leave out items whose ``confidence`` is below this value. + :returns: the located spans as dicts with ``start``, ``end``, ``text`` and the optional keys + the item had; the number of items without a free match; the number of malformed items. + """ + spans: list[dict[str, Any]] = [] + used: list[tuple[int, int]] = [] + not_found = 0 + malformed = 0 + for item in items: + text = item.get("text") if isinstance(item, dict) else item + if not isinstance(text, str) or not text: + malformed += 1 + continue + match = next( + ( + match + for match in re.finditer(re.escape(text), answer) + if not any(match.start() < end and start < match.end() for start, end in used) + ), + None, + ) + if match is None: + not_found += 1 + continue + used.append((match.start(), match.end())) + span: dict[str, Any] = {"start": match.start(), "end": match.end(), "text": text} + if isinstance(item, dict): + if item.get("is_hallucination") is False: + continue + score = span_score(item) + if score is not None and score < min_score: + continue + for key in ("confidence", "reasoning", "category", "subcategory"): + if key in item: + span[key] = item[key] + spans.append(span) + return spans, not_found, malformed + + +def to_detected_spans(spans: list[dict[str, Any]]) -> tuple[list[DetectedSpan], bool]: + """Turn located spans into ``DetectedSpan`` objects. + + :param spans: spans as :func:`locate_items` returns them. + :returns: the spans, and whether any of them had no usable ``confidence`` and scores 1.0. + """ + detected = [] + synthetic = False + for span in spans: + score = span_score(span) + synthetic = synthetic or score is None + labels = { + key: span[key] if isinstance(span.get(key), str) else None + for key in ("category", "subcategory", "reasoning") + } + detected.append( + DetectedSpan( + start=span["start"], + end=span["end"], + text=span["text"], + score=1.0 if score is None else score, + **labels, + ) + ) + return detected, synthetic + + +def complete( + client: LLMClient, + semaphore: threading.BoundedSemaphore, + *, + system: str, + user: str, + model: str, + temperature: float, + schema: dict[str, Any], +) -> str: + """Call the client while holding the detector's semaphore, and return the raw reply. + + The semaphore is held only for the client call and is released when the call returns or + raises. Errors of the client propagate unwrapped. + """ + with semaphore: + reply = client.complete( + system=system, user=user, model=model, temperature=temperature, schema=schema + ) + content_logger.debug("LLM reply: %s", reply) + return reply diff --git a/lettucedetect/detectors/llm_judge.py b/lettucedetect/detectors/llm_judge.py new file mode 100644 index 0000000..61ae2ca --- /dev/null +++ b/lettucedetect/detectors/llm_judge.py @@ -0,0 +1,400 @@ +"""Detector that asks an LLM, as a zero-shot or few-shot judge, which parts of an answer are hallucinated.""" + +from __future__ import annotations + +import json +import logging +import threading +from pathlib import Path +from string import Template +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator + +from lettucedetect.detectors._llm_shared import ( + Labels, + complete, + locate_items, + resolve_taxonomy, + to_detected_spans, + unparseable_response, +) +from lettucedetect.detectors.base import BaseDetector +from lettucedetect.detectors.errors import ConfigurationError +from lettucedetect.detectors.llm_client import LLMClient, build_hallucination_schema +from lettucedetect.detectors.prompt_utils import LANG_TO_PASSAGE, PROMPT_DIR, PromptUtils +from lettucedetect.detectors.response_cache import ResponseCache +from lettucedetect.detectors.types import ( + Detection, + DetectRequest, + ResultWarning, + SourcesInput, + Usage, +) + +logger = logging.getLogger(__name__) + +__all__ = ["LLMJudgeConfig", "LLMJudgeDetector"] + +_SYSTEM = "You are an expert in detecting hallucinations in LLM outputs." + +_RESPONSE_FORMAT = """**Return** a JSON object following *exactly* this schema + (no extra keys, no markdown, no code-block fences): + + `{"hallucination_list": ["substring1", "substring2", …]}` + + Each substring must be copied **verbatim** from the answer — an exact, + character-for-character match. List substrings in answer order and include a + repeated substring at most once per distinct occurrence. If none are found, + return `{"hallucination_list": []}`.""" + + +def fewshot_block(fewshot: list[dict[str, Any]]) -> str: + """Render the few-shot examples of the judge prompt. + + :param fewshot: examples with ``source``, ``answer`` and ``hallucination_list``. + :returns: the examples block, empty when there are no examples. + """ + lines = [] + for i, ex in enumerate(fewshot, 1): + lines.append( + f""" +{ex["source"]} +{ex["answer"]} +{{"hallucination_list": {json.dumps(ex["hallucination_list"], ensure_ascii=False)} }} +""" + ) + return "\n".join(lines) + + +def _label_lines(labels: Labels) -> str: + return "\n".join( + f' - "{name}": {desc}' if desc else f' - "{name}"' for name, desc in labels.items() + ) + + +def response_format_block( + include_reasoning: bool, categories: Labels | None, subcategories: Labels | None +) -> str: + """Compose the response-format instructions of the judge prompt for the enabled options. + + :param include_reasoning: whether the reply carries an analysis and per-span reasoning, + confidence and verdict. + :param categories: category labels, ``None`` for an untyped reply. + :param subcategories: subcategory labels, ``None`` for none. + :returns: the response-format block for the prompt template. + """ + if not include_reasoning and not categories: + return _RESPONSE_FORMAT + + example: dict = {"text": "substring1"} + notes = [ + '- "text" must be an exact substring of the answer and items must be listed in answer order.', + "- For repeated substrings, return at most one item per distinct occurrence.", + ] + if include_reasoning: + example["reasoning"] = "compare the span against the source before judging it" + notes.append( + '- "reasoning" comes first: weigh the span against the source before scoring or judging it.' + ) + if categories: + example["category"] = next(iter(categories)) + notes.append( + '- "category" classifies the hallucination as one of:\n' + _label_lines(categories) + ) + if subcategories: + example["subcategory"] = next(iter(subcategories)) + notes.append( + '- "subcategory" further classifies the span as one of:\n' + _label_lines(subcategories) + ) + if include_reasoning: + example["confidence"] = 0.95 + example["is_hallucination"] = True + notes.append( + '- "confidence" is your confidence between 0 and 1 that the span is hallucinated.' + ) + notes.append( + '- "is_hallucination" is your final verdict. You may list a span you suspect and, after ' + "reasoning, set this to false if you conclude it is actually supported; such spans are " + "discarded. Only spans you confirm should be true." + ) + notes.append( + "- Examples above may show only the hallucinated substrings; still return full objects." + ) + + example_json = json.dumps(example, ensure_ascii=False) + notes_block = "\n ".join(notes) + if include_reasoning: + schema_line = f'`{{"analysis": "...", "hallucination_list": [{example_json}, …]}}`' + notes_block = ( + '- "analysis" (written first) is a brief claim-by-claim comparison of the answer ' + "against the source; reason here before listing any spans.\n " + notes_block + ) + empty_line = 'return `{"analysis": "...", "hallucination_list": []}`' + else: + schema_line = f'`{{"hallucination_list": [{example_json}, …]}}`' + empty_line = 'return `{"hallucination_list": []}`' + return ( + "**Return** a JSON object following *exactly* this schema\n" + " (no extra keys, no markdown, no code-block fences):\n\n" + f" {schema_line}\n\n" + f" {notes_block}\n\n" + f" If none are found, {empty_line}." + ) + + +def parse_hallucination_list(reply: str) -> list[Any]: + """Parse a judge reply into its list of items. + + A ``hallucination_list`` that is a JSON-encoded string is decoded. + + :param reply: the raw reply of the client. + :returns: the items of ``hallucination_list``. + :raises UpstreamError: (``unparseable_response``) the reply is not JSON, has no + ``hallucination_list`` or has one that is not a list. + """ + try: + items = json.loads(reply)["hallucination_list"] + if isinstance(items, str): + items = json.loads(items) + except (json.JSONDecodeError, KeyError, TypeError) as exc: + raise unparseable_response("a JSON object with a hallucination_list") from exc + if not isinstance(items, list): + raise unparseable_response("a JSON object whose hallucination_list is a list") + return items + + +class LLMJudgeConfig(BaseModel): + """Options of a :class:`LLMJudgeDetector`. + + An invalid option raises :class:`ConfigurationError` with ``param`` set to + ``config.