TutorialsRAG evaluationRagasTruLensLLM observability

Building a RAG Evaluation Harness: A Practical Tutorial with Ragas and TruLens

Build a repeatable RAG evaluation harness with Ragas and TruLens: curated datasets, metric suites, trace storage, and a CI regression gate.

Retrieval-augmented generation systems fail quietly. A retriever returns plausible-but-wrong chunks, the model grounds an answer in stale context, and the response still reads fluently—so nobody notices until a customer does. The fix is a repeatable RAG evaluation harness: a fixed dataset, a defined metric suite, a trace store, and a regression gate that runs in CI. This tutorial builds one with Ragas (the metric library) and TruLens (the instrumentation and dashboard layer). They are complementary: Ragas scores answer quality against retrieved context, while TruLens records every retrieval and generation call and aggregates scores over time. You will end with a harness wired into continuous integration. This is written for engineers who already have a working RAG pipeline and need to measure it.

Version note: Both libraries have changed their APIs across releases. Pin versions in your requirements.txt (e.g., ragas, trulens) and check the migration notes for the release you adopt. The patterns below are stable; exact import paths may differ.

Why a RAG Evaluation Harness Beats Ad-Hoc Spot Checks

Manual spot checks feel productive and scale poorly. Someone asks ten questions, the answers look fine, and the change ships. Three weeks later, a retriever tweak has quietly dropped recall on a whole query class, and there is no record that it ever worked.

A harness replaces vibes with numbers you can trend. It also forces a useful discipline: separate retrieval quality from generation quality so a failure is diagnosable. When faithfulness is high but context recall is low, you know the generator is doing its job and the retriever is starving it. Without that separation, every regression looks like "the model got worse." (See also: how to diagnose RAG retrieval failures.)

The Three Failure Modes of RAG

  • Retrieval miss — the right document exists but never surfaces. The model answers from parametric memory or says it doesn't know.
  • Context dilution — too many marginal chunks crowd out the signal; the model latches onto an irrelevant passage.
  • Hallucinated grounding — the context is correct, but the answer asserts claims the context does not support.

Each maps to a different metric family:

Failure modePrimary signalReference needed?
Retrieval missContext recall (did the right doc surface?)Yes (ground-truth sources)
Context dilutionContext precision (are retrieved chunks relevant?)No
Hallucinated groundingFaithfulness / groundedness (is the answer supported?)No
Answer drift (bonus)Answer relevancy (does it address the question?)No

A harness that reports one aggregate score collapses all three into a number you cannot act on. (Related: RAG hallucination detection techniques.)

What "Harness" Means Here

A harness is four pieces wired together: a curated dataset, a metric suite, a trace store, and a regression gate. The dataset defines what "good" means. The metrics quantify it. The trace store lets you inspect individual failures. The gate blocks merges that break it.

Define your pass/fail thresholds before you ship a change. Choosing thresholds after seeing results is how teams rationalize regressions.

Ragas vs. TruLens: How the Two Tools Fit Together

The most common mistake is treating these as competitors. They operate at different layers.

Ragas in Brief

Ragas is a metric library built around an LLM judge. It provides both reference-free metrics (faithfulness, answer relevancy, and context precision, which evaluate an answer against its retrieved contexts and the question) and reference-based metrics (context recall and answer correctness, which require ground-truth answers or source IDs). You hand it questions, answers, contexts, and optionally ground truths, and it returns per-sample scores. (Read more: Ragas metrics explained.)

TruLens in Brief

TruLens is an instrumentation and observability layer. It wraps your app, records every retrieval and generation call as a trace, and runs feedback functions against those traces. Its RAG triad—context relevance, groundedness, and answer relevance—maps closely to the failure modes above. The payoff is the dashboard: every run is a row, every score is trendable. (See: TruLens RAG triad overview.)

Note that TruLens and Ragas both offer a "faithfulness/groundedness" style metric, but they are different implementations with different prompts and judges. They will not produce identical numbers. Pick one as your source of truth per metric and stay consistent.

The Integration Pattern

Wrap Ragas metrics as TruLens feedback functions so a single evaluation run produces both per-call traces and standardized scores. TruLens owns the recording and storage; Ragas owns the scoring logic. A minimal feedback function looks like this:

from ragas.metrics import faithfulness
from trulens.core import Feedback

# Adapter: turn a Ragas metric into a TruLens feedback function.
def ragas_faithfulness(question: str, answer: str, contexts: list[str]) -> float:
    score = faithfulness.score_single(
        {"question": question, "answer": answer, "contexts": contexts}
    )
    return float(score)

faithfulness_feedback = Feedback(ragas_faithfulness).on(
    {"question": "input", "answer": "output", "contexts": "contexts"}
)

Use both. Ragas alone gives you numbers with no trace to debug. TruLens alone gives you traces with metrics you have to hand-roll.

Step 1 — Assemble an Evaluation Dataset

In practice, teams get more signal from fifty to one hundred curated question/answer/reference triples than from a thousand synthetic ones. Synthetic sets are cheap to generate and tend to skew toward easy questions the model already passes, which inflates your baseline and hides real failures. (Background: building a RAG test dataset from production logs.)

Source questions from production. Pull real user queries, support tickets, and search logs. Then add the hard cases deliberately:

  • Adversarial questions where the corpus contains a plausible distractor.
  • Multi-hop questions requiring two or more documents.
  • Out-of-scope questions where the correct behavior is "I don't know."

Store everything as JSONL with question, ground_truth, and expected_sources (document IDs). The expected sources are what make retrieval failures diagnosable later—and they are required for reference-based metrics like context recall.

{"question": "What is the refund window for annual plans?",
 "ground_truth": "Annual plans can be refunded within 30 days.",
 "expected_sources": ["policy-billing-v4#refunds"]}

Keep the set versioned in the repo alongside your prompts. When you add a question, that is a reviewable change.

Step 2 — Instrument the RAG Pipeline with TruLens

Instrumentation is the part teams skip, and it is the part that makes failures debuggable.

Wrapping Retrieval and Generation

TruLens records your app as a chain. To get retrieved contexts into the trace as a structured field, return them from the recorded call alongside the answer—don't rely on them being picked up implicitly. The pattern below returns a dict so contexts are explicitly captured and available to feedback functions.

from trulens.apps.basic import TruBasicApp
from trulens.core import TruSession

session = TruSession()

def rag_app(question: str) -> dict:
    contexts = retriever.search(question, k=5)      # list[str]
    answer = generator.answer(question, contexts)   # str
    return {"answer": answer, "contexts": contexts}

tru_app = TruBasicApp(
    rag_app,
    app_name="support-rag",
    app_version="v1.2.0",
)

Because rag_app returns a dict, the recorder stores contexts as a trace field you can attach feedback to (as in the ragas_faithfulness adapter above). If your app is more complex than a single callable—multiple tools, conditional retrieval—use a custom app class with @instrument on the retrieval and generation methods so each step is its own span.

Pin the Judge

Every metric here is computed by an LLM judge, and judge choice drives your numbers. Pin three things:

  • Judge model (e.g., a specific model version, not "latest").
  • Temperature = 0 for reproducibility.
  • A calibration set: 30–50 human-labeled samples where you've recorded the "correct" score. Before trusting a metric in a gate, confirm the judge agrees with humans within your tolerance.

A flaky judge produces a flaky gate, and a flaky gate gets disabled within a month. Budget for judge latency and cost too: a 100-question set with five metrics is 500 judge calls per run—fine nightly, expensive on every push.

Step 3 — Run the Evaluation and Read the Traces

Run the full dataset through the instrumented app, then read scores back from the session. The exact API varies by version; the shape is: run inputs → collect per-sample scores → aggregate.

from trulens.core import Feedback
# ... define faithfulness_feedback, context_recall_feedback, etc.

results = []
for row in dataset:  # list of dicts loaded from JSONL
    trace = tru_app.with_record(
        tru_app.app,
        feedbacks=[faithfulness_feedback, context_recall_feedback],
    ).run(row["question"])
    results.append(trace)

In the TruLens dashboard, sort by the lowest score first. A single faithfulness failure is worth ten passes: open the trace, read the retrieved contexts, and compare them to the answer. This is the loop that turns a number into a fix. If the context was wrong, fix retrieval. If the context was right but the answer wasn't, fix the prompt or the model.

Step 4 — Gate the Build in CI

The gate is what makes the harness a harness and not a dashboard. Read back the latest run's aggregate scores, compare them to committed thresholds, and exit non-zero on regression.

# scripts/gate.py
import json, sys

THRESHOLDS = {
    "faithfulness": 0.85,
    "context_recall": 0.80,
    "context_precision": 0.75,
    "answer_relevancy": 0.80,
}

with open("eval_results.json") as f:
    run = json.load(f)

failures = []
for metric, floor in THRESHOLDS.items():
    actual = run["aggregates"][metric]
    if actual < floor:
        failures.append(f"{metric}: {actual:.3f} < {floor}")

if failures:
    print("REGRESSION:\n" + "\n".join(failures))
    sys.exit(1)
print("All metrics within threshold.")

Two statistical caveats before you trust this in a merge gate:

  • Small N is noisy. With 100 samples, a 2-point drop may be sampling variance, not a regression. Either set thresholds with margin below your baseline, or track a rolling window and fail only on sustained drops.
  • Pin the dataset and seed. A gate that runs against a shifting question set is measuring the set, not the system.

Wire gate.py into your CI as a step that runs after your test suite. Run the full harness nightly; run a fast subset (say, 20 questions) on every pull request.

Putting It Together

The harness is four files and one CI step:

  1. eval_set.jsonl — curated, versioned, with expected_sources.
  2. instrument.py — TruLens-wrapped app returning {answer, contexts}.
  3. evaluate.py — Ragas metrics adapted as TruLens feedback, judge pinned.
  4. gate.py — thresholds checked against the latest run, exit code enforced.

Start small. Twenty curated questions with a faithfulness and a context-recall metric will catch more regressions than a thousand synthetic ones with a single aggregate score. Then grow the set every time production surfaces a failure the harness missed—that is the flywheel that makes the system trustworthy.

ShareX / TwitterLinkedIn
← Back to Learn