Table of Contents

    LLM Evaluation (LLM-as-Judge, Hallucination Metrics)

    Generative AI and Large Language Models

    LLM Evaluation: LLM-as-Judge and Hallucination Metrics

    Learn how to evaluate Large Language Model applications using deterministic tests, reference-based metrics, human assessment, LLM-as-Judge, hallucination and faithfulness checks, retrieval evaluation, safety tests, tool-use validation, operational metrics, controlled quality gates, and continuous production evaluation.

    Introduction

    Large Language Models can produce fluent, relevant, and human-readable responses. However, fluency does not prove factual correctness, faithfulness, safety, completeness, or usefulness. A response may sound confident while containing unsupported claims, incorrect citations, omitted requirements, invalid tool arguments, or fabricated information.

    Traditional Machine Learning evaluation often compares a prediction with a structured reference label. LLM applications may produce long, open-ended outputs with several possible acceptable answers. This makes evaluation more complex.

    Reliable LLM evaluation combines multiple methods. Deterministic checks can validate schemas, citations, tool calls, required terms, and executable outputs. Reference-based metrics can compare outputs with approved answers. Human evaluators can assess nuanced quality. An LLM-as-Judge can apply a structured rubric at scale, provided that its limitations and biases are controlled.

    Core principle: No single score proves that an LLM application is production-ready. Evaluation should combine task quality, factuality, faithfulness, safety, robustness, efficiency, human judgment, and operational evidence.

    Learning Objectives

    By the End of This Lesson

    • Define LLM evaluation
    • Explain why ordinary accuracy is insufficient
    • Distinguish offline and online evaluation
    • Build a versioned evaluation dataset
    • Define multidimensional evaluation criteria
    • Use deterministic checks where possible
    • Understand reference-based text metrics
    • Design human-evaluation rubrics
    • Explain LLM-as-Judge evaluation
    • Use pointwise, pairwise, and ranking judgments
    • Create structured judge prompts
    • Validate judge outputs
    • Identify position and verbosity bias
    • Measure judge-human agreement
    • Define hallucination and faithfulness
    • Calculate claim-level faithfulness
    • Evaluate RAG retrieval and generation separately
    • Evaluate agent actions and tool calls
    • Integrate LLM evaluation with CI/CD
    • Create an LLM evaluation readiness checklist

    Prerequisites

    Recommended Knowledge

    • Python programming
    • Large Language Model fundamentals
    • Prompt engineering
    • Retrieval-Augmented Generation
    • Embeddings and semantic search
    • Vector databases
    • Train-validation-test separation
    • Precision, recall, and F1 score
    • Experiment tracking
    • Model observability and logging
    • Responsible AI fundamentals

    Example Packages

    • pandas
    • scikit-learn
    • DeepEval
    • ROUGE Score
    • SacreBLEU
    • BERTScore
    • Pydantic
    python -m pip install \
      pandas \
      scikit-learn \
      deepeval \
      rouge-score \
      sacrebleu \
      bert-score \
      pydantic
    Environment requirement: Use only approved model endpoints, evaluation services, datasets, credentials, storage systems, and monitoring platforms. Do not send restricted prompts, outputs, documents, or reference answers to an external judge without authorization.

    What Is LLM Evaluation?

    LLM evaluation is the systematic process of measuring whether a model or LLM application satisfies its defined quality, safety, operational, and business requirements.

    Evaluation Inputs
    Test Input + System Output + Reference or Context + Rubric → Evidence
    Evaluation Area Question
    Correctness Is the response factually or functionally correct?
    Relevance Does the response address the actual request?
    Faithfulness Are claims supported by the supplied context?
    Completeness Does the response satisfy all required parts?
    Safety Does the output avoid prohibited or harmful behavior?
    Format Does the response follow the required schema?
    Tool Use Did the system select and call tools correctly?
    Efficiency Does the system satisfy latency, token, and cost objectives?
    Business Value Does the output support the intended workflow effectively?

    Why LLM Evaluation Is Difficult

    Evaluation Challenges

    • Several different answers may be acceptable
    • Fluent text may contain subtle factual errors
    • Quality can depend on user context and intended use
    • A response can be partly correct and partly unsupported
    • Reference answers may be incomplete
    • Exact string matching may reject valid paraphrases
    • Human evaluators may disagree
    • LLM judges can be biased or inconsistent
    • Model behavior can vary with prompt and decoding settings
    • Retrieval and generation failures can be confused
    • Labels may arrive after production use
    • Safety failures may be rare but consequential
    Evaluation principle: Select evaluation methods according to the task. A metric suitable for translation may not be suitable for code execution, factual question answering, tool use, or conversational support.

    Evaluation Layers

    Layer What Is Evaluated?
    Model Base model or fine-tuned model capabilities
    Prompt Instruction clarity, constraints, and output format
    Retrieval Relevance, completeness, ranking, and authorization
    Generation Correctness, relevance, faithfulness, and style
    Tool Use Tool selection, arguments, sequence, and execution result
    Agent Trajectory Steps taken to complete a multi-stage task
    Application End-to-end user experience and workflow completion
    Operations Latency, availability, errors, token usage, and cost
    Business Outcome quality, adoption, fallback, and operational value

    Offline vs Online Evaluation

    Area Offline Evaluation Online Evaluation
    Data Versioned test cases and benchmarks Approved production interactions and outcomes
    Purpose Compare candidates before release Monitor actual behavior after deployment
    Repeatability Usually highly repeatable Affected by changing users, data, and workflows
    Risk Does not expose users to an unsuitable candidate Requires rollout, privacy, and incident controls
    Examples Regression suite, benchmark, red-team dataset A/B test, canary analysis, user feedback, delayed outcomes
    Lifecycle principle: Offline evaluation is required before deployment, but production monitoring is still necessary because real users and real inputs may differ from the evaluation dataset.

    Evaluation Dataset

    An evaluation dataset is a versioned collection of test cases representing the scenarios an LLM application must handle.

    {
        "case_id": "support-001",
        "input": "How do I reset my account password?",
        "reference_answer": "Use the approved password-reset workflow.",
        "context": [
            "Approved password-reset policy content"
        ],
        "expected_behavior": {
            "must_reference_policy": true,
            "must_not_request_password": true,
            "requires_human_escalation": false
        },
        "tags": [
            "account-support",
            "grounded-answer",
            "security"
        ]
    }

    Dataset Should Include

    • Common user requests
    • Difficult requests
    • Edge cases
    • Ambiguous inputs
    • Incomplete inputs
    • Requests requiring abstention
    • Unsupported requests
    • Adversarial inputs
    • Safety-sensitive cases
    • Tool-use scenarios
    • Multilingual cases where required
    • Regression cases from previous incidents

    Evaluation Dataset Metadata

    Metadata Purpose
    Case ID Provides an immutable test-case identity
    Task Identifies the capability being tested
    Difficulty Supports stratified analysis
    Language Supports language-specific evaluation
    Domain Identifies the relevant business or knowledge scope
    Source Preserves case provenance
    Expected Behavior Defines requirements beyond text similarity
    Risk Level Supports risk-weighted evaluation
    Rubric Version Identifies the criteria used for scoring

    Deterministic Evaluation

    Deterministic evaluation uses explicit rules or executable checks. It should be preferred when the required behavior can be tested reliably without subjective language judgment.

    Check Example
    Exact Match Expected classification label
    Schema Validation Valid JSON matching a Pydantic schema
    Required Field Response contains every mandatory property
    Forbidden Content Response does not contain credentials or prohibited terms
    Unit Test Generated code passes executable tests
    SQL Validation Generated query parses and satisfies read-only policy
    Tool Arguments Arguments match the tool schema
    Citation Validation Every citation maps to a retrieved source
    Evaluation priority: Do not use an expensive subjective LLM judge when a precise deterministic test can establish the requirement.

    Validate Structured Output

    import json
    from typing import Literal
    
    from pydantic import BaseModel
    from pydantic import ValidationError
    
    
    class SupportClassification(
        BaseModel
    ):
        category: Literal[
            "Bug",
            "Billing",
            "Access",
            "How-To",
            "Other"
        ]
    
        confidence: float
    
        explanation: str
    
    
    def validate_structured_output(
        model_output
    ):
        try:
            parsed_output = json.loads(
                model_output
            )
    
            validated_output = (
                SupportClassification
                .model_validate(
                    parsed_output
                )
            )
    
            if not (
                0.0
                <=
                validated_output.confidence
                <=
                1.0
            ):
                raise ValueError(
                    "Confidence must be "
                    "between zero and one."
                )
    
            return {
                "valid": True,
                "value": (
                    validated_output.model_dump()
                ),
                "error": None
            }
    
        except (
            json.JSONDecodeError,
            ValidationError,
            ValueError
        ) as error:
    
            return {
                "valid": False,
                "value": None,
                "error": str(
                    error
                )
            }

    Reference-Based Text Metrics

    Metric General Signal Limitation
    Exact Match Complete string equality Rejects valid paraphrases
    BLEU N-gram precision against references Lexical overlap may not reflect semantic correctness
    ROUGE N-gram or sequence overlap, commonly recall-oriented May reward copied wording without factual quality
    METEOR Token matching with additional linguistic matching behavior Still depends substantially on reference form
    BERTScore Contextual token-embedding similarity Semantic similarity does not guarantee factual correctness
    Task-Specific Accuracy Correct label, field, result, or action Requires an explicit structured target
    Metric principle: Lexical and semantic similarity metrics can support evaluation, but they should not be treated as complete factuality or safety checks.

    Calculate ROUGE

    from rouge_score import rouge_scorer
    
    
    def calculate_rouge(
        reference_text,
        generated_text
    ):
        scorer = rouge_scorer.RougeScorer(
            [
                "rouge1",
                "rouge2",
                "rougeL"
            ],
            use_stemmer=True
        )
    
        scores = scorer.score(
            reference_text,
            generated_text
        )
    
        return {
            metric_name: {
                "precision": float(
                    score.precision
                ),
                "recall": float(
                    score.recall
                ),
                "fmeasure": float(
                    score.fmeasure
                )
            }
            for metric_name, score
            in scores.items()
        }

    Human Evaluation

    Human evaluation uses qualified reviewers to assess model outputs according to an explicit rubric.

    Human Evaluation Type Description
    Pointwise Scoring Rates one response independently
    Pairwise Preference Selects the better of two responses
    Ranking Orders several responses from best to worst
    Error Annotation Labels specific factual, safety, style, or task errors
    Expert Review Uses domain-qualified evaluators for specialized claims
    User Feedback Captures real-world helpfulness or workflow success

    Human Evaluation Requires

    • Clear scoring instructions
    • Representative test cases
    • Reviewer training
    • Examples of each score level
    • Independent review where appropriate
    • Disagreement-resolution procedures
    • Privacy and access controls
    • Recorded rubric and dataset versions

    Example Evaluation Rubric

    Score Meaning
    4 Fully satisfies the criterion with no material issue
    3 Mostly satisfies the criterion with a minor issue
    2 Partially satisfies the criterion but has a meaningful issue
    1 Provides limited value and contains major problems
    0 Fails the criterion or produces unsafe or unusable behavior
    Rubric design: Define observable differences between score levels. Avoid vague labels such as “good” and “bad” without decision criteria.

    What Is LLM-as-Judge?

    LLM-as-Judge uses a language model to evaluate another model's response against a prompt, reference, retrieved context, rubric, or expected behavior.

    Judge Evaluation
    Input + Candidate Output + Reference or Context + Rubric → Judge Verdict
    Judge Output Example
    Binary Verdict Pass or fail
    Categorical Label Supported, unsupported, or contradictory
    Numeric Score Score from zero to four
    Pairwise Preference Response A, Response B, or tie
    Error Labels Factual error, omission, irrelevant content, or unsafe content
    Reason Brief evidence-based explanation for the verdict

    Pointwise vs Pairwise Judging

    Method Approach Use
    Pointwise Scores one candidate against a rubric Quality gates and per-response diagnostics
    Pairwise Compares two candidate responses directly Prompt, model, or configuration comparison
    Listwise Ranks several candidates Ordering several alternatives
    Reference-Based Scores against an approved answer Tasks with reliable references
    Context-Grounded Scores claims against supplied evidence RAG faithfulness and hallucination analysis

    Design a Judge Prompt

    You are evaluating an AI-generated response.
    
    Evaluate only the criterion in the rubric.
    Do not reward writing style unless the rubric requests it.
    Use only the supplied reference and context as evidence.
    If the evidence is insufficient, mark the relevant claim as unsupported.
    Return valid JSON matching the required schema.
    
    Input:
    {input}
    
    Reference answer:
    {reference_answer}
    
    Context:
    {context}
    
    Candidate response:
    {candidate_response}
    
    Rubric:
    1. Correctness
    2. Relevance
    3. Completeness
    4. Faithfulness to context
    
    Required JSON:
    {
      "correctness_score": 0,
      "relevance_score": 0,
      "completeness_score": 0,
      "faithfulness_score": 0,
      "unsupported_claims": [],
      "reason": ""
    }
    Prompt principle: Specify the evidence boundary, criterion, score definitions, output schema, and treatment of insufficient evidence. Do not ask the judge to apply an undefined concept such as “overall goodness.”

    Validate Judge Output

    from pydantic import BaseModel
    from pydantic import Field
    
    
    class JudgeResult(
        BaseModel
    ):
        correctness_score: int = Field(
            ge=0,
            le=4
        )
    
        relevance_score: int = Field(
            ge=0,
            le=4
        )
    
        completeness_score: int = Field(
            ge=0,
            le=4
        )
    
        faithfulness_score: int = Field(
            ge=0,
            le=4
        )
    
        unsupported_claims: list[
            str
        ]
    
        reason: str
    
    
    def validate_judge_result(
        parsed_judge_output
    ):
        return JudgeResult.model_validate(
            parsed_judge_output
        )
    Validation requirement: Treat judge output as untrusted model output. Validate its schema, score range, required fields, and failure behavior.

    Biases in LLM-as-Judge

    Bias or Failure Description
    Position Bias The judge may prefer the response shown first or second
    Verbosity Bias The judge may reward a longer answer regardless of usefulness
    Self-Preference A judge may favor response patterns similar to its own
    Style Bias Polished writing may be mistaken for correctness
    Reference Anchoring The judge may penalize a valid answer that differs from the reference wording
    Prompt Sensitivity Small rubric or instruction changes may alter judgments
    Non-Determinism Repeated judgments may differ
    Context Overload Long evidence may reduce reliable evaluation
    Domain Weakness The judge may lack the expertise needed for specialized claims

    Reduce Position Bias

    def create_pairwise_orders(
        input_text,
        first_response,
        second_response
    ):
        return [
            {
                "input": input_text,
                "response_a": first_response,
                "response_b": second_response,
                "mapping": {
                    "A": "first",
                    "B": "second"
                }
            },
            {
                "input": input_text,
                "response_a": second_response,
                "response_b": first_response,
                "mapping": {
                    "A": "second",
                    "B": "first"
                }
            }
        ]

    Judge-Bias Controls

    • Randomize response order
    • Judge both possible orders
    • Allow ties
    • Remove model names from responses
    • Define concise score anchors
    • Separate quality criteria
    • Use deterministic checks first
    • Calibrate against human-labeled examples
    • Review judge disagreement cases

    Calibrate the Judge

    Judge calibration compares automated judgments with labels produced by qualified human evaluators.

    Agreement
    \[ \text{Observed Agreement} = \frac{ \text{Matching Judge and Human Labels} }{ \text{Evaluated Cases} } \]
    Calibration Evidence Purpose
    Exact Agreement Measures identical labels
    Adjacent Agreement Measures whether ordinal scores differ only slightly
    Cohen's Kappa Measures categorical agreement beyond chance
    Confusion Matrix Shows which labels the judge confuses
    Criterion-Level Agreement Separates faithfulness, relevance, and completeness performance
    Segment-Level Agreement Checks judge consistency across domains and languages

    Calculate Judge Agreement

    from sklearn.metrics import accuracy_score
    from sklearn.metrics import cohen_kappa_score
    from sklearn.metrics import confusion_matrix
    
    
    def calculate_judge_agreement(
        human_labels,
        judge_labels
    ):
        if len(
            human_labels
        ) != len(
            judge_labels
        ):
            raise ValueError(
                "Human and judge label counts "
                "must match."
            )
    
        return {
            "exact_agreement": float(
                accuracy_score(
                    human_labels,
                    judge_labels
                )
            ),
            "cohen_kappa": float(
                cohen_kappa_score(
                    human_labels,
                    judge_labels
                )
            ),
            "confusion_matrix": (
                confusion_matrix(
                    human_labels,
                    judge_labels
                ).tolist()
            )
        }
    Calibration rule: Do not assume that a judge is reliable because its explanations sound convincing. Measure agreement using representative human-reviewed cases.

    What Is Hallucination?

    In practical LLM evaluation, hallucination refers to generated information that is fabricated, contradicted by reliable evidence, or unsupported by the evidence the application was expected to use.

    Hallucination Type Example Pattern
    Fabricated Fact Invents a date, person, policy, product, or event
    Contradiction States the opposite of the supplied evidence
    Unsupported Addition Adds details not established by available evidence
    Misattribution Associates a valid fact with the wrong entity
    Fabricated Citation Invents or misrepresents a source
    Incorrect Numerical Claim Changes a quantity, date, percentage, or measurement
    False Tool Result Claims that a tool returned data it did not return

    Hallucination vs Faithfulness

    Concept Evaluation Question
    Hallucination Does the response contain fabricated, contradictory, or unsupported information?
    Faithfulness Are the response's claims supported by the supplied context?
    Factual Correctness Are the claims correct relative to reliable ground truth?
    Answer Relevance Does the response address the user's question?
    Context Relevance Is the retrieved context useful for answering the question?
    Critical distinction: A response can be faithful to incorrect context. A response can also be factually correct using external knowledge while not being grounded in the supplied context. Evaluate factual correctness and faithfulness separately.

    Claim-Level Evaluation

    Claim-level evaluation decomposes a response into checkable claims and evaluates each claim against context or reliable ground truth.

    Faithfulness
    \[ \operatorname{Faithfulness} = \frac{ \text{Supported Claims} }{ \text{Evaluated Claims} } \]
    Unsupported Claim Rate
    \[ \operatorname{UnsupportedRate} = \frac{ \text{Unsupported Claims} }{ \text{Evaluated Claims} } \]
    Contradiction Rate
    \[ \operatorname{ContradictionRate} = \frac{ \text{Contradicted Claims} }{ \text{Evaluated Claims} } \]

    Calculate Claim-Level Metrics

    def calculate_claim_metrics(
        claim_labels
    ):
        allowed_labels = {
            "supported",
            "unsupported",
            "contradicted"
        }
    
        invalid_labels = [
            label
            for label in claim_labels
            if label not in allowed_labels
        ]
    
        if invalid_labels:
    
            raise ValueError(
                "Unknown claim labels were found."
            )
    
        total_claims = len(
            claim_labels
        )
    
        if total_claims == 0:
    
            raise ValueError(
                "At least one evaluated claim "
                "is required."
            )
    
        supported_count = claim_labels.count(
            "supported"
        )
    
        unsupported_count = claim_labels.count(
            "unsupported"
        )
    
        contradicted_count = claim_labels.count(
            "contradicted"
        )
    
        return {
            "evaluated_claims": total_claims,
            "supported_claims": supported_count,
            "unsupported_claims": unsupported_count,
            "contradicted_claims": contradicted_count,
            "faithfulness": (
                supported_count
                /
                total_claims
            ),
            "unsupported_rate": (
                unsupported_count
                /
                total_claims
            ),
            "contradiction_rate": (
                contradicted_count
                /
                total_claims
            )
        }

    Hallucination Evaluation Workflow

    1

    Identify the Evidence Boundary

    Define whether the answer should rely on retrieved context, reference material, tool output, general knowledge, or a combination.

    2

    Extract Verifiable Claims

    Separate factual statements from opinions, instructions, formatting, and non-factual language.

    3

    Match Claims to Evidence

    Identify the context passage, reference, or tool result that supports or contradicts each claim.

    4

    Assign Claim Labels

    Mark each claim as supported, unsupported, contradicted, or not assessable according to the rubric.

    5

    Calculate Metrics

    Calculate claim-level faithfulness, unsupported-claim rate, and contradiction rate.

    6

    Preserve Evidence

    Record claim text, context references, labels, judge version, rubric version, and reviewer decisions.

    Hallucination Evaluation with DeepEval

    from deepeval import evaluate
    from deepeval.metrics import HallucinationMetric
    from deepeval.test_case import LLMTestCase
    
    
    test_case = LLMTestCase(
        input=(
            "What does the supplied policy "
            "say about password resets?"
        ),
        actual_output=(
            generated_response
        ),
        context=[
            approved_policy_context
        ]
    )
    
    
    hallucination_metric = (
        HallucinationMetric(
            threshold=0.5,
            include_reason=True
        )
    )
    
    
    evaluation_result = evaluate(
        test_cases=[
            test_case
        ],
        metrics=[
            hallucination_metric
        ]
    )
    Metric configuration: The threshold illustrates the interface. Select pass criteria from your validated rubric, application risk, judge calibration, and human-reviewed evidence. Library defaults and APIs may change between versions.

    Faithfulness for RAG

    In a RAG system, faithfulness evaluates whether the generated response is supported by the retrieved context supplied to the model.

    from deepeval.metrics import FaithfulnessMetric
    
    
    faithfulness_metric = (
        FaithfulnessMetric(
            threshold=0.8,
            include_reason=True
        )
    )
    
    
    rag_test_case = LLMTestCase(
        input=user_question,
        actual_output=generated_answer,
        retrieval_context=(
            retrieved_contexts
        )
    )
    
    
    rag_evaluation = evaluate(
        test_cases=[
            rag_test_case
        ],
        metrics=[
            faithfulness_metric
        ]
    )
    RAG evaluation rule: Evaluate retrieval quality separately. A faithful response cannot provide a complete correct answer when the retriever supplied incomplete, obsolete, or irrelevant evidence.

    RAG Evaluation Dimensions

    Dimension Question
    Contextual Precision Are relevant chunks ranked ahead of irrelevant chunks?
    Contextual Recall Does the retrieved context contain the evidence needed for the reference answer?
    Contextual Relevance Is the retrieved context useful for the input?
    Faithfulness Is the generated answer supported by the retrieved context?
    Answer Relevancy Does the answer address the user's request?
    Factual Correctness Does the answer match reliable ground truth?
    Citation Correctness Do citations support the claims associated with them?
    Citation Completeness Are important factual claims adequately cited?

    Diagnose RAG Failures

    Retrieval Generation Interpretation
    Good Good System behaves as intended
    Poor Faithful Generator used the supplied evidence, but retrieval was insufficient
    Good Unfaithful Relevant evidence was available, but generation introduced unsupported claims
    Poor Unfaithful Both retrieval and generation require investigation
    Diagnostic principle: Do not label every incorrect RAG answer as a generation hallucination. First determine whether the required evidence was retrieved.

    Evaluate Tool Use

    Tool-Use Dimension Question
    Tool Selection Did the model select the correct tool?
    Argument Correctness Are arguments complete, valid, and grounded?
    Authorization Was the operation permitted?
    Call Order Were dependent tools called in a valid sequence?
    Result Interpretation Did the model accurately describe the tool output?
    Failure Handling Did the system respond safely to tool errors?
    Unnecessary Tool Use Did the model avoid actions not needed for the task?
    Task Completion Did the tool-assisted workflow achieve the intended result?

    Deterministic Tool-Call Validation

    def evaluate_tool_call(
        actual_call,
        expected_tool,
        required_arguments
    ):
        failures = []
    
        if actual_call.get(
            "tool_name"
        ) != expected_tool:
    
            failures.append(
                "Incorrect tool selected."
            )
    
        actual_arguments = actual_call.get(
            "arguments",
            {}
        )
    
        for argument_name, expected_value in (
            required_arguments.items()
        ):
            if argument_name not in actual_arguments:
    
                failures.append(
                    f"Missing argument: {argument_name}"
                )
    
            elif (
                actual_arguments[
                    argument_name
                ]
                != expected_value
            ):
                failures.append(
                    f"Incorrect value for: "
                    f"{argument_name}"
                )
    
        return {
            "passed": len(
                failures
            ) == 0,
            "failures": failures
        }

    Evaluate Agent Trajectories

    Agent evaluation may need to examine not only the final answer but also the observable sequence of planned actions, tool calls, tool results, retries, and state transitions.

    Trajectory Area Evaluation Question
    Goal Completion Did the agent complete the task?
    Action Validity Were actions valid and authorized?
    Efficiency Did the agent avoid unnecessary steps?
    Recovery Did the agent recover safely from errors?
    State Consistency Did the agent preserve required information across steps?
    Grounding Were claims based on tool and retrieval results?
    Stop Behavior Did the agent stop when the task was complete or blocked?
    Human Approval Did consequential actions receive required confirmation?

    Safety Evaluation

    Safety Test Areas

    • Harmful-content handling
    • Privacy and confidential-data protection
    • Prompt injection
    • Jailbreak attempts
    • Unauthorized tool use
    • Data exfiltration attempts
    • System-prompt extraction attempts
    • Fabricated citations
    • Bias and unequal behavior
    • Overconfident unsupported claims
    • Unsafe automation
    • Failure to request human approval
    Risk principle: Overall average quality can hide rare safety failures. Track high-risk scenarios separately and apply strict release gates.

    Multilingual Evaluation

    Evaluate for Every Required Language

    • Instruction understanding
    • Answer correctness
    • Faithfulness
    • Safety behavior
    • Terminology accuracy
    • Code-mixed input
    • Transliteration
    • Formatting
    • Retrieval quality
    • Judge-human agreement
    Language caution: A judge performing well in one language may not evaluate another language with equal reliability. Calibrate per required language and domain.

    Operational Evaluation

    Operational Metric Purpose
    End-to-End Latency Measures total response time
    Time to First Token Measures initial response delay
    Generation Throughput Measures output-token production speed
    Input Tokens Measures prompt and context consumption
    Output Tokens Measures generated-output length
    Cost per Request Measures estimated or billed request cost
    Error Rate Measures failed requests
    Retry Rate Measures repeated model or tool calls
    Fallback Rate Measures use of alternate behavior
    Judge Cost Measures evaluation-model consumption

    Composite Quality Scores

    A composite score can summarize several dimensions, but it can also hide a critical failure. Use it for reporting only after preserving the individual criterion scores.

    Weighted Composite Score
    \[ S = \sum_{i=1}^{n} w_i s_i \]
    Weight Constraint
    \[ \sum_{i=1}^{n} w_i = 1 \]
    Quality-gate principle: Use independent mandatory gates for critical safety, authorization, factuality, and schema requirements. A high average should not compensate for a severe failure.

    Create an Evaluation Gate

    def evaluate_release_gate(
        measured_metrics,
        minimum_metrics,
        maximum_metrics=None,
        mandatory_failures=None
    ):
        maximum_metrics = (
            maximum_metrics
            or {}
        )
    
        mandatory_failures = (
            mandatory_failures
            or []
        )
    
        failures = list(
            mandatory_failures
        )
    
        for metric_name, minimum_value in (
            minimum_metrics.items()
        ):
            actual_value = measured_metrics.get(
                metric_name
            )
    
            if actual_value is None:
    
                failures.append(
                    f"Missing metric: {metric_name}"
                )
    
            elif actual_value < minimum_value:
    
                failures.append(
                    f"{metric_name} is below "
                    "the approved minimum."
                )
    
        for metric_name, maximum_value in (
            maximum_metrics.items()
        ):
            actual_value = measured_metrics.get(
                metric_name
            )
    
            if actual_value is None:
    
                failures.append(
                    f"Missing metric: {metric_name}"
                )
    
            elif actual_value > maximum_value:
    
                failures.append(
                    f"{metric_name} exceeds "
                    "the approved maximum."
                )
    
        return {
            "passed": len(
                failures
            ) == 0,
            "failures": failures
        }
    No invented thresholds: Minimums and maximums must come from approved application requirements and validated evaluation evidence.

    Evaluation in CI/CD

    Evaluation Pipeline
    Prompt or Model Change → Deterministic Tests → Evaluation Dataset → LLM Judge → Human Review → Release Gate
    name: Evaluate LLM Application
    
    on:
      pull_request:
      push:
        branches:
          - main
    
    jobs:
      evaluate:
        runs-on: ubuntu-latest
    
        steps:
          - name: Check out repository
            uses: actions/checkout@v4
    
          - name: Set up Python
            uses: actions/setup-python@v5
            with:
              python-version: "3.12"
    
          - name: Install dependencies
            run: |
              python -m pip install --upgrade pip
              python -m pip install -r requirements.txt
    
          - name: Run deterministic tests
            run: |
              python -m pytest -v
    
          - name: Run offline LLM evaluation
            run: |
              python -m evaluation.run_suite \
                --dataset evaluation/dataset.jsonl \
                --configuration evaluation/config.json \
                --output artifacts/evaluation-results.json
    
          - name: Apply release gate
            run: |
              python -m evaluation.release_gate \
                --results artifacts/evaluation-results.json \
                --policy evaluation/release-policy.json

    Continuous Production Evaluation

    Production Signals

    • Answer relevance
    • Faithfulness
    • Unsupported-claim rate
    • Abstention rate
    • Retrieval precision and recall
    • Citation correctness
    • Format-validation rate
    • Tool-call correctness
    • Task-completion rate
    • Safety-filter activation
    • User correction and complaint rate
    • Latency, token consumption, and cost
    Production-evaluation caution: Production prompts and outputs may contain sensitive information. Apply minimization, redaction, access control, retention, and sampling before automated or human evaluation.

    Production Evaluation Sampling

    Sampling Method Purpose
    Random Sampling Provides broad population coverage
    Error-Based Sampling Prioritizes failed or low-confidence interactions
    Risk-Based Sampling Increases inspection of consequential use cases
    New-Version Sampling Increases evidence during canary deployment
    Language Sampling Preserves evaluation coverage across required languages
    Complaint-Based Sampling Prioritizes reported failures
    Drift-Based Sampling Prioritizes changed input or output populations

    A/B and Canary Evaluation

    Evidence Candidate Comparison
    Task Quality Which version completes the task more reliably?
    Faithfulness Which version produces fewer unsupported claims?
    Safety Which version better follows safety requirements?
    Latency Which version responds within the objective?
    Cost Which version uses fewer resources for acceptable quality?
    User Outcome Which version better supports the intended workflow?
    Fallback Which version requires fewer escalations or retries?

    Evaluation Reproducibility

    Version

    • Application code
    • Base model and revision
    • Fine-tuned model or adapter
    • System prompt
    • User prompt template
    • Retrieval corpus
    • Embedding model
    • Reranker
    • Tool definitions
    • Evaluation dataset
    • Reference answers
    • Judge model
    • Judge prompt and rubric
    • Generation configuration
    • Evaluation-library versions
    {
        "evaluation_run_id": "generated-run-identifier",
        "application_version": "2.0.0",
        "candidate_model": "approved-model-identifier",
        "candidate_model_revision": "immutable-revision",
        "prompt_version": "3.1.0",
        "evaluation_dataset_version": "1.4.0",
        "judge_model": "approved-judge-identifier",
        "judge_prompt_version": "2.0.0",
        "rubric_version": "2.0.0",
        "generation_temperature": 0,
        "evaluation_library_version": "record-installed-version"
    }

    Security and Privacy

    Required Controls

    • Use only authorized evaluation data
    • Minimize personal and confidential information
    • Protect reference answers and hidden tests
    • Do not expose evaluation labels to the candidate model
    • Protect judge credentials
    • Restrict access to production-evaluation samples
    • Redact secrets before judgment
    • Encrypt evaluation artifacts
    • Audit dataset and result access
    • Define retention and deletion policies
    • Prevent prompt injection from controlling judge instructions
    • Separate candidate content from judge-system instructions
    Unsafe Evaluation Send complete confidential prompts, outputs, retrieved documents, credentials, and user identifiers to an unapproved judge service.
    Controlled Evaluation Use an approved judge, minimize and redact records, protect hidden references, enforce access, and retain only the evidence required for the evaluation purpose.

    Responsible LLM Evaluation

    Responsible Evaluation Requirements

    • Align metrics with the intended use
    • Evaluate prohibited and out-of-scope requests
    • Include qualified domain reviewers
    • Measure behavior across relevant languages and populations
    • Track disagreement and uncertainty
    • Avoid hiding critical failures behind averages
    • Preserve human oversight for consequential decisions
    • Test correction, appeal, and escalation workflows
    • Evaluate fallback and abstention
    • Document known evaluation gaps
    • Monitor production behavior continuously
    • Retire systems that no longer satisfy approved requirements

    Common LLM Evaluation Mistakes

    Mistake Use one overall score for every application requirement.
    Correction Track correctness, relevance, faithfulness, safety, format, operational quality, and business outcomes separately.
    Mistake Treat lexical similarity as factual correctness.
    Correction Use lexical metrics for appropriate tasks and add factual, faithfulness, deterministic, or human evaluation.
    Mistake Trust the LLM judge without human calibration.
    Correction Compare judge results with qualified human labels across representative cases and segments.
    Mistake Use a vague judge prompt asking whether an answer is good.
    Correction Define evidence boundaries, criteria, score anchors, and a validated output schema.
    Mistake Use the final test set repeatedly during prompt tuning.
    Correction Use development and validation cases for iteration and preserve an independent final evaluation set.
    Mistake Evaluate only the generated answer in a RAG application.
    Correction Evaluate retrieval, context quality, generation faithfulness, factual correctness, citations, and end-to-end usefulness.
    Mistake Treat judge explanations as proof of correct scoring.
    Correction Validate judge labels and reasons against human-reviewed cases.
    Mistake Report only the average score.
    Correction Report distributions, failures, criteria, risk levels, languages, domains, and confidence intervals where appropriate.

    Troubleshooting

    Symptom Investigation
    Judge Scores Are Inconsistent Temperature, prompt clarity, model version, position bias, and context length
    Judge Rewards Long Answers Verbosity bias and missing conciseness criteria
    High Faithfulness but Incorrect Answers Incorrect or incomplete retrieved context
    Low Faithfulness but Correct Answer Answer relied on knowledge outside the supplied evidence
    Good Offline but Poor Production Quality Dataset representativeness, prompt drift, user mix, retrieval drift, and tool failures
    Pairwise Results Reverse Position bias and unstable rubric interpretation
    Evaluation Is Too Expensive Sampling, deterministic pre-checks, judge size, batching, caching, and criterion scope
    Human Reviewers Disagree Rubric ambiguity, reviewer training, domain complexity, and insufficient evidence
    Hallucination Score Is Misleading Claim extraction, evidence boundary, judge calibration, and context correctness
    Regression Suite Becomes Easy Test contamination, benchmark overfitting, repeated tuning, and missing fresh cases

    Recommended LLM Evaluation Workflow

    1

    Define the Application Objective

    Identify intended users, tasks, quality requirements, prohibited uses, risks, latency, cost, and business outcomes.

    2

    Define Evaluation Dimensions

    Select correctness, relevance, faithfulness, safety, format, tool use, efficiency, and business criteria.

    3

    Build the Evaluation Dataset

    Create representative common, difficult, adversarial, multilingual, no-answer, and high-risk test cases.

    4

    Implement Deterministic Checks

    Validate schemas, citations, tools, labels, permissions, code, and required output conditions.

    5

    Design Human and Judge Rubrics

    Define evidence boundaries, score anchors, failure labels, ties, abstention, and disagreement handling.

    6

    Calibrate the Judge

    Compare automated judgments with representative expert-reviewed examples and investigate disagreement.

    7

    Run Multidimensional Evaluation

    Execute deterministic, reference-based, judge-based, human, safety, retrieval, tool-use, and operational evaluations.

    8

    Apply Release Gates

    Block release when critical safety, authorization, correctness, faithfulness, or operational requirements fail.

    9

    Deploy Through a Controlled Rollout

    Use staging, shadow, canary, or A/B evaluation with fallback and rollback.

    10

    Evaluate Continuously

    Monitor quality, safety, cost, latency, drift, complaints, incidents, judge stability, and business outcomes.

    Hands-On Practice

    1

    Create an Evaluation Dataset

    Build versioned question, reference, context, expected behavior, language, difficulty, and risk fields.

    2

    Add Deterministic Checks

    Validate structured output, required fields, citations, tool arguments, and forbidden content.

    3

    Design an LLM Judge

    Create a structured rubric for correctness, relevance, completeness, and faithfulness.

    4

    Test Position Bias

    Evaluate response pairs in both orders and compare the verdicts.

    5

    Evaluate Hallucination

    Extract claims, label each claim against context, and calculate supported, unsupported, and contradicted rates.

    6

    Evaluate a RAG Pipeline

    Measure retrieval relevance, contextual recall, generation faithfulness, factual correctness, and citation behavior.

    7

    Calibrate Against Human Review

    Calculate exact agreement, Cohen's kappa, and a confusion matrix between judge and human labels.

    8

    Create a Release Gate

    Define mandatory safety and factuality gates plus approved quality, latency, and cost requirements.

    Knowledge Check

    1

    Why is exact match insufficient for many LLM tasks?

    Explain how different phrasings can represent equally valid answers.

    2

    What is LLM-as-Judge?

    Explain how one model evaluates another model's output using supplied evidence and a rubric.

    3

    What is pairwise evaluation?

    Explain how a judge compares two candidate responses and selects a preferred response or tie.

    4

    What is position bias?

    Explain how response order can influence a judge's preference.

    5

    What is hallucination?

    Explain fabricated, contradicted, misattributed, or unsupported information in generated output.

    6

    What is faithfulness?

    Explain whether generated claims are supported by the supplied evidence.

    7

    How can a response be faithful but incorrect?

    Explain how the response may accurately reflect context that is itself incorrect or obsolete.

    8

    Why evaluate retrieval separately from generation?

    Explain how missing evidence and unfaithful generation are different failure modes.

    9

    Why calibrate an LLM judge?

    Explain how human-labeled cases reveal judge bias, inconsistency, and criterion-specific weakness.

    10

    Why should critical gates remain separate from an average score?

    Explain how a severe safety or authorization failure must not be offset by strong performance on less critical dimensions.

    LLM Evaluation Readiness Checklist

    Confirm Before Production Use

    • The application objective is documented
    • Intended and prohibited uses are documented
    • Evaluation dimensions align with the actual workflow
    • The evaluation dataset is versioned
    • Common and difficult cases are included
    • No-answer and abstention cases are included
    • Safety and adversarial cases are included
    • Required languages and domains are included
    • Reference answers are reviewed
    • Expected behavior is recorded separately from wording
    • Hidden test cases are protected
    • Deterministic checks are implemented where possible
    • Judge rubrics use observable score anchors
    • Judge outputs use a validated schema
    • Judge model and immutable version are recorded
    • Judge prompt and rubric versions are recorded
    • Position bias is assessed
    • Verbosity bias is assessed
    • Judge-human agreement is measured
    • Judge disagreement cases are reviewed
    • Hallucination claims are evaluated against defined evidence
    • Faithfulness and factual correctness are separated
    • Retrieval and generation are evaluated separately
    • Citations are validated
    • Tool selection and arguments are tested
    • Agent trajectories are evaluated where applicable
    • Safety requirements use mandatory gates
    • Latency and token usage are measured
    • Evaluation cost is measured
    • Final test data remains independent
    • Evaluation artifacts are access controlled
    • Sensitive production samples are minimized
    • CI/CD quality gates are automated
    • Canary and rollback criteria are defined
    • Continuous production evaluation is configured
    • Known evaluation limitations are documented

    Lesson Summary

    Evaluation Concept Main Outcome
    Evaluation Dataset Provides representative and repeatable test cases
    Deterministic Evaluation Validates explicit and executable requirements
    Reference-Based Metrics Compare generated text with approved references
    Human Evaluation Provides nuanced and domain-qualified judgments
    LLM-as-Judge Applies structured natural-language rubrics at scale
    Judge Calibration Measures agreement with qualified human reviewers
    Hallucination Evaluation Detects fabricated, unsupported, or contradictory claims
    Faithfulness Measures support from supplied context
    Factual Correctness Measures correctness relative to reliable ground truth
    RAG Evaluation Separates retrieval quality from generation quality
    Tool Evaluation Validates selection, arguments, execution, and result use
    Safety Evaluation Tests harmful, prohibited, adversarial, and unauthorized behavior
    Operational Evaluation Measures latency, tokens, errors, and cost
    Release Gates Prevent unsuitable candidates from progressing
    Continuous Evaluation Tracks quality and safety after deployment

    Key Takeaway

    LLM evaluation requires a multidimensional and risk-aware framework. Deterministic checks should validate structured requirements whenever possible. Reference-based metrics can measure lexical or semantic similarity, but they do not prove factuality. Human reviewers provide domain judgment, while LLM-as-Judge can help scale rubric-based evaluation when the judge is explicitly instructed, schema validated, calibrated against humans, and monitored for bias. Hallucination evaluation identifies fabricated, unsupported, contradictory, or misattributed claims, while faithfulness asks whether claims are grounded in supplied evidence. In RAG systems, retrieval quality and generation quality must be assessed separately. Production readiness also requires safety, tool-use, agent-trajectory, latency, token, cost, privacy, and business evaluation. Reliable evaluation does not end with an offline benchmark. It continues through CI/CD, controlled rollout, production monitoring, incident investigation, and periodic human review.

    Get Machine Learning updates by email

    Short, practical lessons and course updates from Rumman Ansari. No spam.