StackPractices
advanced By Mathias Paulenko

Complete Guide to LLM Evaluation

Evaluate LLM apps in production: RAGAS, LLM-as-judge, hallucination detection, human eval, A/B testing and CI/CD regression pipelines.

Introduction

The classic LLM failure doesn’t look like a crash — it looks like a slightly worse answer. A prompt refactor ships Tuesday, and by Friday support tickets are up because the refund policy answers got vaguer. Nobody notices in the diff because nothing broke; the model just got a little less faithful, and the twenty-question eval suite that was supposed to catch it never covered refunds.

Evaluating LLM applications is the discipline of measuring whether outputs are correct, useful, and safe when there’s no binary pass/fail to assert on. Outputs are non-deterministic, quality is subjective, and the failure modes are subtle enough to hide for weeks.

This guide covers the full spectrum: evaluation dimensions worth measuring, RAGAS for RAG pipelines, LLM-as-judge for subjective quality (and its real biases), hallucination detection, human evaluation with agreement metrics, A/B testing, and regression suites wired into CI/CD.

Choosing an Evaluation Method

No single method covers everything — production stacks layer several:

MethodWhat it measuresWhen to useFidelityCost
RAGASRAG-specific: faithfulness, context precision/recallAny retrieval pipelineMedium — only sees RAGLow — batch API calls
LLM-as-judgeSubjective quality: clarity, helpfulness, correctnessRelative comparisons, rubric scoringMedium — has its own biasesMedium — one call per case
Human evaluationGround truth quality, preferenceCalibration, high-stakes, judges’ sanity checkHighestHigh — slow and expensive
A/B testingReal user preference between variantsModel/prompt launchesHighest — real behaviorHigh — needs traffic
Regression suite”Did this change break something?”Every prompt/model/code changeLow-Medium per caseLow once built
Hallucination checksUnsupported claims, fabricationAny factual/RAG outputMediumMedium — extra calls

The honest trade-off: automated methods are cheap and fast but measure proxies; human judgment is truth but doesn’t scale. Use automation to iterate and humans to calibrate — if your automated metric disagrees with human raters, the metric loses.

flowchart diagram: ds[Eval dataset<br/>prod failures + golden set

Evaluation Dimensions

What you measure depends on your app’s failure modes:

DimensionQuestion it answersTypical method
FaithfulnessIs the answer grounded in the provided context?RAGAS, claim verification
Answer relevancyDoes it address the actual question?RAGAS, judge rubric
Context precisionAre retrieved docs relevant?RAGAS (RAG only)
Context recallDid retrieval fetch what was needed?RAGAS (RAG only)
FactualityIs it factually correct?Judge, human eval, source checks
Hallucination rateHow often does it fabricate?Self-consistency, source checks
Safety/toxicityIs it safe and non-toxic?Guardrail classifiers, judge
CoherenceIs it well-structured and readable?Judge rubric, human eval
ConcisenessIs it appropriately brief?Judge rubric, length heuristics

RAGAS Framework

Installing and Using RAGAS

RAGAS is the standard eval library for RAG pipelines — it scores faithfulness, answer relevancy, and context quality from a dataset of question/answer/context/ground-truth tuples:

# pip install ragas datasets  — API varies by version; this follows ragas>=0.1
from ragas import evaluate
from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_precision,
    context_recall,
)
from datasets import Dataset

eval_data = {
    "question": [
        "What is Python's GIL?",
        "How does async/await work?",
    ],
    "answer": [
        "The GIL is a mutex that protects access to Python objects.",
        "async/await allows non-blocking I/O operations using coroutines.",
    ],
    "contexts": [
        ["Python's GIL (Global Interpreter Lock) is a mutex that prevents multiple threads from executing Python bytecodes at once."],
        ["async/await is syntax for writing asynchronous code. async marks a function as a coroutine, await suspends execution until the awaited task completes."],
    ],
    "ground_truth": [
        "The GIL is a mutex that prevents multiple native threads from executing Python bytecodes simultaneously.",
        "async/await enables non-blocking concurrent code using coroutines and an event loop.",
    ]
}

dataset = Dataset.from_dict(eval_data)

results = evaluate(
    dataset,
    metrics=[faithfulness, answer_relevancy, context_precision, context_recall],
)

print(results)
# {'faithfulness': 0.92, 'answer_relevancy': 0.88, 'context_precision': 0.95, 'context_recall': 0.90}

Two caveats worth knowing upfront. RAGAS only measures RAG — if your pipeline doesn’t retrieve, half the metrics are meaningless. And its scores are themselves LLM-judged under the hood, so they inherit judge biases; treat them as relative signals (did v2 improve over v1?) rather than absolute truth. For non-RAG evaluation, DeepEval and TruLens cover similar ground with different defaults.

Custom RAGAS Metrics

When the built-ins don’t fit, subclass MetricWithLLM:

from ragas.metrics.base import MetricWithLLM
from ragas.callbacks import Callbacks

class ConcisenessMetric(MetricWithLLM):
    name = "conciseness"

    async def _ascore(self, row, callbacks: Callbacks) -> float:
        answer = row["answer"]
        question = row["question"]

        prompt = f"""Rate the conciseness of this answer on a scale of 0-1.
        0 = overly verbose, 1 = perfectly concise.

        Question: {question}
        Answer: {answer}

        Score (0-1):"""

        response = await self.llm.generate(prompt)
        score = float(response.strip())
        return max(0.0, min(1.0, score))

LLM-as-Judge

Basic LLM Judge

For quality dimensions RAGAS doesn’t cover — and for non-RAG apps — a strong model grades outputs against a rubric:

from openai import AsyncOpenAI
import json

client = AsyncOpenAI()

JUDGE_PROMPT = """You are an expert evaluator. Rate the quality of an AI assistant's response.

Question: {question}
Response: {response}
Reference Answer: {reference}

Evaluate on these criteria (0-10 each):
1. Accuracy: Is the response factually correct?
2. Completeness: Does it cover all important aspects?
3. Clarity: Is it clear and well-structured?
4. Helpfulness: Is it useful to the user?

Return JSON: {{"accuracy": N, "completeness": N, "clarity": N, "helpfulness": N, "aggregate": N, "reasoning": "..."}}"""

async def llm_judge(question: str, response: str, reference: str) -> dict:
    prompt = JUDGE_PROMPT.format(question=question, response=response, reference=reference)
    result = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
        temperature=0.0
    )
    return json.loads(result.choices[0].message.content)

The rule that makes judging work: the judge must be stronger than the evaluated model, and at temperature=0 for reproducibility. Asking gpt-4o-mini to grade gpt-4o gives you noise dressed as scores.

Pairwise Comparison

Absolute scores drift; “which of these two is better” is a much easier judgment — and a more reliable one, per the LLM-as-judge paper (Zheng et al., MT-Bench):

PAIRWISE_PROMPT = """Compare two AI responses to the same question. Choose the better one.

Question: {question}

Response A: {response_a}
Response B: {response_b}

Criteria: accuracy, completeness, clarity, helpfulness.

Which response is better? Return JSON:
{{"winner": "A" or "B" or "tie", "reasoning": "..."}}"""

async def pairwise_compare(question: str, response_a: str, response_b: str) -> dict:
    prompt = PAIRWISE_PROMPT.format(question=question, response_a=response_a, response_b=response_b)
    result = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
        temperature=0.0
    )
    return json.loads(result.choices[0].message.content)

Reducing Judge Bias

Judges have documented biases, and the paper above quantifies them: position bias (the first response shown wins more often), verbosity bias (longer answers score higher even when wrong), and self-preference (models rate their own family’s outputs better). Randomize position and repeat:

import random

async def unbiased_pairwise_compare(question: str, response_a: str, response_b: str) -> dict:
    # Randomize order to reduce position bias
    if random.random() > 0.5:
        return await pairwise_compare(question, response_a, response_b)
    else:
        result = await pairwise_compare(question, response_b, response_a)
        # Flip the result back to original A/B labels
        if result["winner"] == "A":
            result["winner"] = "B"
        elif result["winner"] == "B":
            result["winner"] = "A"
        return result

async def robust_compare(question: str, response_a: str, response_b: str, n: int = 5) -> dict:
    results = []
    for _ in range(n):
        result = await unbiased_pairwise_compare(question, response_a, response_b)
        results.append(result["winner"])

    a_wins = results.count("A")
    b_wins = results.count("B")
    ties = results.count("tie")

    if a_wins > b_wins:
        return {"winner": "A", "confidence": a_wins / n, "details": {"A": a_wins, "B": b_wins, "tie": ties}}
    elif b_wins > a_wins:
        return {"winner": "B", "confidence": b_wins / n, "details": {"A": a_wins, "B": b_wins, "tie": ties}}
    else:
        return {"winner": "tie", "confidence": ties / n, "details": {"A": a_wins, "B": b_wins, "tie": ties}}

For verbosity bias, strip obvious giveaways (length-normalize or ask for justification-first reasoning). For self-preference, pick a judge from a different model family than the system under test.

Hallucination Detection

Self-Consistency Check

A model that hallucinates gives different answers on re-rolls; a model that knows tends to converge:

async def self_consistency_check(question: str, n: int = 3) -> dict:
    """Generate multiple responses and check for consistency."""
    responses = []
    for _ in range(n):
        result = await client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": question}],
            temperature=0.7  # higher temperature for diversity
        )
        responses.append(result.choices[0].message.content)

    consistency_prompt = f"""Are these responses factually consistent with each other?

    Response 1: {responses[0]}
    Response 2: {responses[1]}
    Response 3: {responses[2]}

    Return JSON: {{"consistent": true/false, "differences": ["..."], "confidence": 0-1}}"""

    check = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": consistency_prompt}],
        response_format={"type": "json_object"},
        temperature=0.0
    )
    return json.loads(check.choices[0].message.content)

This catches uncertainty, not truth — a confidently wrong model stays consistent. It’s cheap signal, not proof.

Cross-Reference with Sources

The stronger check for RAG: verify each claim against what was actually retrieved:

async def fact_check_with_sources(answer: str, sources: list[str]) -> dict:
    """Check if each claim in the answer is supported by the sources."""
    prompt = f"""Verify each claim in the answer against the provided sources.

    Answer: {answer}

    Sources:
    {chr(10).join(f"[{i+1}] {s}" for i, s in enumerate(sources))}

    For each claim, determine:
    - Is it supported by the sources?
    - Which source supports it?

    Return JSON:
    {{"claims": [{{"claim": "...", "supported": true/false, "source": N or null}}], "hallucination_rate": 0-1}}"""

    result = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
        temperature=0.0
    )
    return json.loads(result.choices[0].message.content)

No single method catches everything — self-consistency misses confident errors, source-checking misses out-of-context truth. Production systems combine them and alert on disagreement; the incident runbook covers what to do when detection fires in prod.

Human Evaluation

Evaluation Interface

Human eval is the calibration layer — slow, expensive, and the only ground truth for “is this actually good”:

from dataclasses import dataclass

@dataclass
class HumanEvaluation:
    question: str
    response: str
    rating: int  # 1-5
    feedback: str
    evaluator_id: str
    category: str  # "accuracy", "helpfulness", "safety"

class HumanEvalCollector:
    def __init__(self):
        self.evaluations: list[HumanEvaluation] = []

    def add(self, eval: HumanEvaluation):
        self.evaluations.append(eval)

    def summary(self) -> dict:
        if not self.evaluations:
            return {}
        ratings = [e.rating for e in self.evaluations]
        by_category = {}
        for eval in self.evaluations:
            by_category.setdefault(eval.category, []).append(eval.rating)
        return {
            "total_evaluations": len(self.evaluations),
            "avg_rating": sum(ratings) / len(ratings),
            "rating_distribution": {str(i): ratings.count(i) for i in range(1, 6)},
            "by_category": {cat: sum(rs) / len(rs) for cat, rs in by_category.items()}
        }

# In practice, use Argilla, Label Studio, or a custom UI

Inter-Annotator Agreement

Two annotators rating the same output should mostly agree — Cohen’s kappa measures agreement beyond chance:

def cohen_kappa(ratings_a: list[int], ratings_b: list[int]) -> float:
    """Calculate Cohen's Kappa for inter-annotator agreement."""
    assert len(ratings_a) == len(ratings_b)
    n = len(ratings_a)
    categories = sorted(set(ratings_a + ratings_b))

    # Observed agreement
    observed = sum(1 for a, b in zip(ratings_a, ratings_b) if a == b) / n

    # Expected agreement
    expected = 0
    for c in categories:
        p_a = ratings_a.count(c) / n
        p_b = ratings_b.count(c) / n
        expected += p_a * p_b

    if expected == 1:
        return 1.0
    return (observed - expected) / (1 - expected)

evaluator_1 = [5, 4, 3, 5, 4, 2, 5, 3, 4, 5]
evaluator_2 = [5, 4, 4, 5, 3, 2, 5, 3, 4, 4]

kappa = cohen_kappa(evaluator_1, evaluator_2)
# > 0.8 = strong agreement, 0.6-0.8 = good, < 0.6 = needs better rubric

One thing kappa does not measure: whether annotators are right. Two raters can agree strongly and both be wrong — kappa validates your rubric’s clarity, not your labels’ truth. Low kappa means the rubric is ambiguous; fix the rubric before trusting the scores.

A/B Testing

Statistical Significance

For “is variant B actually better,” you need a real proportion test — not vibes over a hundred thumbs-up:

import math

def ab_test_significance(
    conversions_a: int,
    total_a: int,
    conversions_b: int,
    total_b: int
) -> dict:
    """Calculate z-score and significance for an A/B test."""
    rate_a = conversions_a / total_a
    rate_b = conversions_b / total_b

    pooled = (conversions_a + conversions_b) / (total_a + total_b)
    se = math.sqrt(pooled * (1 - pooled) * (1/total_a + 1/total_b))

    if se == 0:
        return {"z_score": 0, "significant": False, "rate_a": rate_a, "rate_b": rate_b}

    z_score = (rate_b - rate_a) / se
    significant = abs(z_score) > 1.96  # |z| > 1.96 → p < 0.05

    return {
        "rate_a": rate_a,
        "rate_b": rate_b,
        "lift": (rate_b - rate_a) / rate_a if rate_a > 0 else 0,
        "z_score": z_score,
        "significant": significant,
        "confidence": "95% confidence" if significant else "Not significant at 95%"
    }

# Model A: 120 thumbs up / 200. Model B: 145 / 200.
result = ab_test_significance(120, 200, 145, 200)

Know your minimum detectable effect before you start: with ~400 total samples you can detect large swings, but a 2-point lift needs thousands per variant. If your traffic can’t power the effect size you care about, pairwise judge comparisons are the more sensitive instrument.

Online A/B Testing Framework

from dataclasses import dataclass

@dataclass
class ABTestConfig:
    name: str
    model_a: str
    model_b: str
    traffic_split: float  # fraction routed to model B
    min_samples: int = 100
    metrics: list = None

class ABTestRunner:
    def __init__(self, config: ABTestConfig):
        self.config = config
        self.results_a: list[dict] = []
        self.results_b: list[dict] = []

    def assign(self, user_id: str) -> str:
        """Deterministic assignment — same user always gets the same model."""
        hash_val = hash(user_id) % 100 / 100
        if hash_val < self.config.traffic_split:
            return self.config.model_b
        return self.config.model_a

    def record(self, model: str, user_rating: int, latency_ms: float):
        entry = {"rating": user_rating, "latency_ms": latency_ms}
        if model == self.config.model_a:
            self.results_a.append(entry)
        else:
            self.results_b.append(entry)

    def can_conclude(self) -> bool:
        return len(self.results_a) >= self.config.min_samples and \
               len(self.results_b) >= self.config.min_samples

Deterministic assignment matters more than it looks: randomize per request and a user bounces between models — your “B effect” gets contaminated by the A experience they saw ten seconds ago. Track latency and cost alongside satisfaction; a +5% quality lift that doubles latency might be a net loss.

Regression Testing

Test Suite for LLM Applications

The eval suite is your safety net for prompt, model, and code changes. Build the dataset from production failures — every bug report, thumbs-down, and incident becomes a test case:

import json
from pathlib import Path
from dataclasses import dataclass

@dataclass
class TestCase:
    id: str
    input: str
    expected_output: str  # or expected behavior
    min_score: float      # minimum similarity/quality score
    category: str

class LLMTestSuite:
    def __init__(self, test_file: str):
        self.tests: list[TestCase] = []
        self._load(test_file)

    def _load(self, test_file: str):
        with open(test_file) as f:
            data = json.load(f)
            for item in data["tests"]:
                self.tests.append(TestCase(**item))

    def run(self, llm_fn, judge_fn=None) -> dict:
        results = []
        for test in self.tests:
            output = llm_fn(test.input)
            score = judge_fn(test.input, output, test.expected_output) if judge_fn \
                else self._similarity(output, test.expected_output)
            passed = score >= test.min_score
            results.append({
                "id": test.id,
                "category": test.category,
                "score": score,
                "passed": passed,
                "input": test.input,
                "output": output[:200],
                "expected": test.expected_output[:200],
            })

        passed_count = sum(1 for r in results if r["passed"])
        return {
            "total": len(results),
            "passed": passed_count,
            "failed": len(results) - passed_count,
            "pass_rate": passed_count / len(results) if results else 0,
            "results": results,
        }

    def _similarity(self, a: str, b: str) -> float:
        # Simple Jaccard similarity on word sets
        words_a = set(a.lower().split())
        words_b = set(b.lower().split())
        if not words_a or not words_b:
            return 0.0
        return len(words_a & words_b) / len(words_a | words_b)

# tests.json
# {"tests": [{"id": "t1", "input": "What is 2+2?", "expected_output": "4", "min_score": 0.8, "category": "math"}]}

suite = LLMTestSuite("tests.json")
report = suite.run(lambda x: llm_call(x))

Jaccard similarity is the floor, not the ceiling — it catches catastrophic drift cheaply, but two phrasings of the same correct answer score low. Layer a judge_fn for semantic comparison on the cases that matter, and version tests.json alongside the prompts; the LangChain production guide covers eval-driven prompt iteration.

CI/CD Integration

Eval suites that don’t run in CI decay into shelf-ware. Gate merges on pass rate — but be deliberate about what’s blocking vs advisory:

import sys

def run_llm_tests():
    """Run LLM evaluation suite in CI/CD pipeline."""
    suite = LLMTestSuite("tests/llm_tests.json")
    report = suite.run(lambda x: llm_call(x))

    print(f"\nLLM Test Suite Report")
    print(f"Total: {report['total']}  Passed: {report['passed']}  Failed: {report['failed']}")
    print(f"Pass Rate: {report['pass_rate']:.1%}")

    if report["failed"] > 0:
        print("\nFailed Tests:")
        for r in report["results"]:
            if not r["passed"]:
                print(f"  [{r['id']}] {r['category']}  score={r['score']:.2f}")
                print(f"    input: {r['input'][:80]}")
                print(f"    output: {r['output'][:80]}")

    # Blocking gate: known-behavior cases must all pass
    # Advisory gate: subjective scores warn but don't block
    threshold = 0.85
    if report["pass_rate"] < threshold:
        print(f"\nPass rate {report['pass_rate']:.1%} below threshold {threshold:.1%}")
        sys.exit(1)

if __name__ == "__main__":
    run_llm_tests()

Two failure modes to avoid: a gate so loose it never fires (everyone stops checking), and a gate so tight it flakes on judge noise (everyone learns to merge through it). Deterministic cases — format, required fields, known answers — belong in the blocking gate. Judge-scored quality belongs in an advisory trend dashboard you review, not a hard 0.85 cutoff that fires when the judge model itself updates.

See Also

Frequently Asked Questions

What is LLM-as-judge and is it reliable?

LLM-as-judge uses a strong model to evaluate another model's output. It's reliable for relative comparisons and subjective dimensions (clarity, helpfulness) when the judge is stronger than the evaluated model — and unreliable for factuality, because the judge hallucinates too. Reduce bias with position randomization, repeated runs, and a judge from a different model family.

How many test cases do I need for regression testing?

Start with 50-100 covering your main use cases — that's where most failures hide. Grow it from production: every bug report, thumbs-down, and incident becomes a test case. A suite that started at 80 cases and sits at 300 a year later is doing its job.

What is a good RAGAS score?

For production RAG, target faithfulness > 0.85, answer relevancy > 0.80, context precision > 0.75, context recall > 0.80 — but thresholds depend on stakes: a medical assistant needs faithfulness > 0.95 while a casual Q&A bot tolerates 0.80. Treat scores as relative signals between versions, not absolute truth.

How do I detect hallucinations?

Combine three methods: self-consistency (re-generate and check agreement — catches uncertainty), source verification (check each claim against retrieved context — catches unsupported statements), and judge-based claim extraction. No single method catches everything; confident hallucinations survive consistency checks.

Should I use human evaluation or automated evaluation?

Both — automated for iteration speed and regression gating, human for calibration and high-stakes calls. If your automated metric disagrees with human raters on a sample, fix the metric. Human eval is the only ground truth, but it doesn't scale to every deploy.

How do I set up A/B testing for LLM models?

Assign users deterministically (hash the user ID — never per-request random, or users see both models). Collect explicit feedback plus latency and cost. Run until statistical significance on the effect size you care about — often 100+ samples per variant for big differences, thousands for small ones.

How is LLM evaluation different from software testing?

No binary assertions: outputs are non-deterministic and quality is a spectrum. Traditional tests assert exact behavior; LLM evals score distributions of quality. You need statistical thinking — sample sizes, agreement rates, thresholds — instead of "the test passed."