Search Tutorials
--Ads--RAGAS Tutorial: Evaluating RAG Step by Step
Install RAGAS, configure a judge model and compute faithfulness, relevancy and context metrics.
RAGAS is a popular open-source library for evaluating RAG systems. Its metrics use an LLM as a judge to score how faithful answers are to the retrieved context, how relevant they are to the question, and how well retrieval covered the evidence. This lesson installs RAGAS, configures a judge model, scores single samples and a whole test set, and explains how to read the results.
What you will learn
- How to install RAGAS and configure a judge LLM and embeddings
- How to compute Faithfulness, Answer Relevancy, Context Precision and Context Recall
- How to score a whole test set and summarise the results
- How to interpret scores and avoid common pitfalls
Prerequisites
- Generation Metrics (what the metrics mean)
- An OpenAI API key for the judge in this example (OpenAI API setup)
This lesson uses RAGAS's collections metric API (ragas.metrics.collections), which the RAGAS documentation recommends as of November 2026. The older API (ragas.metrics classes with SingleTurnSample and the evaluate() function) is deprecated and is being replaced by RAGAS's experiment workflow. Older tutorials you find online often use it. Check the RAGAS documentation for your installed version.
Installation
pip install ragas openai python-dotenv pandas
Step 1: Configure the judge
RAGAS metrics need a judge LLM, and Answer Relevancy also needs an embedding model. llm_factory and embedding_factory create them from a provider client:
import asyncio
from dotenv import load_dotenv
from openai import AsyncOpenAI
from ragas.embeddings.base import embedding_factory
from ragas.llms import llm_factory
from ragas.metrics.collections import AnswerRelevancy, ContextPrecision, ContextRecall, Faithfulness
load_dotenv() # OPENAI_API_KEY
client = AsyncOpenAI()
judge = llm_factory("gpt-6.2-sol", client=client) # use a current model id from the provider
embeddings = embedding_factory("openai", model="text-embedding-3-small", client=client)
faithfulness = Faithfulness(llm=judge)
relevancy = AnswerRelevancy(llm=judge, embeddings=embeddings)
precision = ContextPrecision(llm=judge)
recall = ContextRecall(llm=judge)
The RAGAS quickstart also shows creating the judge with an Anthropic client (llm_factory(model, provider="anthropic", client=Anthropic())). Use a judge model at least as capable as the model being evaluated.
Step 2: Score one sample
Each metric scores the fields it needs, and returns a result whose .value is a number between 0 and 1:
question = "How many paid leave days do first-year employees get?"
contexts = ["Employees in their first year receive 18 days of paid leave.",
"Sick leave is separate: 10 days per year."]
answer = "First-year employees get 18 days of paid leave, plus a 2-day birthday bonus."
reference = "First-year employees get 18 days of paid leave."
async def score_one():
f = await faithfulness.ascore(user_input=question, response=answer, retrieved_contexts=contexts)
r = await relevancy.ascore(user_input=question, response=answer)
p = await precision.ascore(user_input=question, reference=reference, retrieved_contexts=contexts)
c = await recall.ascore(user_input=question, retrieved_contexts=contexts, reference=reference)
print(f"faithfulness={f.value:.2f} relevancy={r.value:.2f} precision={p.value:.2f} recall={c.value:.2f}")
asyncio.run(score_one())
faithfulness=0.50 relevancy=0.94 precision=1.00 recall=1.00
The invented "2-day birthday bonus" is not in the contexts, so faithfulness drops to about 0.5 (one of two claims is supported). Retrieval was fine (precision and recall are 1.0). This is exactly the diagnosis RAGAS is for: the problem is in generation, not retrieval. Your numbers will vary slightly between runs.
Each metric also has a synchronous .score(...) method with the same arguments.
Step 3: Score a whole test set
Run your RAG pipeline over a golden test set (Building a Golden Test Set), then score every row concurrently:
import json
import pandas as pd
def load_run(path: str) -> list[dict]:
"""JSONL rows with: question, retrieved_texts, answer, reference_answer (see the evaluation module)."""
return [json.loads(line) for line in open(path, encoding="utf-8")]
async def score_row(row: dict) -> dict:
q, ctx, ans, ref = row["question"], row["retrieved_texts"], row["answer"], row["reference_answer"]
f, r, p, c = await asyncio.gather(
faithfulness.ascore(user_input=q, response=ans, retrieved_contexts=ctx),
relevancy.ascore(user_input=q, response=ans),
precision.ascore(user_input=q, reference=ref, retrieved_contexts=ctx),
recall.ascore(user_input=q, retrieved_contexts=ctx, reference=ref),
)
return {"question": q, "faithfulness": f.value, "answer_relevancy": r.value,
"context_precision": p.value, "context_recall": c.value}
async def score_run(path: str, concurrency: int = 4) -> pd.DataFrame:
semaphore = asyncio.Semaphore(concurrency) # stay within rate limits
async def limited(row):
async with semaphore:
return await score_row(row)
rows = await asyncio.gather(*(limited(r) for r in load_run(path)))
return pd.DataFrame(rows)
df = asyncio.run(score_run("eval_runs/baseline.jsonl"))
print(df.mean(numeric_only=True).round(3))
print(df.sort_values("faithfulness").head(5)[["question", "faithfulness"]]) # worst cases first
faithfulness 0.912
answer_relevancy 0.874
context_precision 0.803
context_recall 0.856
Reading the results
| Low metric | Means | Look at |
|---|---|---|
| Context recall | Evidence needed for the reference answer was not retrieved | Chunking, embeddings, hybrid search, query rewriting |
| Context precision | Relevant chunks are ranked low or mixed with noise | Reranking, smaller k |
| Faithfulness | The answer contains unsupported claims | Prompt grounding rules, citations |
| Answer relevancy | The answer drifts from the question | Prompt instructions, answer length |
Practical advice
- Validate the judge: compare RAGAS scores with human judgements on 30–50 samples before trusting them (LLM-as-Judge).
- Pin versions of RAGAS and the judge model; scores shift when either changes.
- Watch cost: each metric makes one or more LLM calls per sample. Score a fixed, representative set rather than all traffic.
- Read the worst cases: averages hide the failures you need to fix.
Common errors and troubleshooting
ImportErrorforragas.metrics.collections: your RAGAS version predates the collections API; upgrade, or follow the documentation for your version.- Rate-limit errors: lower the concurrency semaphore.
- Deprecation warnings from
evaluate(): you are using the legacy workflow; prefer the metric classes as above or RAGAS's experiment workflow. - Empty contexts: context metrics need at least one retrieved text; log retrieval output in your runs.
Key takeaways
- RAGAS scores faithfulness, answer relevancy, context precision and context recall with an LLM judge.
- Current API: metric classes from
ragas.metrics.collections, created withllm=(andembeddings=), scored withascore, read from.value. - Use the pattern of low scores to locate failures in retrieval or generation.
- Validate the judge, pin versions and read the worst cases.
Frequently asked questions
Do I need reference answers?
Faithfulness and answer relevancy do not; context precision (with reference) and context recall do.
RAGAS or my own judge prompts?
RAGAS gives tested, comparable metrics quickly; your own judges capture domain-specific rules. Many teams use both.
Practice exercises
- Score two pipeline versions (with and without reranking) and compare context precision.
- Add a column for the number of retrieved chunks and check whether more chunks lower faithfulness.
Related tutorials
- RAG Evaluation Frameworks
- DeepEval and TruLens Tutorial
- Project: RAG Evaluation Dashboard