The hardest part of building a RAG system isn't getting it to work. It's knowing when it stops working. RAG fails silently — the system retrieves irrelevant context, hallucinates an answer that sounds plausible, and you don't find out until a user complains. Or worse, you push a "improvement" (new embedding model, different chunk size, updated prompts) and have no way to tell whether it actually helped.
You need an evaluation framework that runs automatically, measures what matters, and catches regressions before your users do. This post builds one from scratch using Gemini 2.5 Pro as an LLM judge, implementing the RAGAS methodology adapted for production use.
What to measure
RAG pipelines have two failure modes: retrieval failures (wrong chunks) and generation failures (wrong answers from right chunks). You need metrics for both.
| Metric | What it catches | Component |
|---|---|---|
| Context Precision | Irrelevant chunks ranked too high | Retriever |
| Context Recall | Relevant information not retrieved | Retriever |
| Faithfulness | Hallucinations not grounded in context | Generator |
| Answer Relevance | Answers that miss the question | Generator |
These four metrics, implemented as LLM-as-judge evaluations, give you a complete picture of pipeline health. Let's build each one.
Setup
from google import genai
import json
client = genai.Client()
JUDGE_MODEL = "gemini-2.5-pro"
def judge(prompt: str) -> dict:
"""Call Gemini as a structured judge."""
response = client.models.generate_content(
model=JUDGE_MODEL,
contents=prompt,
config={"response_mime_type": "application/json"},
)
return json.loads(response.text)We use Gemini 2.5 Pro as the judge — not Flash — because evaluation requires careful reasoning about whether claims are supported by evidence. The extra quality is worth the cost here since evaluations run offline, not in the hot path.
Metric 1: Faithfulness
Faithfulness measures whether every claim in the generated answer is grounded in the retrieved context. This catches hallucinations — the most dangerous RAG failure mode.
Algorithm:
- Decompose the answer into atomic claims
- For each claim, check whether it's supported by the context
def evaluate_faithfulness(
answer: str,
context: list[str],
) -> dict:
context_block = "\n---\n".join(context)
# Step 1: Decompose into claims
decompose_result = judge(f"""Decompose the following answer into a list of atomic factual claims.
Each claim should be a single, verifiable statement.
Answer: {answer}
Respond as JSON: {{"claims": ["claim 1", "claim 2", ...]}}""")
claims = decompose_result["claims"]
if not claims:
return {"score": 1.0, "claims": [], "unsupported": []}
# Step 2: Verify each claim against context
verify_result = judge(f"""For each claim below, determine if it is supported by the context.
A claim is "supported" if the context contains evidence that directly implies or states the claim.
A claim is "unsupported" if the context does not contain sufficient evidence.
Context:
{context_block}
Claims:
{json.dumps(claims)}
Respond as JSON: {{"verdicts": [{{"claim": "...", "verdict": "supported"|"unsupported", "evidence": "quote or empty"}}]}}""")
verdicts = verify_result["verdicts"]
supported = sum(1 for v in verdicts if v["verdict"] == "supported")
unsupported = [v for v in verdicts if v["verdict"] == "unsupported"]
return {
"score": supported / len(verdicts) if verdicts else 1.0,
"total_claims": len(claims),
"unsupported": unsupported,
}A faithfulness score below 0.8 means more than 20% of the answer contains unsupported claims. That's a regression signal.
Metric 2: Answer Relevance
Answer relevance measures whether the response actually addresses the question. A system might retrieve perfect context and still generate an answer that drifts off-topic.
def evaluate_answer_relevance(
question: str,
answer: str,
) -> dict:
result = judge(f"""Evaluate whether the following answer is relevant to the question.
Consider:
- Does the answer address the core intent of the question?
- Is the answer complete, or does it miss key aspects?
- Does the answer contain unnecessary information that dilutes the response?
Question: {question}
Answer: {answer}
Respond as JSON:
{{
"score": <float 0-1, where 1 = perfectly relevant>,
"reasoning": "<brief explanation>",
"missing_aspects": ["<any aspects of the question not addressed>"]
}}""")
return resultMetric 3: Context Precision
Context precision measures whether the retrieved chunks that are actually relevant are ranked higher than irrelevant ones. If your top-5 retrieval returns 3 relevant chunks at positions 3, 4, 5 and 2 irrelevant chunks at positions 1, 2 — your precision is technically okay but your ranking is broken.
def evaluate_context_precision(
question: str,
context_chunks: list[str],
) -> dict:
result = judge(f"""For each context chunk below, determine if it is relevant to answering the question.
A chunk is "relevant" if it contains information needed to answer the question.
Question: {question}
Chunks (in retrieval rank order):
{json.dumps([{"rank": i+1, "text": c} for i, c in enumerate(context_chunks)])}
Respond as JSON: {{"judgments": [{{"rank": 1, "relevant": true/false}}, ...]}}""")
judgments = result["judgments"]
if not judgments:
return {"score": 0.0, "precision_at_k": {}}
# Average precision: reward relevant chunks appearing earlier
relevant_count = 0
precision_sum = 0.0
for j in judgments:
if j["relevant"]:
relevant_count += 1
precision_sum += relevant_count / j["rank"]
avg_precision = precision_sum / relevant_count if relevant_count > 0 else 0.0
return {
"score": avg_precision,
"relevant_chunks": relevant_count,
"total_chunks": len(judgments),
}Metric 4: Context Recall
Context recall measures whether the retriever found all the information needed to answer correctly. This requires a reference answer (ground truth).
def evaluate_context_recall(
reference_answer: str,
context_chunks: list[str],
) -> dict:
context_block = "\n---\n".join(context_chunks)
result = judge(f"""Decompose the reference answer into key statements, then check if each
statement can be attributed to the retrieved context.
Reference answer: {reference_answer}
Retrieved context:
{context_block}
Respond as JSON:
{{
"statements": [
{{"statement": "...", "attributable": true/false}}
]
}}""")
statements = result["statements"]
if not statements:
return {"score": 1.0, "statements": []}
attributable = sum(1 for s in statements if s["attributable"])
return {
"score": attributable / len(statements),
"attributable": attributable,
"total": len(statements),
"missing": [s for s in statements if not s["attributable"]],
}Building the evaluation harness
Now wrap these metrics into a harness that runs over a test dataset:
from dataclasses import dataclass
@dataclass
class EvalCase:
question: str
reference_answer: str # ground truth
retrieved_context: list[str]
generated_answer: str
def evaluate_pipeline(cases: list[EvalCase]) -> dict:
results = {
"faithfulness": [],
"answer_relevance": [],
"context_precision": [],
"context_recall": [],
}
for case in cases:
results["faithfulness"].append(
evaluate_faithfulness(case.generated_answer, case.retrieved_context)["score"]
)
results["answer_relevance"].append(
evaluate_answer_relevance(case.question, case.generated_answer)["score"]
)
results["context_precision"].append(
evaluate_context_precision(case.question, case.retrieved_context)["score"]
)
results["context_recall"].append(
evaluate_context_recall(case.reference_answer, case.retrieved_context)["score"]
)
return {
metric: {
"mean": sum(scores) / len(scores),
"min": min(scores),
"scores": scores,
}
for metric, scores in results.items()
}Creating the test dataset
The evaluation harness needs a test dataset of (question, reference_answer) pairs. You don't need thousands — 50-100 high-quality examples that cover your query distribution are enough to catch regressions.
Three approaches to building this dataset:
Manual curation (best quality, highest effort): Have domain experts write question-answer pairs from your actual documents. Cover edge cases, multi-hop questions, and "unanswerable" queries.
Synthetic generation (good enough, fast): Use Gemini to generate questions from your documents:
def generate_eval_pairs(document: str, n: int = 5) -> list[dict]:
result = judge(f"""Generate {n} question-answer pairs from this document.
Include a mix of:
- Simple factual questions (1 chunk needed)
- Complex questions requiring synthesis (2+ chunks)
- Questions that test nuance or caveats
Document:
{document}
Respond as JSON: {{"pairs": [{{"question": "...", "answer": "..."}}]}}""")
return result["pairs"]User feedback (production gold): Log cases where users report bad answers, thumbs-down responses, or ask follow-up questions (indicating the first answer was insufficient). These become your most valuable eval cases.
Running evaluations in CI
The real value of automated evaluation is catching regressions before deploy:
import sys
THRESHOLDS = {
"faithfulness": 0.85,
"answer_relevance": 0.80,
"context_precision": 0.70,
"context_recall": 0.75,
}
def ci_evaluation(cases: list[EvalCase]) -> bool:
results = evaluate_pipeline(cases)
passed = True
for metric, threshold in THRESHOLDS.items():
mean_score = results[metric]["mean"]
status = "PASS" if mean_score >= threshold else "FAIL"
print(f" {metric}: {mean_score:.3f} (threshold: {threshold}) [{status}]")
if mean_score < threshold:
passed = False
return passed
if __name__ == "__main__":
cases = load_eval_dataset("eval_cases.json")
if not ci_evaluation(cases):
sys.exit(1)Run this in your CI pipeline whenever you change the embedding model, chunking strategy, prompt template, or retrieval parameters. A failing metric tells you exactly which component regressed.
Cost and latency
LLM-as-judge evaluation isn't free. Each eval case requires 4 Gemini 2.5 Pro calls (one per metric). For a 100-case dataset, that's 400 API calls.
Cost at current pricing: ~$0.003 per eval call × 400 = ~$1.20 per full evaluation run. Cheap enough to run in CI on every PR that touches the RAG pipeline.
Latency: ~2-3 seconds per eval call, ~5 minutes for 100 cases sequentially. Parallelize with asyncio.gather to bring it under 30 seconds.
When to use Pro vs Flash as judge: Pro for faithfulness and context recall (requires careful reasoning about claim support). Flash is acceptable for answer relevance and context precision (simpler judgments). This hybrid approach cuts costs by 40% with minimal quality loss.
Correlation with human judgment
In our experiments, Gemini 2.5 Pro as a judge achieves 0.85+ Spearman correlation with human evaluators on faithfulness judgments and 0.80+ on relevance. The main failure mode: the judge is slightly more lenient than humans on partial answers (scores 0.7 where humans would score 0.5). Calibrate your thresholds accordingly.
Conclusion
RAG evaluation isn't optional — it's the only way to know your system works and keeps working. The four RAGAS metrics (faithfulness, relevance, precision, recall) cover both retrieval and generation failures. Gemini 2.5 Pro as a judge makes this automated and reproducible at ~$1 per evaluation run.
Start with 50 manually-curated eval cases. Add synthetic ones for coverage. Run evaluations in CI. Set thresholds that match your quality bar. When a metric drops, you'll know exactly which component broke.
Further reading: