Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ Each name below is deprecated since 0.3.0 and carries a `.. deprecated::` note i
- Errors and logging convention in `CONTRIBUTING.md`
- "Vela 2.0" section in the detection methods guide, with the reproduced Vela 2.0 0.3B results

## [Unreleased]

### Fixed
- Claude Code Stop hook: `--min-confidence` above `0.0` no longer drops every span in `--llm-model` mode. Unscored spans are kept, matching `BaseDetector._filter_spans_by_confidence` (#117)

## [0.2.3] - 2026-08-14

### Added
Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ LettuceDetect now detects hallucinations in **coding-agent** answers — grounde

- **Models:** `lettucedect-v2-qwen-2b` (generative, emits typed spans in one pass) and `lettucedect-v2-mmbert-base` (fast encoder) — a single model across code, tool output, and prose (including 14-language [PsiloQA](https://huggingface.co/datasets/s-nlp/PsiloQA) and [RAGTruth](https://aclanthology.org/2024.acl-long.585/)).
- **Benchmark:** a span-annotated code + tool-output + structured-document hallucination dataset — [KRLabsOrg/lettucedetect-code-hallucination](https://huggingface.co/datasets/KRLabsOrg/lettucedetect-code-hallucination).
- **Paper:** [Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents](https://aclanthology.org/2026.groundlm-1.44/) (GroundLM 2026 workshop at EMNLP 2026) · [arXiv:2607.00895](https://arxiv.org/abs/2607.00895)
- On code-agent answers, the fine-tuned 2B detector substantially outperforms the off-the-shelf detectors and large LLM judges we evaluated, which over-flag generated code:

<p align="center"><img src="https://github.com/KRLabsOrg/LettuceDetect/blob/main/assets/code_agent_comparison.png?raw=true" alt="Code-agent hallucination detection comparison" width="560"/></p>
Expand Down Expand Up @@ -181,6 +182,7 @@ For detailed performance metrics and evaluations of our models:
- [English model documentation](docs/README.md)
- [Multilingual model documentation](docs/EUROBERT.md)
- [Paper](https://arxiv.org/abs/2502.17125)
- [Paper: span-level detection over code, tool output and documents](https://aclanthology.org/2026.groundlm-1.44/) (GroundLM 2026 workshop at EMNLP 2026)
- [Model cards](https://huggingface.co/KRLabsOrg)

## How does it work?
Expand Down Expand Up @@ -384,3 +386,34 @@ Please cite the following paper if you use LettuceDetect in your work:
url={https://arxiv.org/abs/2502.17125},
}
```

For the models that cover code, tool output and documents, and the unified benchmark, please cite:

```bibtex
@inproceedings{kovacs-etal-2026-beyond,
title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents",
author = "Kov{\'a}cs, {\'A}d{\'a}m and
He, Bowei and
Liu, Xue and
Boros, Istv{\'a}n and
T{\'o}th, Szilveszter and
Recski, Gabor",
editor = "Wang, Yimu and
Choi, Yee Man and
Wu, Di and
Ouyang, Siqi and
Azadani, Mozhgan Nasr and
Fung, Yi R. (May)",
booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)",
month = oct,
year = "2026",
address = "Budapest, Hungary",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2026.groundlm-1.44/",
doi = "10.18653/2026.groundlm-1.44",
pages = "566--577",
ISBN = "979-8-89176-478-1"
}
```

Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895).
2 changes: 2 additions & 0 deletions docs/code-hallucination/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ character-level annotations marking the hallucinated spans.
Published as the `lettucedetect-code-agent` source of
[`KRLabsOrg/lettucedetect-code-hallucination`](https://huggingface.co/datasets/KRLabsOrg/lettucedetect-code-hallucination).

**Paper:** [Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents](https://aclanthology.org/2026.groundlm-1.44/) (GroundLM 2026 workshop at EMNLP 2026) · [arXiv:2607.00895](https://arxiv.org/abs/2607.00895)

## Why this dataset

Existing hallucination-detection datasets (RAGTruth, RAGBench) focus on **text** —
Expand Down
32 changes: 29 additions & 3 deletions docs/code-hallucination/model_card_v2_mmbert_base.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,35 @@ spans, then type each span with the label-conditioned taxonomy head (see

## Citing

```bibtex
@inproceedings{kovacs-etal-2026-beyond,
title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents",
author = "Kov{\'a}cs, {\'A}d{\'a}m and
He, Bowei and
Liu, Xue and
Boros, Istv{\'a}n and
T{\'o}th, Szilveszter and
Recski, Gabor",
editor = "Wang, Yimu and
Choi, Yee Man and
Wu, Di and
Ouyang, Siqi and
Azadani, Mozhgan Nasr and
Fung, Yi R. (May)",
booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)",
month = oct,
year = "2026",
address = "Budapest, Hungary",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2026.groundlm-1.44/",
doi = "10.18653/2026.groundlm-1.44",
pages = "566--577",
ISBN = "979-8-89176-478-1"
}
```

Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). LettuceDetect itself:

```bibtex
@article{Kovacs2025LettuceDetect,
title={LettuceDetect: A Hallucination Detection Framework for RAG Applications},
Expand All @@ -167,6 +196,3 @@ spans, then type each span with the label-conditioned taxonomy head (see
year={2025}
}
```

*A dedicated paper for the unified code+prose benchmark and the v2 models is in
preparation; this card will be updated with its citation on release.*
32 changes: 29 additions & 3 deletions docs/code-hallucination/model_card_v2_qwen.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,35 @@ near chance) because a generated code patch is not literally present in the cont

## Citing

```bibtex
@inproceedings{kovacs-etal-2026-beyond,
title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents",
author = "Kov{\'a}cs, {\'A}d{\'a}m and
He, Bowei and
Liu, Xue and
Boros, Istv{\'a}n and
T{\'o}th, Szilveszter and
Recski, Gabor",
editor = "Wang, Yimu and
Choi, Yee Man and
Wu, Di and
Ouyang, Siqi and
Azadani, Mozhgan Nasr and
Fung, Yi R. (May)",
booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)",
month = oct,
year = "2026",
address = "Budapest, Hungary",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2026.groundlm-1.44/",
doi = "10.18653/2026.groundlm-1.44",
pages = "566--577",
ISBN = "979-8-89176-478-1"
}
```

Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). LettuceDetect itself:

```bibtex
@article{Kovacs2025LettuceDetect,
title={LettuceDetect: A Hallucination Detection Framework for RAG Applications},
Expand All @@ -280,6 +309,3 @@ near chance) because a generated code patch is not literally present in the cont
year={2025}
}
```

*A dedicated paper for the unified code+prose benchmark and the v2 models is in
preparation; this card will be updated with its citation on release.*
29 changes: 29 additions & 0 deletions docs/code-hallucination/model_card_v2_taxonomy_head.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,35 @@ Wikipedia, plus RAGTruth and 14-language PsiloQA.

## Citing

```bibtex
@inproceedings{kovacs-etal-2026-beyond,
title = "Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents",
author = "Kov{\'a}cs, {\'A}d{\'a}m and
He, Bowei and
Liu, Xue and
Boros, Istv{\'a}n and
T{\'o}th, Szilveszter and
Recski, Gabor",
editor = "Wang, Yimu and
Choi, Yee Man and
Wu, Di and
Ouyang, Siqi and
Azadani, Mozhgan Nasr and
Fung, Yi R. (May)",
booktitle = "Proceedings of the 1st Workshop on Grounding Language Models: Learning Faithfully and Efficiently ({G}round{LM} 2026)",
month = oct,
year = "2026",
address = "Budapest, Hungary",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2026.groundlm-1.44/",
doi = "10.18653/2026.groundlm-1.44",
pages = "566--577",
ISBN = "979-8-89176-478-1"
}
```

Also on arXiv: [2607.00895](https://arxiv.org/abs/2607.00895). LettuceDetect itself:

```bibtex
@article{Kovacs2025LettuceDetect,
title={LettuceDetect: A Hallucination Detection Framework for RAG Applications},
Expand Down
14 changes: 14 additions & 0 deletions lettucedetect/detectors/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,20 @@ def _validate_min_confidence(min_confidence: float) -> None:
if not 0.0 <= min_confidence <= 1.0:
raise ValueError(f"min_confidence must be in [0, 1], got {min_confidence}")

@staticmethod
def _validate_batch_lengths(prompts: list[str], answers: list[str]) -> None:
"""Validate that ``prompts`` and ``answers`` have the same length.

:param prompts: The prompt strings of the batch.
:param answers: The answer strings of the batch.
:raises ValueError: If ``len(prompts) != len(answers)``.
"""
if len(prompts) != len(answers):
raise ValueError(
"Number of prompts must match number of answers, "
f"got {len(prompts)} prompts and {len(answers)} answers"
)

@staticmethod
def _filter_spans_by_confidence(
result: list, output_format: str, min_confidence: float
Expand Down
3 changes: 1 addition & 2 deletions lettucedetect/detectors/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,7 @@ def predict_prompt_batch(
:returns: List of prediction lists, one per input pair.
:raises ValueError: If ``len(prompts) != len(answers)``.
"""
if len(prompts) != len(answers):
raise ValueError("Number of prompts must match number of answers")
self._validate_batch_lengths(prompts, answers)
if not prompts:
return []
if output_format not in ("tokens", "spans"):
Expand Down
2 changes: 1 addition & 1 deletion lettucedetect/integrations/claude_code/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ found the agent receives them and revises.
| `--llm-model ID` | Generative detector or LLM judge; use `KRLabsOrg/lettucedect-v2-qwen-2b` for typed spans in one pass |
| `--llm-base-url URL` | OpenAI-compatible endpoint for `--llm-model` (e.g. `vllm serve KRLabsOrg/lettucedect-v2-qwen-2b`) |
| `--context-file F` | Grounding passage file, repeatable; default `context.md` |
| `--min-confidence X` | Report only spans at or above this confidence |
| `--min-confidence X` | Report only spans at or above this confidence; spans the detector did not score (every span in `--llm-model` mode) are always reported |

Models: `KRLabsOrg/lettucedect-base-modernbert-en-v1` for prose RAG answers;
`KRLabsOrg/lettucedect-v2-mmbert-base` plus
Expand Down
10 changes: 8 additions & 2 deletions lettucedetect/integrations/claude_code/check_answer.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,11 @@ def main(argv: list[str] | None = None) -> int:
"--min-confidence",
type=float,
default=0.0,
help="Report only spans at or above this confidence (default 0.0)",
help=(
"Report only spans at or above this confidence (default 0.0). "
"Applies to scored spans only; spans the detector did not score "
"(every span in --llm-model mode) are always reported."
),
)
args = parser.parse_args(argv)

Expand Down Expand Up @@ -231,7 +235,9 @@ def main(argv: list[str] | None = None) -> int:
flagged = [
s
for s in spans
if (s.get("confidence", s.get("hallucination_score")) or 0.0) >= args.min_confidence
if args.min_confidence <= 0.0
or s.get("confidence", s.get("hallucination_score")) is None
or s.get("confidence", s.get("hallucination_score")) >= args.min_confidence
]
if not flagged:
return 0
Expand Down
75 changes: 75 additions & 0 deletions tests/test_claude_code_hook_pytest.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,81 @@ def test_min_confidence_filters(self, tmp_path):
)
assert code == 0

def test_min_confidence_keeps_unscored_spans(self, tmp_path, capsys):
"""Test min confidence keeps unscored spans."""
ctx = self.make_context(tmp_path)
code = run_main(
["--model-path", "stub", "--context-file", ctx, "--min-confidence", "0.5"],
{"transcript_path": str(FIXTURE)},
spans=[
{"text": "69 million", "hallucination_score": None},
{"text": "wrong version", "start": 0, "end": 13},
],
)
assert code == 2
captured = capsys.readouterr()
assert "69 million" in captured.err
assert "wrong version" in captured.err

def test_min_confidence_mixes_scored_and_unscored(self, tmp_path, capsys):
"""Test min confidence keeps unscored spans and drops scored ones."""
ctx = self.make_context(tmp_path)
code = run_main(
["--model-path", "stub", "--context-file", ctx, "--min-confidence", "0.5"],
{"transcript_path": str(FIXTURE)},
spans=[
{"text": "low confidence", "confidence": 0.1},
{"text": "native typed span", "category": "unsupported_addition"},
{"text": "high confidence", "confidence": 0.9},
],
)
assert code == 2
err = capsys.readouterr().err
assert "low confidence" not in err
assert "native typed span" in err
assert "high confidence" in err

def test_llm_mode_unscored_spans_reported_above_threshold(self, tmp_path, capsys):
"""Test llm mode unscored spans reported above threshold."""
ctx = self.make_context(tmp_path)
seen = {}

class StubDetector:
"""Stub LLM detector returning native-path spans without confidence."""

def __init__(self, **kwargs):
seen.update(kwargs)

def predict(self, **kwargs):
return [
{
"text": "added retry logic",
"start": 0,
"end": 19,
"category": "unsupported_addition",
}
]

with (
patch("sys.stdin", io.StringIO(json.dumps({"transcript_path": str(FIXTURE)}))),
patch("lettucedetect.models.inference.HallucinationDetector", StubDetector),
):
code = main(
[
"--llm-model",
"KRLabsOrg/lettucedect-v2-qwen-2b",
"--llm-base-url",
"http://localhost:8001/v1",
"--context-file",
ctx,
"--min-confidence",
"0.5",
]
)
assert seen["base_url"] == "http://localhost:8001/v1"
assert code == 2
assert "added retry logic" in capsys.readouterr().err

def test_invalid_stdin_exits_0(self):
"""Test invalid stdin exits 0."""
with patch("sys.stdin", io.StringIO("not json")):
Expand Down
17 changes: 17 additions & 0 deletions tests/test_inference_pytest.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,23 @@ def test_filter_keeps_spans_without_confidence(self):
assert BaseDetector._filter_spans_by_confidence(spans, "spans", 0.9) == spans


class TestBatchLengthValidation:
"""Unit tests for the shared BaseDetector._validate_batch_lengths helper."""

def test_mismatch_message_shows_both_lengths(self):
"""A length mismatch raises a ValueError that shows the two lengths."""
with pytest.raises(ValueError, match="got 2 prompts and 1 answers"):
BaseDetector._validate_batch_lengths(["p1", "p2"], ["a1"])

@pytest.mark.parametrize(
("prompts", "answers"),
[([], []), (["p1"], ["a1"]), (["p1", "p2"], ["a1", "a2"])],
)
def test_equal_lengths_raise_no_error(self, prompts, answers):
"""The helper accepts equal lengths, including two empty lists."""
BaseDetector._validate_batch_lengths(prompts, answers)


class TestTransformerMinConfidence:
"""min_confidence behaviour wired through TransformerDetector."""

Expand Down
Loading
Loading