Skip to content

Evaluating LLM Hallucinations: The RAG Triad in CI/CD

Why manual prompt reviews fail, how the RAG Triad quantifies context relevance and groundedness, and how to automate regression testing in production CI/CD.

Evaluating LLM Hallucinations: The RAG Triad in CI/CD

Most engineering teams discover generative AI regressions only after their enterprise customers report them in production tickets. A developer tweaks a system prompt to sound more concise, runs three test queries in a local notebook, and merges the pull request with confidence. Two days later, customer support escalates that the assistant is inventing nonexistent billing policies and citing deprecated API flags. In generative systems, this failure happens because natural language applications lack the deterministic unit tests that protect traditional software. When retrieval parameters, embedding models, or prompt instructions change, teams cannot rely on manual eyeball reviews to detect hallucinations. Adopting the RAG Triad evaluation framework converts subjective quality assessments into reproducible CI/CD test assertions, preventing hallucination regressions before code deploys.

Quick RAG Evaluation Triage Checklist

  1. Establish a Golden Dataset: Assemble 50 to 100 production user queries covering standard tasks, ambiguous questions, and adversarial edge cases along with ground-truth reference context.
  2. Implement RAG Triad Metrics: Measure Context Relevance (retrieval precision), Groundedness (faithfulness to context), and Answer Relevance (query alignment) on every prompt modification.
  3. Automate Pull Request Quality Gates: Embed evaluation suites into GitHub Actions, configuring hard assertion thresholds (e.g., Groundedness ≥ 0.85) to block regressions automatically. Similar testing discipline is required when auditing AI-generated codebases.
  4. Schedule an AI Architecture Diagnostic: When generative pipelines suffer unpredictable latency or uncontrolled vector spend, engineering teams engage our 48-Hour Codebase Audit to audit chunking strategies, vector indexing configurations, and multi-tenant security perimeters.

The Blind Spot of Generative Prototyping

Software engineering has spent decades developing deterministic testing methodologies: unit tests, integration suites, type checking, and mutation testing. If a pull request modifies a SQL query, automated tests immediately verify that the function returns the expected columns and handles null records.

Generative AI pipelines destroy this testing determinism. A RAG pipeline comprises multiple independent probabilistic components operating in sequence:

+-----------------------------------------------------------------------------------+
|                        Probabilistic RAG Failure Surface                          |
+-----------------------------------------------------------------------------------+
| 1. Query Processing: Embedding Model vectorizes user prompt                       |
|    - Vulnerability: Semantic drift, out-of-vocabulary terms                      |
|                                                                                   |
| 2. Context Retrieval: Vector DB queries top-k nearest neighbors                   |
|    - Vulnerability: Distractor chunks, low cosine similarity, noisy metadata     |
|                                                                                   |
| 3. Context Assembly: Chunks injected into system prompt window                    |
|    - Vulnerability: Context stuffing, lost-in-the-middle positioning             |
|                                                                                   |
| 4. Generation: LLM synthesizes natural language response                          |
|    - Vulnerability: Sycophancy, hallucinated extrapolation, ignored constraints  |
+-----------------------------------------------------------------------------------+

When an engineer adjusts a retrieval parameter (such as reducing top_k from 5 to 3 or altering chunk overlap), the change may improve response speed by 200 milliseconds while silently starving the LLM of necessary factual context on 8% of technical queries.

Without automated statistical evaluation, teams operate blind. They celebrate localized improvements on their own test prompts while degrading production reliability for thousands of concurrent users.

The RAG Triad: Three Mathematical Pillars of Faithfulness

The RAG Triad framework, formulated by the maintainers of TruLens and formalized across open-source evaluation systems like DeepEval, isolates generative performance into three measurable dimensions: Context Relevance, Groundedness, and Answer Relevance.

                         [ USER QUERY ]
                           /        \
                          /          \
     (Context Relevance) /            \ (Answer Relevance)
                        /              \
                       v                v
             [ RETRIEVED CONTEXT ] ---> [ GENERATED ANSWER ]
                               (Groundedness)

1. Context Relevance: Auditing Retrieval Precision

Context Relevance measures whether the document chunks retrieved from the vector database contain information directly pertinent to resolving the user query.

Context Relevance Score = (Number of Relevant Sentences in Context) / (Total Sentences in Context)

If a user asks “How do I configure mutual TLS in ingress controllers?” and the vector database returns four chunks describing standard HTTP routing alongside one chunk on TLS certificates, the Context Relevance score drops to 0.25.

Low context relevance introduces noise into the prompt. When language models encounter irrelevant context, their attention heads distribute probability mass across distractor tokens, drastically increasing the likelihood of hallucinated answers. Retrieval noise and index tuning are explored in depth in our guide to production RAG cost and architecture traps.

2. Groundedness (Faithfulness): Auditing Factuality

Groundedness measures whether every claim made in the generated response can be mathematically verified against the retrieved context chunks.

Groundedness Score = (Number of Supported Statements in Output) / (Total Statements in Output)

To compute Groundedness, the evaluation engine breaks the LLM’s generated response into discrete propositional claims. Each claim is evaluated against the retrieved context:

  • Statement 1: “The default timeout is 30 seconds.” (Supported in Chunk A -> Valid)
  • Statement 2: “You must pass the —strict flag.” (Supported in Chunk B -> Valid)
  • Statement 3: “This command requires cluster admin rights.” (Not mentioned in any chunk -> HALLUCINATION)

In this example, 2 out of 3 statements are supported, resulting in a Groundedness score of 0.67. If your production threshold requires 0.90, this generation fails the test assertion.

3. Answer Relevance: Auditing Query Alignment

Answer Relevance measures whether the generated response directly answers the user’s explicit question, independent of whether the context was accurate.

Answer Relevance Score = Cosine_Similarity(Embedding(Generated_Answer), Embedding(Hypothetical_Queries))

An answer can achieve 100% Groundedness while failing Answer Relevance completely. For instance, if a user asks “How do I increase database connection limits?” and the assistant responds “PostgreSQL was created in 1996 by the POSTGRES project at UC Berkeley”, the answer is historically true and fully grounded in the provided Wikipedia chunk, but completely irrelevant to the user’s operational problem.

Implementing Automated Evaluation in TypeScript with DeepEval

To integrate RAG Triad evaluations directly into modern TypeScript CI/CD pipelines, teams construct automated test suites using evaluation harnesses.

Below is an automated evaluation module implementing the RAG Triad using TypeScript:

// tests/rag-eval.test.ts
import { describe, it, expect } from 'vitest';
import OpenAI from 'openai';

interface RagTestCase {
  query: string;
  expectedContextKeywords: string[];
}

interface EvaluationResult {
  contextRelevance: number;
  groundedness: number;
  answerRelevance: number;
  passed: boolean;
}

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

/**
 * Evaluates Groundedness using an LLM-as-a-Judge prompt with structured scoring.
 */
async function evaluateGroundedness(context: string, answer: string): Promise<number> {
  const prompt = `
You are an impartial, highly rigorous evaluation judge.
Your task is to determine whether the statements in the GENERATED ANSWER are strictly supported by the RETRIEVED CONTEXT.

RETRIEVED CONTEXT:
${context}

GENERATED ANSWER:
${answer}

Rules:
1. Extract all factual statements from the GENERATED ANSWER.
2. Check if each statement is explicitly supported by the RETRIEVED CONTEXT.
3. If an answer makes a claim not present in the context, mark it as ungrounded.
4. Output a single JSON object: { "totalStatements": number, "supportedStatements": number, "score": number }
`;

  const response = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: prompt }],
    response_format: { type: 'json_object' },
    temperature: 0.0,
  });

  const parsed = JSON.parse(response.choices[0].message.content || '{}');
  return typeof parsed.score === 'number' ? parsed.score : 0.0;
}

/**
 * Automated RAG Test Suite executed on pull requests.
 */
describe('Production RAG Quality Gate', () => {
  const goldenDataset: RagTestCase[] = [
    {
      query: 'What is the maximum execution duration for serverless background tasks?',
      expectedContextKeywords: ['timeout', 'seconds', 'execution limit'],
    },
    {
      query: 'How do you rotate JWT signing keys without invalidating active sessions?',
      expectedContextKeywords: ['jwks', 'key id', 'kid', 'grace period'],
    },
  ];

  it.each(goldenDataset)('should pass RAG Triad quality gates for: $query', async ({ query }) => {
    // 1. Execute your real retrieval pipeline
    const retrievedChunks = await mockRetrieveContext(query);
    const combinedContext = retrievedChunks.join('\n\n');

    // 2. Execute your real generation pipeline
    const generatedAnswer = await mockGenerateAnswer(query, combinedContext);

    // 3. Compute Groundedness score
    const groundedness = await evaluateGroundedness(combinedContext, generatedAnswer);

    // 4. Assert quality thresholds
    expect(groundedness).toBeGreaterThanOrEqual(0.85);
  });
});

async function mockRetrieveContext(query: string): Promise<string[]> {
  return [
    'Serverless background task execution ceiling is capped at 900 seconds (15 minutes).',
    'Jobs exceeding this limit must be broken into idempotent queue messages.',
  ];
}

async function mockGenerateAnswer(query: string, context: string): Promise<string> {
  return 'The maximum execution duration for serverless background tasks is 15 minutes (900 seconds). Tasks running longer must be split into queued steps.';
}

By constraining the judge model to low-cost, high-speed models (gpt-4o-mini or Claude 3.5 Haiku) with temperature: 0.0, the entire 50-query golden test suite executes in under 45 seconds and costs less than $0.15 per test run. Integrating structured JSON guarantees prevents evaluator formatting failures, following the principles detailed in our guide to structured JSON extraction from LLMs.

Building a Golden Dataset That Stresses Production Edges

An evaluation suite is only as robust as the golden dataset that powers it. Testing against 50 trivial questions that your model already answers easily creates a false sense of security.

+-----------------------------------------------------------------------------------+
|                        Golden Dataset Composition Blueprint                       |
+-----------------------------------------------------------------------------------+
| Query Category        | Percentage | Purpose & Edge Scenario                      |
|-----------------------|------------|----------------------------------------------|
| Core Canonical Queries| 40%        | High-volume user questions with exact answers|
| Ambiguous / Underspec | 20%        | Prompts that require requesting clarification|
| Distractor / Negative | 20%        | Queries where retrieved context lacks answers|
| Adversarial Injections| 20%        | Prompts attempting prompt leak or rule bypass|
+-----------------------------------------------------------------------------------+

Handling Negative and Unanswerable Queries

The most vital 20% of your evaluation dataset consists of questions that your retrieval system cannot answer from its documentation (e.g., “What is the refund policy for enterprise hardware?” when your database only documents software licenses).

A high-performing RAG pipeline must reliably recognize missing evidence and output: “I do not have sufficient information in the provided documentation to answer this question.”

If your evaluation suite does not test unanswerable queries, your assistant will hallucinate plausible-sounding explanations whenever retrieval returns empty or low-confidence matches.

Embedding RAG Triad Quality Gates in CI/CD

To prevent regressions from merging into production branches, embed the evaluation suite as a mandatory status check in your CI/CD configuration:

# .github/workflows/rag-evaluation.yml
name: RAG Evaluation Suite

on:
  pull_request:
    paths:
      - 'prompts/**'
      - 'src/ai/**'
      - 'knowledge_base/**'

jobs:
  evaluate-rag:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'
      
      - run: npm ci
      
      - name: Run RAG Triad Regression Suite
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          EVAL_DATASET_PATH: ./tests/fixtures/golden-dataset.json
        run: npx vitest run tests/rag-eval.test.ts --reporter=verbose

Architectural Quality Gate Rules:

  1. Groundedness Floor (0.85): Any PR that causes Groundedness to drop below 0.85 fails the build automatically. Factual hallucination is treated as a breaking bug.
  2. Context Relevance Floor (0.75): Ensures retrieval is not stuffing unneeded tokens into prompts, keeping LLM API token invoices minimal.
  3. No Regressions on Golden Queries: Even if the average score across 100 queries rises, if any single mission-critical canonical query drops in Groundedness, the pull request requires manual approval.

Architectural Comparison: Evaluation Frameworks

Choosing the right testing harness determines both testing execution speed and diagnostic clarity:

Evaluation HarnessPrimary LanguageBuilt-in RAG Triad?CI/CD IntegrationExecution Speed
Manual Playground ReviewsNoneNo (Ad hoc)ImpossibleExtremely slow
DeepEvalPython / TSYes (Native metrics)Native CLI & PytestFast (Parallel async)
TruLensPythonYes (Core concept)High (Dashboard export)Moderate (Instrumented)
RagasPythonYes (Faithfulness focus)High (HuggingFace native)Moderate
Custom In-House JudgeTypeScript / NodeYes (Custom prompt)Complete controlFastest (Lightweight)

Production Engineering Runbook for AI Quality Assurance

To ensure your generative AI pipelines maintain strict factual accuracy under continuous deployment:

  1. Automate Dataset Generation with Production Telemetry: Capture real production user queries and anonymize them into candidate evaluation fixtures, prioritizing questions that triggered thumbs-down ratings or re-prompts.
  2. Freeze Evaluation Prompts: Do not modify your judge model prompts and application system prompts in the same pull request. Isolate evaluation metric adjustments to ensure historical scoring continuity.
  3. Run Multi-Judge Consensus for Mission-Critical SLAs: In enterprise compliance domains (healthcare, fintech, legal), evaluate Groundedness across two distinct model providers (e.g., GPT-4o-mini and Claude 3.5 Haiku). Only mark a response grounded if both judges agree.
  4. Engage an Architectural Diagnostic: When generative pipelines experience recurring hallucinations, uncontrolled token spending, or vector retrieval drift, schedule our 48-Hour Codebase Audit to audit RAG retrieval bounds, embedding chunking, and system prompt boundaries.

Replacing subjective prompt evaluations with the RAG Triad guarantees that every prompt update, retrieval tweak, and embedding migration is backed by verifiable mathematical quality assertions.

Written By

Elena Rostova

Product Strategy Lead

Product and operations lead dedicated to helping non-technical founders navigate technical scale and architectural decisions. Advises founders on technical debt triage, cloud unit economics, and rapid pre-launch risk evaluation.

Practice: Vexn • Focus: Founder Strategy, Operational Risk & Scale
Frequently Asked Questions
What is the RAG Triad in LLM evaluation?
The RAG Triad is an evaluation framework that isolates the three failure modes of retrieval-augmented generation: Context Relevance (measuring whether retrieved chunks are relevant to the query), Groundedness (measuring whether the model's claims are mathematically supported by the retrieved context), and Answer Relevance (measuring whether the output answers the user query).
Why do manual prompt evaluations fail at production scale?
Manual prompt engineering relies on small, subjective sample tests (evaluating 5 to 10 queries in a playground). In production, subtle adjustments to system prompts, chunk overlap, or top-k retrieval thresholds create silent regression cascades, causing hallucination rates to spike on edge cases that manual reviews never anticipate.
How does Groundedness differ from Answer Relevance?
Groundedness (also known as faithfulness) checks if the generated statements can be strictly traced back to factual assertions in the retrieved document context. Answer Relevance checks if the response directly addresses the user's intent. An answer can be completely grounded in context while remaining irrelevant to the question, or highly relevant while containing ungrounded hallucinations.
How can teams automate RAG evaluation in CI/CD pipelines?
Teams compile a curated golden dataset of 50 to 100 representative queries with expected context chunks. In pull request workflows, automated testing frameworks (such as DeepEval or TruLens) run evaluation pipelines using fast, cost-effective judge models to score the RAG Triad, failing builds if Groundedness or Relevance scores drop below defined statistical thresholds.
Need an Architectural Audit?

Have our team inspect your AI-generated codebase.

48-hour turnaround with direct pull requests fixing security and scale bottlenecks.

Request Audit