Testing LLM Outputs: Determinism, Hallucination Detection, and Evaluation Frameworks

Testing LLM Outputs: Determinism, Hallucination Detection, and Evaluation Frameworks

LLMs are probabilistic systems. The same input can produce different outputs on different runs. Outputs can be factually wrong but sound confident. Testing them requires different techniques than testing deterministic code. This guide covers how to approach LLM output testing systematically — handling non-determinism, detecting hallucinations, and building evaluation frameworks with DeepEval and OpenAI Evals.

The Fundamental Testing Challenge

Traditional software testing assumes determinism:

assert add(2, 3) == 5  # Always true

LLMs don't work this way:

response = llm.complete("What is 2+3?")
assert response == "5"  # Fails ~20% of the time: "2 + 3 equals 5", "The answer is 5", "5."

The problem isn't the assertion — it's the assumption that there's one correct output. LLM testing must evaluate quality dimensions, not exact string matching.

What to Test in LLM Outputs

Before picking tools, decide what you're measuring:

Dimension Question How to measure
Factual accuracy Is the claim true? Against ground truth or web search
Faithfulness Is the answer grounded in the provided context? Check if claims are in source docs
Relevance Does it answer the actual question? Semantic similarity, judge models
Toxicity Does it contain harmful content? Classifier models
Hallucination Does it invent facts? Entailment checking, citations
Format compliance Does it match the expected format? Schema validation
Consistency Does it give the same answer on re-runs? Statistical testing

Handling Non-Determinism in Tests

Temperature controls how random the output is. For testing, reduce temperature:

import openai

client = openai.OpenAI()

def get_deterministic_response(prompt: str) -> str:
    """Temperature 0 maximizes determinism but doesn't guarantee it."""
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,
        seed=42,  # OpenAI supports seed for reproducibility
    )
    return response.choices[0].message.content

Even at temperature=0, small model updates can change outputs. Handle this:

def assert_contains_key_info(response: str, required_info: list[str]) -> None:
    """Flexible assertion that checks for key information, not exact text."""
    for info in required_info:
        # Check semantic presence, not literal string match
        assert info.lower() in response.lower() or \
               any_semantically_similar(info, response), \
               f"Response missing: {info}\n\nResponse was: {response}"

Statistical Testing for Non-Deterministic Outputs

For higher temperatures, run multiple times and check aggregate behavior:

import pytest
from collections import Counter

def test_llm_classifies_sentiment_correctly_most_of_the_time():
    """Sentiment classification should be correct at least 90% of the time."""
    test_cases = [
        ("I love this product!", "positive"),
        ("This is terrible.", "negative"),
        ("It's fine, nothing special.", "neutral"),
    ]
    
    results = []
    for text, expected in test_cases:
        correct = 0
        for _ in range(10):  # Run each 10 times
            response = classify_sentiment(text)  # Your LLM wrapper
            if response == expected:
                correct += 1
        results.append(correct / 10)
    
    average_accuracy = sum(results) / len(results)
    assert average_accuracy >= 0.9, f"Accuracy {average_accuracy:.1%} below 90% threshold"

Hallucination Detection

Hallucination — the LLM making up facts — is the most common failure mode in production. There are three strategies:

Strategy 1: Ground Truth Comparison

If you have known correct answers, compare against them:

from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

class FactualAccuracyChecker:
    def __init__(self):
        self.model = SentenceTransformer('all-MiniLM-L6-v2')
    
    def check_factual_accuracy(
        self,
        response: str,
        ground_truth: str,
        threshold: float = 0.85
    ) -> dict:
        """Check if response is semantically similar to ground truth."""
        response_embedding = self.model.encode([response])
        truth_embedding = self.model.encode([ground_truth])
        
        similarity = cosine_similarity(response_embedding, truth_embedding)[0][0]
        
        return {
            "score": float(similarity),
            "passed": similarity >= threshold,
            "threshold": threshold,
        }

# Test usage
checker = FactualAccuracyChecker()

def test_product_description_accuracy():
    response = llm.complete("What does HelpMeTest do?")
    ground_truth = "HelpMeTest is an AI-powered testing tool that monitors your app 24/7 in plain English."
    
    result = checker.check_factual_accuracy(response, ground_truth, threshold=0.75)
    
    assert result["passed"], \
        f"Response too dissimilar from ground truth. Score: {result['score']:.3f}\nResponse: {response}"

Strategy 2: Entailment Checking

Does the response's claims follow from the provided context?

from transformers import pipeline

nli_model = pipeline("text-classification", model="cross-encoder/nli-deberta-v3-base")

def check_response_grounded_in_context(response: str, context: str) -> dict:
    """
    Verify response claims are entailed by the context.
    Uses Natural Language Inference (NLI) to detect unsupported claims.
    """
    # Split response into individual claims
    claims = extract_claims(response)  # Simple: split on periods
    
    results = []
    for claim in claims:
        if len(claim.strip()) < 10:  # Skip very short fragments
            continue
        
        result = nli_model(f"{context} [SEP] {claim}")
        label = result[0]["label"]
        score = result[0]["score"]
        
        results.append({
            "claim": claim,
            "verdict": label,  # ENTAILMENT, NEUTRAL, or CONTRADICTION
            "confidence": score,
        })
    
    hallucinations = [r for r in results if r["verdict"] == "CONTRADICTION" and r["confidence"] > 0.8]
    
    return {
        "total_claims": len(results),
        "hallucinations": hallucinations,
        "hallucination_rate": len(hallucinations) / max(len(results), 1),
        "passed": len(hallucinations) == 0,
    }

Strategy 3: LLM-as-Judge

Use a more capable model to evaluate outputs from a less capable one:

def llm_judge_hallucination(
    question: str,
    context: str,
    response: str,
    judge_model: str = "gpt-4o"
) -> dict:
    """Use GPT-4 to judge whether a response contains hallucinations."""
    
    judge_prompt = f"""You are evaluating whether an AI response contains hallucinations.

QUESTION: {question}

CONTEXT (the only valid source of information):
{context}

RESPONSE TO EVALUATE:
{response}

Evaluate whether the RESPONSE contains any claims not supported by the CONTEXT.
Respond with JSON:
{{
    "verdict": "PASS" or "FAIL",
    "hallucinated_claims": ["list", "of", "unsupported", "claims"],
    "reasoning": "brief explanation"
}}"""
    
    judge_response = client.chat.completions.create(
        model=judge_model,
        messages=[{"role": "user", "content": judge_prompt}],
        temperature=0,
        response_format={"type": "json_object"},
    )
    
    return json.loads(judge_response.choices[0].message.content)

DeepEval: Structured LLM Evaluation

DeepEval provides a test framework specifically for LLM applications. It integrates with pytest and provides metrics as first-class objects.

Install:

pip install deepeval

Basic DeepEval Test

import pytest
from deepeval import assert_test
from deepeval.test_case import LLMTestCase
from deepeval.metrics import AnswerRelevancyMetric, FaithfulnessMetric, HallucinationMetric

def test_rag_response_quality():
    # Setup
    test_case = LLMTestCase(
        input="What are the pricing tiers for HelpMeTest?",
        actual_output=your_rag_pipeline("What are the pricing tiers for HelpMeTest?"),
        expected_output="HelpMeTest offers usage-based pricing ($0.003 per test run), a Managed plan at $2,500/month, and Enterprise (contact sales).",
        retrieval_context=[
            "Usage-based plan: $0.003 per test run, no base fee, unlimited health checks, 24/7 monitoring.",
            "Managed plan: $2,500/month, up to 500 tests included, parallel execution.",
            "Enterprise plan: contact sales, includes SSO and priority support."
        ]
    )
    
    # Define metrics
    relevancy_metric = AnswerRelevancyMetric(threshold=0.7, model="gpt-4o-mini")
    faithfulness_metric = FaithfulnessMetric(threshold=0.8, model="gpt-4o-mini")
    hallucination_metric = HallucinationMetric(threshold=0.3, model="gpt-4o-mini")
    
    # Assert
    assert_test(test_case, [relevancy_metric, faithfulness_metric, hallucination_metric])

DeepEval Dataset Testing

Test across a full evaluation dataset:

from deepeval.dataset import EvaluationDataset
from deepeval.metrics import AnswerRelevancyMetric, ContextualPrecisionMetric

def test_rag_system_on_golden_dataset():
    dataset = EvaluationDataset()
    dataset.add_test_cases([
        LLMTestCase(
            input="How do I run tests in parallel?",
            actual_output=rag_pipeline("How do I run tests in parallel?"),
            expected_output="Parallel test execution is unlimited and included in HelpMeTest's usage-based pricing.",
            retrieval_context=["Usage-based pricing includes unlimited parallel execution and unlimited tests."],
        ),
        LLMTestCase(
            input="Does HelpMeTest support SSO?",
            actual_output=rag_pipeline("Does HelpMeTest support SSO?"),
            expected_output="SSO is available on the Enterprise plan.",
            retrieval_context=["Enterprise plan features: SSO, priority support, custom features."],
        ),
        # Add 50-100 cases for a meaningful benchmark
    ])
    
    metrics = [
        AnswerRelevancyMetric(threshold=0.7, model="gpt-4o-mini"),
        ContextualPrecisionMetric(threshold=0.7, model="gpt-4o-mini"),
    ]
    
    dataset.evaluate(metrics)
    
    # Assert aggregate scores
    for metric in metrics:
        avg_score = sum(tc.metrics_metadata[metric.__class__.__name__]["score"] 
                       for tc in dataset.test_cases) / len(dataset.test_cases)
        assert avg_score >= metric.threshold, \
            f"{metric.__class__.__name__} average score {avg_score:.2f} below threshold {metric.threshold}"

OpenAI Evals Framework

OpenAI Evals is a framework for evaluating AI system performance with a focus on reproducibility.

Install:

pip install evals

Writing a Custom Eval

# evals/my_rag_eval.py
import evals
import evals.metrics
from evals.api import CompletionFn
from evals.eval import Eval
from evals.record import RecorderBase

class RAGFaithfulnessEval(Eval):
    """Evaluate whether RAG responses are faithful to retrieved context."""
    
    def __init__(self, completion_fns: list[CompletionFn], samples_jsonl: str, *args, **kwargs):
        super().__init__(completion_fns, *args, **kwargs)
        self.samples_jsonl = samples_jsonl
    
    def eval_sample(self, sample, rng):
        """Evaluate a single sample."""
        question = sample["input"]
        context = sample["context"]
        expected = sample["ideal"]
        
        # Get actual response from RAG pipeline
        prompt = f"Answer based on context only:\nContext: {context}\n\nQuestion: {question}"
        response = self.completion_fn(prompt=prompt)
        actual_output = response.get_completions()[0]
        
        # Use LLM judge to assess faithfulness
        judge_prompt = f"""Is this response faithful to the context?
Context: {context}
Response: {actual_output}
Answer ONLY 'yes' or 'no'."""
        
        judge_response = evals.get_client().chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": judge_prompt}],
            temperature=0,
        )
        faithful = judge_response.choices[0].message.content.strip().lower() == "yes"
        
        evals.record_match(faithful, expected="yes", picked="yes" if faithful else "no")
        
        return {"faithful": faithful, "response": actual_output}
    
    def run(self, recorder: RecorderBase):
        samples = evals.get_jsonl(self.samples_jsonl)
        self.eval_all_samples(recorder, samples)
        
        events = recorder.get_events("match")
        return {
            "accuracy": evals.metrics.get_accuracy(events),
            "n": len(events),
        }

Run the eval:

oaieval gpt-4o-mini my_rag_eval.faithfulness --record_path ./results/

Building a CI Evaluation Pipeline

# .github/workflows/llm-eval.yml
name: LLM Evaluation

on:
  push:
    paths:
      - 'src/llm/**'
      - 'src/rag/**'
      - 'prompts/**'

jobs:
  evaluate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: pip install deepeval openai pytest
      
      - name: Run evaluation suite
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          pytest tests/evals/ -v --tb=short
      
      - name: Check score regression
        run: |
          python scripts/check_eval_regression.py \
            --baseline results/baseline.json \
            --current results/current.json \
            --max-regression 0.05  # Fail if any metric drops > 5%

Setting Evaluation Baselines

Before any change, record your baseline scores:

# scripts/record_baseline.py
import json
from deepeval.dataset import EvaluationDataset
from deepeval.metrics import AnswerRelevancyMetric, FaithfulnessMetric

dataset = load_evaluation_dataset("evals/golden_set.json")
metrics = [
    AnswerRelevancyMetric(model="gpt-4o-mini"),
    FaithfulnessMetric(model="gpt-4o-mini"),
]

results = dataset.evaluate(metrics)

# Save baseline
baseline = {
    metric.__class__.__name__: {
        "mean_score": compute_mean_score(results, metric),
        "pass_rate": compute_pass_rate(results, metric),
    }
    for metric in metrics
}

with open("results/baseline.json", "w") as f:
    json.dump(baseline, f, indent=2)

print("Baseline recorded:")
for name, scores in baseline.items():
    print(f"  {name}: mean={scores['mean_score']:.3f}, pass_rate={scores['pass_rate']:.1%}")

Key Takeaways

  • Use temperature=0 and seed parameters for more deterministic test runs, but don't assume perfect reproducibility
  • Test quality dimensions (relevance, faithfulness, accuracy), not exact string matches
  • Hallucination detection requires either ground truth comparison, NLI entailment checking, or LLM-as-judge
  • DeepEval provides a pytest-compatible framework with batteries-included metrics
  • OpenAI Evals is better for reproducible benchmark creation and sharing
  • Always record baseline scores before making changes — catch regressions before deployment
  • Run evals in CI on prompt changes and model version updates, not just code changes

Read more

Start now free