StackPractices
intermediate By Mathias Paulenko

Evaluate RAG Quality with RAGAS Metrics

Measure RAG pipeline quality using RAGAS framework metrics — faithfulness, answer relevancy, context precision, and context recall for objective evaluation

Topics: ai

Overview

RAG pipelines are awkward to evaluate — you can’t just eyeball a few outputs and call it tested. Was the retrieved context actually relevant? Is the answer grounded in it or confidently made up? RAGAS (Retrieval-Augmented Generation Assessment) answers that with an LLM-as-judge: four automated metrics you can run on every change instead of trusting vibes.

This recipe builds a complete evaluation loop: a test dataset, the four core metrics (faithfulness, answer relevancy, context precision, context recall), a report printer, and a helper that scores your own pipeline against a test set. If you don’t have a pipeline to evaluate yet, Local RAG with Chroma gets you one in an afternoon. For the wider eval picture — eval-driven prompts, golden sets, regression gates — see the complete LLM evaluation guide and the RAG evaluation checklist.

When to Use This

  • Gating a RAG pipeline before it ships to production
  • Comparing chunking strategies, embedding models, or LLMs with numbers instead of opinions
  • Regression testing in CI when any RAG component changes
  • Setting a baseline so “the pipeline got worse” is measurable, not anecdotal

Skip this if you only have a handful of queries — with under ~20 test cases the averages are noisy enough to mislead, and a careful manual review is faster to set up.

Prerequisites

  • Python 3.10+
  • ragas package (pip install ragas — the examples target the 0.2+ schema)
  • langchain-openai for the evaluator LLM
  • datasets for the evaluation dataset
  • An OpenAI API key

Solution

1. Install Dependencies

pip install ragas langchain-openai datasets

2. Prepare Evaluation Dataset

from datasets import Dataset

# RAGAS 0.2+ expects: user_input, response, retrieved_contexts, reference
# (older 0.1.x docs use question/answer/contexts/ground_truth)
eval_data = {
    "user_input": [
        "What is the Redis cache-aside pattern?",
        "How does Docker Compose define multi-container apps?",
        "What are PostgreSQL ACID compliance features?",
    ],
    "response": [
        "The cache-aside pattern checks the cache first, and if data is missing, loads it from the database and sets it in the cache with a TTL.",
        "Docker Compose uses a YAML file to define multi-container applications, specifying services, networks, and volumes.",
        "PostgreSQL provides ACID compliance through atomic transactions, consistent constraints, isolation levels, and durable write-ahead logging.",
    ],
    "retrieved_contexts": [
        [
            "Redis cache-aside: application checks cache first. On cache miss, loads from database and sets cache entry with TTL.",
        ],
        [
            "Docker Compose is a tool for defining multi-container Docker applications in a YAML file with services, networks, and volumes.",
        ],
        [
            "PostgreSQL ensures ACID compliance: atomicity via transactions, consistency via constraints, isolation via MVCC, durability via WAL.",
        ],
    ],
    "reference": [
        "Cache-aside checks cache first, loads from DB on miss, sets cache with TTL.",
        "Docker Compose defines multi-container apps in YAML with services, networks, and volumes.",
        "PostgreSQL ACID: atomicity (transactions), consistency (constraints), isolation (MVCC), durability (WAL).",
    ],
}

eval_dataset = Dataset.from_dict(eval_data)

3. Run RAGAS Evaluation

from ragas import evaluate
from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_precision,
    context_recall,
)
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

# LLM and embeddings for evaluation
eval_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
eval_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")

# Run evaluation with all four core metrics
results = evaluate(
    eval_dataset,
    metrics=[
        faithfulness,
        answer_relevancy,
        context_precision,
        context_recall,
    ],
    llm=eval_llm,
    embeddings=eval_embeddings,
)

# Convert to pandas DataFrame for analysis
df = results.to_pandas()
print(df[["user_input", "faithfulness", "answer_relevancy", "context_precision", "context_recall"]])

4. Interpret the Metrics

def print_eval_report(results) -> None:
    """Print a formatted evaluation report."""
    df = results.to_pandas()

    print("=" * 60)
    print("RAGAS Evaluation Report")
    print("=" * 60)

    metrics = ["faithfulness", "answer_relevancy", "context_precision", "context_recall"]

    for metric in metrics:
        scores = df[metric].tolist()
        avg = sum(scores) / len(scores)
        print(f"\n{metric.replace('_', ' ').title()}:")
        print(f"  Average: {avg:.3f}")
        print(f"  Min:     {min(scores):.3f}")
        print(f"  Max:     {max(scores):.3f}")
        for i, score in enumerate(scores):
            print(f"  Q{i+1}: {score:.3f}")

    print("\n" + "=" * 60)
    aggregate_score = sum(df[m].mean() for m in metrics) / len(metrics)
    print(f"Aggregate Score: {aggregate_score:.3f}")

print_eval_report(results)

5. Evaluate Your Own RAG Pipeline

def evaluate_rag_pipeline(
    rag_pipeline,
    test_cases: list[dict],
):
    """Evaluate a RAG pipeline against test cases.

    Args:
        rag_pipeline: Object with .ask(query) -> {answer, sources} method.
        test_cases: List of {question, ground_truth} dicts.

    Returns:
        RAGAS evaluation results.
    """
    eval_rows = []

    for case in test_cases:
        # Run the RAG pipeline
        result = rag_pipeline.ask(case["question"])

        eval_rows.append({
            "user_input": case["question"],
            "response": result["answer"],
            "retrieved_contexts": [s["text"] for s in result["sources"]],
            "reference": case["ground_truth"],
        })

    dataset = Dataset.from_list(eval_rows)

    return evaluate(
        dataset,
        metrics=[faithfulness, answer_relevancy, context_precision, context_recall],
        llm=eval_llm,
        embeddings=eval_embeddings,
    )

# Usage — my_rag_pipeline is your own RAG object exposing .ask(query) -> {answer, sources}
test_cases = [
    {
        "question": "What data structures does Redis support?",
        "ground_truth": "Redis supports strings, hashes, lists, sets, sorted sets, streams, and more.",
    },
    {
        "question": "How does PostgreSQL handle isolation?",
        "ground_truth": "PostgreSQL handles isolation via MVCC (Multi-Version Concurrency Control).",
    },
]

results = evaluate_rag_pipeline(my_rag_pipeline, test_cases)
print_eval_report(results)

How It Works

flowchart diagram: Test dataset<br/>user_input + reference

The four metrics split into two pairs that measure different halves of the pipeline:

  • Faithfulness — is the answer grounded in the retrieved context? Each claim in the answer is checked against the context. Low faithfulness = hallucination. This is your generation-quality signal.
  • Answer relevancy — does the answer actually address the question? The judge generates questions that the answer would plausibly answer and embeds them against the original; it catches “correct but off-topic” responses.
  • Context precision — did retrieval surface the useful chunks, or bury them under noise? It scores whether the relevant context ranks near the top.
  • Context recall — did retrieval fetch everything needed for the reference answer? Low recall means the retriever missed key material, and no generation fix will save you.

That’s the diagnostic trick: faithfulness and relevancy grade the generator, precision and recall grade the retriever. When a pipeline regresses, the metric that dropped tells you which half to debug.

Two caveats that keep scores honest:

  • The judge is a model too. gpt-4o-mini is cheap but inconsistent on borderline cases; gpt-4o gives steadier verdicts. Whatever you pick, pin it — changing evaluator models invalidates your baseline.
  • Small samples lie. Three test cases can’t produce a stable average. Twenty or more per configuration is where the numbers start meaning something, and more is better when the metric you’re watching moves in tenths.

Variants

Custom LLM-Judged Metrics

from ragas.metrics import AspectCritic

# AspectCritic judges a sample against a plain-language definition —
# the supported way to add domain-specific checks in ragas 0.2+
conciseness = AspectCritic(
    name="conciseness",
    definition=(
        "Return 1 if the answer conveys the key facts in 60 words or fewer "
        "without unnecessary preamble, 0 otherwise."
    ),
    llm=eval_llm,
)

results = evaluate(
    eval_dataset,
    metrics=[faithfulness, conciseness],
    llm=eval_llm,
    embeddings=eval_embeddings,
)

Batch Evaluation with CSV

import pandas as pd

def evaluate_from_csv(csv_path: str) -> pd.DataFrame:
    """Load test cases from CSV and evaluate.

    CSV columns: question, answer, contexts (semicolon-separated), ground_truth.
    """
    df = pd.read_csv(csv_path)

    eval_data = {
        "user_input": df["question"].tolist(),
        "response": df["answer"].tolist(),
        "retrieved_contexts": [c.split(";") for c in df["contexts"]],
        "reference": df["ground_truth"].tolist(),
    }

    dataset = Dataset.from_dict(eval_data)
    results = evaluate(
        dataset,
        metrics=[faithfulness, answer_relevancy, context_precision, context_recall],
        llm=eval_llm,
        embeddings=eval_embeddings,
    )
    return results.to_pandas()

Compare Two RAG Configurations

def compare_configs(
    pipeline_a,
    pipeline_b,
    test_cases: list[dict],
) -> pd.DataFrame:
    """Compare two RAG configurations side by side."""
    results_a = evaluate_rag_pipeline(pipeline_a, test_cases).to_pandas()
    results_b = evaluate_rag_pipeline(pipeline_b, test_cases).to_pandas()

    comparison = pd.DataFrame({
        "question": results_a["user_input"],
        "faithfulness_a": results_a["faithfulness"],
        "faithfulness_b": results_b["faithfulness"],
        "relevancy_a": results_a["answer_relevancy"],
        "relevancy_b": results_b["answer_relevancy"],
        "precision_a": results_a["context_precision"],
        "precision_b": results_b["context_precision"],
        "recall_a": results_a["context_recall"],
        "recall_b": results_b["context_recall"],
    })

    comparison["faithfulness_diff"] = comparison["faithfulness_b"] - comparison["faithfulness_a"]
    comparison["relevancy_diff"] = comparison["relevancy_b"] - comparison["relevancy_a"]

    return comparison

Best Practices

  • Pin your evaluator model — scores from gpt-4o-mini and gpt-4o aren’t comparable; pick one per project and stick with it, or your baselines mean nothing
  • Build diverse test cases — factual, comparative, procedural, and edge cases; 20+ per configuration before trusting averages
  • Source ground truth from domain experts — auto-generated references carry the generator’s own biases
  • Run evals on every RAG change — chunking, embedding model, LLM, or prompt-template edits move all four metrics
  • Store baselines — keep last-known-good scores in CI and fail the build when a metric drops past a threshold

Common Mistakes

  • Evaluating without reference answers — context recall needs them; without references you only get three of the four metrics
  • Using the same LLM for generation and judging — models grade their own output leniently; use a different model, or at least a different temperature
  • Too few test cases — 3-5 cases produce noise, not signal; you’ll chase phantom regressions
  • Watching only faithfulness — high relevancy with low faithfulness is confident hallucination, and a perfect score on a broken retriever still means wrong answers
  • Swapping the evaluator between runs — a score bump from changing judge models looks exactly like an improvement but proves nothing

Further Reading

The complete runnable project — dataset builder, evaluation runner, and report printer — is in the companion repository.

Frequently Asked Questions

What is a good RAGAS score?

Rough guide: below 0.5 means something is broken, 0.7 is workable, 0.8+ is good, 0.9+ is excellent. Treat them as relative signals against your own baseline rather than absolute grades — a 0.05 drop after a change matters more than hitting a magic number.

How much does a RAGAS evaluation cost?

Each metric makes 1-3 judge calls per test case. Twenty cases across four metrics on gpt-4o-mini lands around half a dollar; on gpt-4o it's several times that. For a zero-cost option, point llm at a local model through Ollama or another LangChain-compatible provider — just expect noisier verdicts.

Can I use RAGAS with non-OpenAI models?

Yes. RAGAS takes any LangChain chat model and embeddings via the llm and embeddings parameters — Anthropic, local models, whatever you run. Judgment quality varies, so re-baseline when you switch.

How often should I run RAGAS?

On every change to a RAG component — chunk size, embedding model, LLM, prompt template — ideally as a CI step with the previous baseline for comparison. There's no value in running it daily against an unchanged pipeline.

What is a good faithfulness score?

Above 0.8 means the answer is mostly grounded in the retrieved context. Below 0.5 the model is generating beyond the sources — check chunk size, retrieval quality, and whether the prompt tells the model to stick to context.

My dataset uses question/answer/contexts/ground_truth — why does evaluation fail?

That naming is the older RAGAS 0.1.x schema. On 0.2+, rename the columns to user_input, response, retrieved_contexts, and reference (as in the examples above), or pin ragas<0.2 in your requirements.

Can I add custom metrics to RAGAS?

Yes — AspectCritic lets you define an LLM-judged check in plain language (the conciseness example above). For fully deterministic checks you can subclass the metric classes, but AspectCritic covers most domain needs like citation accuracy or format compliance.