KatInterview

Evaluate LLM Output Quality and Build a Groundedness Scorer

Machine LearningModel answer
MediumModel answerMachine Learningllmevaluationhallucination-detection

Last 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 answer into 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_fn across all passages. Its best passage is the index that achieves that maximum (lowest index on ties). It is "supported" if its score is at least threshold.
  • 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 flag
    • groundedness: 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_fn calls 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.