Evaluate LLM Output Quality and Build a Groundedness Scorer
Machine LearningModel answerLast updated
Design a full LLM evaluation system covering metrics, A/B comparison, hallucination detection, and a Python groundedness scorer that flags unsupported sentences.
You are building a retrieval-augmented generation (RAG) feature that produces answers grounded in retrieved document passages. Your task is to think through how to evaluate that feature rigorously, and then implement a small scoring component.
Answer the discussion parts as you would in a technical conversation, then write the code.
Questions worth clarifying before you start
- Does the model draw only from supplied passages, only from parametric knowledge, or a mix? The answer determines what "hallucination" means and what it can be checked against.
- Is a reference answer set available, or does scoring have to be reference-free?
- Is hallucination detection online (blocking bad responses before the user sees them) or offline (batch evaluation)? The latency and cost budget differs enormously.
- What happens downstream when a response is flagged — suppress it, retry, show a warning, or just log?
Part 1 — Measuring whether the feature is working
How would you decide whether the LLM feature is performing well today, and whether a candidate prompt or model upgrade is actually better than what is live?
Your answer should address:
- The quality dimensions that matter for this task (beyond just latency and cost)
- How you build, version, and maintain an evaluation set, and why hard or edge-case examples belong in it
- How individual responses are scored, and how you validate the scorer itself
- How you turn per-example scores into a trustworthy comparison between two versions
Part 2 — Finding hallucinations
Define what kinds of hallucination are relevant for a context-grounded Q&A feature, describe at least three detection approaches, and explain how you would evaluate the detector itself.
Your answer should address:
- A precise definition of the hallucination types that matter here (distinguishing context-grounded from knowledge-only failures)
- The trade-offs among detection approaches: cost, latency, recall, and failure modes
- How you measure whether the detector is doing its job (its own evaluation)
- How the product should respond when a response is flagged
Part 3 — Implement a groundedness scorer
Implement the following function:
from typing import Callable
def score_groundedness(
answer: str,
contexts: list[str],
support_fn: Callable[[str, str], float],
threshold: float = 0.5,
) -> dict:
...
Contract:
support_fn(context, claim)returns a float in[0, 1]representing how strongly one passage supports one claim. Treat it as an expensive black box (an entailment model or a judge-LLM call in production).- Split
answerinto sentences; each sentence is one claim. A punctuation-based splitter is fine if you note its limitations. - A sentence's support score is the maximum of
support_fnacross all passages. Its best passage is the index that achieves that maximum (lowest index on ties). It is "supported" if its score is at leastthreshold. - Return a dict with:
sentences: a list of per-sentence records, each containing the sentence text, its support score, the best passage index, and a supported flaggroundedness: fraction of sentences that are supported (answer-level aggregate)has_unsupported: whether any sentence is unsupported
- Document your chosen behavior for: empty answer, empty context list, threshold outside
[0, 1], and scores outside[0, 1].
Then implement:
def evaluate_dataset(
examples: list[tuple[str, list[str]]],
support_fn: Callable[[str, str], float],
threshold: float = 0.5,
) -> dict:
...
This takes a list of (answer, contexts) pairs and returns the mean groundedness and the hallucination rate (share of answers that contain at least one unsupported sentence).
Your answer should also cover:
- The total number of
support_fncalls and strategies to reduce it - At least two tests
- Honest limitations of sentence-level checking
Hints
Hint 1
For Part 1, think about what a user actually experiences as 'bad' — faithfulness, completeness, coherence — and note that LLM judges need their own validation against human labels before you can trust them as scorers.
Hint 2
For Part 2, layer your detection methods by cost: a fast lexical or embedding check can filter easy cases before you spend tokens on an entailment or judge-LLM call. The detector is itself a model, so precision/recall at a chosen threshold matters.
Hint 3
For Part 3, the sentence loop is O(S × C) support_fn calls. To reduce cost, consider early-exit once a sentence clears the threshold, batch calls where the API allows it, and caching identical (context, claim) pairs across a dataset run.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Measuring LLM performance
Quality dimensions. For a RAG Q&A feature the dimensions that matter most are faithfulness (does the answer contradict the passages?), answer completeness (does it cover what the passages say about the question?), and fluency. Latency (p50/p95) and cost per query are infrastructure concerns that sit alongside quality, not instead of it.
Building an evaluation set. Start with a random sample of real queries once the feature is live; before launch, use representative synthetic queries plus expert-written ones that target known failure modes (long contexts, conflicting passages, questions with no answer in the docs). Version the eval set in the same repo as the prompt. Refresh it when the query distribution drifts — stale evals give false confidence. Hard cases (short passages, ambiguous questions, multi-hop reasoning) should be over-represented; they are where versions actually diverge.
Scoring. If reference answers exist, use ROUGE/BERTScore as cheap baselines, then augment with an LLM judge prompted to rate faithfulness and completeness on a 1–5 scale. LLM judges are fast and correlate well with human ratings, but they have their own biases (length, confidence-sounding text). Always run a calibration pass: compare judge scores to human labels on 100–200 examples and measure Pearson/Spearman correlation and per-category agreement. If correlation is below ~0.7, the judge is not reliable enough to drive decisions on its own.
Comparing two versions. Compute the metric distribution per example, then run a paired test (Wilcoxon signed-rank or a bootstrap confidence interval) because the same inputs hit both versions. Report the effect size, not just the p-value. Sanity-check for regression on the hard-case slice even when aggregate numbers improve. A difference under ~2–3 percentage points on a few hundred examples usually isn't actionable.
Part 2 — Detecting hallucinations
Types that matter here. In a context-grounded system there are two distinct failure modes: extrinsic hallucinations, where the answer asserts something not supported by any passage, and intrinsic contradictions, where the answer directly contradicts a passage. A third type — fabricated entities or numbers not present in the passages — is a specific sub-case of extrinsic and tends to be the most harmful.
Detection methods (layered by cost).
- Lexical overlap (cheapest). Check whether named entities or numbers in the answer appear in the passages. Fast, zero extra LLM calls, but misses paraphrase and inferences. Good as a pre-filter.
- Embedding similarity. Split the answer into sentences, embed each alongside passage chunks, and flag sentences whose cosine similarity to all passages falls below a threshold. Adds one embedding call per sentence, sub-millisecond at scale. Blind spot: semantic similarity is not entailment.
- Entailment model. Run an NLI model (e.g., DeBERTa fine-tuned on NLI) with the passage as premise and each answer sentence as hypothesis. Good recall, runs locally, ~10–50 ms per call, but requires hosting a model and can be thrown off by long premises.
- Judge-LLM (most expensive). Prompt an LLM with the passages and the full answer, asking it to identify unsupported claims and explain why. Best precision and coverage, but costs tokens and adds latency. Suitable offline; only feasible online with careful caching.
Evaluating the detector. Build a labeled set of (answer, passages, supported/unsupported) pairs covering both types of hallucination. Measure precision, recall, and F1 at several thresholds. Choose the operating point by what the product tolerates: a low-latency feature might prefer higher precision (fewer false blocks), while a high-stakes product prefers high recall (catch everything, accept some false positives). Track calibration — does a score of 0.7 actually correspond to ~70% probability of support?
Product response. Blocking and regenerating adds latency and cost; it's worth it for high-stakes answers. Adding a UI warning ("This answer may not be fully supported") is lower cost and keeps the user informed. Logging everything is a minimum baseline and feeds back into the eval set.
Part 3 — Groundedness scorer
Design decisions and edge-case contract
- Empty answer: return
sentences=[],groundedness=1.0(vacuously all zero sentences are supported),has_unsupported=False. - Empty context list: every sentence gets
support=0.0,best_passage_idx=None,supported=False(nothing to support them). - Threshold outside
[0, 1]: raiseValueError. - Score outside
[0, 1]: raiseValueError(the support_fn contract is violated; fail loudly rather than silently clamp).
Call count. For S sentences and C passages, the naive implementation makes S × C calls. Reducing strategies: early-exit once a sentence reaches score 1.0 (or clears the threshold if downstream logic only needs the binary flag), cache (context, claim) pairs when the same contexts repeat across a dataset, and batch calls if the backing API supports it.
Code
from __future__ import annotations
import re
from typing import Callable
def _split_sentences(text: str) -> list[str]:
"""
Split on sentence-ending punctuation followed by whitespace or end-of-string.
Limitation: fails on abbreviations ("Dr. Smith"), ellipses, and
non-Western punctuation. A production splitter should use spaCy or NLTK.
"""
raw = re.split(r"(?<=[.!?])\s+", text.strip())
return [s for s in raw if s]
def score_groundedness(
answer: str,
contexts: list[str],
support_fn: Callable[[str, str], float],
threshold: float = 0.5,
) -> dict:
"""
Score how well each sentence in `answer` is supported by `contexts`.
Args:
answer: The model-generated answer to evaluate.
contexts: Passages the answer should be grounded in.
support_fn: Callable(context, claim) -> float in [0, 1].
Treated as an expensive black box; called at most
len(sentences) * len(contexts) times.
threshold: Minimum support score for a sentence to be considered
supported. Must be in [0, 1].
Returns:
{
"sentences": [
{
"text": str,
"support": float, # max over passages; 0.0 if no contexts
"best_passage_idx": int | None,
"supported": bool,
},
...
],
"groundedness": float, # fraction of supported sentences; 1.0 if empty
"has_unsupported": bool,
}
Raises:
ValueError: if threshold is outside [0, 1], or if support_fn returns
a value outside [0, 1].
"""
if not 0.0 <= threshold <= 1.0:
raise ValueError(f"threshold must be in [0, 1], got {threshold}")
if not answer.strip():
return {"sentences": [], "groundedness": 1.0, "has_unsupported": False}
sentences = _split_sentences(answer)
results = []
for sentence in sentences:
if not contexts:
results.append(
{
"text": sentence,
"support": 0.0,
"best_passage_idx": None,
"supported": False,
}
)
continue
best_score = -1.0
best_idx = 0
for idx, ctx in enumerate(contexts):
score = support_fn(ctx, sentence)
if not 0.0 <= score <= 1.0:
raise ValueError(
f"support_fn returned {score!r} for passage {idx}; "
"expected a value in [0, 1]."
)
# Strict > preserves lowest-index tie-break
if score > best_score:
best_score = score
best_idx = idx
results.append(
{
"text": sentence,
"support": best_score,
"best_passage_idx": best_idx,
"supported": best_score >= threshold,
}
)
supported_count = sum(1 for r in results if r["supported"])
groundedness = supported_count / len(results)
return {
"sentences": results,
"groundedness": groundedness,
"has_unsupported": supported_count < len(results),
}
def evaluate_dataset(
examples: list[tuple[str, list[str]]],
support_fn: Callable[[str, str], float],
threshold: float = 0.5,
) -> dict:
"""
Aggregate groundedness metrics over a dataset.
Args:
examples: List of (answer, contexts) pairs.
support_fn: Same contract as in score_groundedness.
threshold: Same contract as in score_groundedness.
Returns:
{
"mean_groundedness": float, # average per-answer groundedness
"hallucination_rate": float, # share of answers with >= 1 unsupported sentence
}
Returns {"mean_groundedness": 0.0, "hallucination_rate": 0.0} for an empty dataset.
"""
if not examples:
return {"mean_groundedness": 0.0, "hallucination_rate": 0.0}
groundedness_scores = []
hallucinated = 0
for answer, contexts in examples:
result = score_groundedness(answer, contexts, support_fn, threshold)
groundedness_scores.append(result["groundedness"])
if result["has_unsupported"]:
hallucinated += 1
return {
"mean_groundedness": sum(groundedness_scores) / len(groundedness_scores),
"hallucination_rate": hallucinated / len(examples),
}
Tests
def test_fully_supported():
# Every sentence scores above threshold; groundedness should be 1.0
result = score_groundedness(
answer="The sky is blue. Water is wet.",
contexts=["The sky is blue and water is wet."],
support_fn=lambda ctx, claim: 0.9,
threshold=0.5,
)
assert result["groundedness"] == 1.0
assert not result["has_unsupported"]
assert all(s["supported"] for s in result["sentences"])
def test_tie_break_lowest_index():
# Two passages return the same score; best_passage_idx must be 0
result = score_groundedness(
answer="Paris is in France.",
contexts=["Paris is the capital of France.", "Paris is in France."],
support_fn=lambda ctx, claim: 0.8,
threshold=0.5,
)
assert result["sentences"][0]["best_passage_idx"] == 0
def test_empty_answer():
result = score_groundedness("", ["some context"], lambda c, x: 0.9)
assert result == {"sentences": [], "groundedness": 1.0, "has_unsupported": False}
def test_empty_contexts():
result = score_groundedness("The sky is blue.", [], lambda c, x: 1.0)
assert result["groundedness"] == 0.0
assert result["sentences"][0]["best_passage_idx"] is None
def test_invalid_threshold():
import pytest
with pytest.raises(ValueError):
score_groundedness("hello.", ["ctx"], lambda c, x: 0.5, threshold=1.5)
Limitations worth acknowledging
- Sentence splitting is fragile. Abbreviations, bullet points, and dialogue break the regex. Use a proper tokenizer in production.
- Sentences aren't always independent claims. "She said it was fine" is meaningless without the preceding sentences; splitting destroys coreference context.
- Support ≠ entailment. High cosine similarity or a soft judge score can be fooled by a passage that mentions related words without actually supporting the claim.
- No cross-sentence reasoning. An answer that combines facts from two passages to produce a new inference will appear unsupported even if both facts are present.
- Call cost scales with S × C. On long answers against large retrieval sets, this gets expensive fast. Caching and early-exit on score = 1.0 help, but the architecture should also consider whether all passages need to be checked or whether a re-ranker can short-list the two or three most relevant ones first.