Forge
Skip to main content

RAG evaluation tutorial: Metrics, LLM-as-a-Judge, and W&B Weave

Stop guessing if your RAG pipeline works. Learn how to measure retrieval precision, generation faithfulness, and end-to-end performance using LLM-as-a-judge and Weights & Biases.
Last updated: March 26, 2026
You built a RAG system. Documents go in, answers come out. The demo went great. Then your support team actually starts using it, and weird things happen. The system invents a policy that doesn't exist. It misses an obvious answer sitting right there in the knowledge base. It pulls back five documents when one would do.
This is the RAG evaluation problem. And no, "it seems to work" isn't good enough when real users depend on it.
In this article, we'll walk through why evaluation matters for RAG, what metrics actually tell you something useful, and how to wire it all up with Weights & Biases. The same ideas apply whether you're building enterprise search, a support bot, or some internal tool that answers questions from your docs.

Table of contents



Why RAG evaluation matters

RAG systems are supposed to give you grounded answers. The LLM looks things up before responding, rather than just guessing from training data. Sounds great in theory.
Reality is messier. Your retriever might grab passages that match keywords but miss the point entirely. It might skip the one chunk that actually has the answer. The generator might get perfect context and still make stuff up. Or it faithfully quotes text that is wrong or outdated.
RAG evaluation catches these problems before users complain. Not to get some magic accuracy number, you want to know where your pipeline breaks so you can actually fix it.
A few examples of what goes wrong:
  • Your legal team asks about contract termination. The retriever hands back HR policies. Without checking retrieval quality, you'd assume the answer was grounded when it wasn't.
  • A support bot gets asked about returns. It finds the right FAQ but tells the user 60 days, even though your policy says 30. Generation metrics catch that mismatch.
  • Engineers search your docs. The system grabs five chunks, but only one matters. The rest just adds cost and noise. Precision metrics show you're wasting tokens.
There's another reason evaluation matters: it lets you iterate faster. When retrieval and generation are measured separately, you know whether to fix your embeddings or rewrite your prompt. Lumping everything together leaves you guessing.

What's actually in a RAG system?

It's worth being specific here. A RAG pipeline has two main parts: something that fetches text (the retriever), and something that writes answers using that text (usually an LLM).
User asks a question. Retriever searches a vector database or whatever index you're using. Top results get stuffed into a prompt. LLM reads the prompt and writes an answer.
Some vocabulary:
  • Retriever: The search component. Embeds your query, runs similarity search, and returns top-K results.
  • Vector database: Where your chunked documents live as embeddings. Pinecone, Weaviate, Chroma, FAISS, take your pick.
  • Embeddings: Dense vectors that represent text meaning. What makes semantic search work?
  • Reranker: Optional second pass that re-scores retrieved chunks. Slower but often more accurate.
  • Generator: The LLM is writing the final answer based on the query and context.
  • Prompt template: How you structure everything for the LLM. Tiny changes here have outsized effects.
Problems sneak in everywhere. Retriever misses good documents - that's a recall failure. Retriever returns junk - precision failure. Generator ignores context and hallucinates. Orchestration silently truncates your context because it's too long.
You need to measure three things: retriever alone, generator alone, and the whole pipeline together. Testing only the final output hides where failures actually happen.

RAG fundamentals: what exactly are we evaluating?

Depends on your use case, but most RAG systems care about some mix of:
  • Correctness: Is the information right? Wrong answers are worse than "I don't know."
  • Groundedness: Did the answer come from the retrieved context, or did the model improvise? Factually correct hallucinations are still hallucinations.
  • Coverage: Did you answer the whole question? Partial answers frustrate people even when they're accurate.
  • Latency: How long does the whole thing take? Nobody waits 30 seconds.
  • Cost: How many tokens per query? Retrieving 20 chunks when 3 would work adds up.
  • Safety: Does the system avoid harmful stuff, respect privacy, and follow your policies?
Two flavors of evaluation exist. Offline: you run fixed test cases before deploying, catch regressions, and tune parameters. Online: you watch what happens with real traffic—user feedback, error rates, A/B tests. Both matter for different reasons.
All this connects to business outcomes. Better accuracy means fewer support tickets. Lower latency keeps people engaged. Lower cost protects margins. A good evaluation shows whether your changes actually help.

What goes into an evaluation pipeline?

Five pieces:
  1. Knowledge base. Your documents are chunked and indexed the same way production uses them.
  2. Evaluation dataset. Questions with known-good answers and the source passages that support them. Built from real queries, expert curation, or synthetic generation.
  3. The RAG system. Same retriever, generator, and orchestration code that users hit.
  4. Metrics. The specific things you measure: precision, recall, faithfulness, relevance.
  5. Evaluation engine. Whatever runs the tests, computes scores, and tracks results. Human review, automated checks, LLM-as-a-judge—usually some combination.
The Hugging Face RAG evaluation cookbook shows a clean version of this: load knowledge base, build Q&A dataset, connect your RAG system, run benchmarks. Weights & Biases ties it together so you can track runs, compare configs, and keep an audit trail.

Building your test dataset

Your evaluation is only as good as your test data. You need realistic questions paired with answers that actually come from your knowledge base. Options for building one:
  • Real user queries. Best signal. Sample from production logs, have experts write reference answers, and tag which documents support each one. Takes time, but it's worth it.
  • Expert-curated Q&A. Domain experts write questions from your docs. Good coverage, might not match how users actually phrase things.
  • Synthetic generation. LLM generates Q&A from your documents. Scales fast, needs filtering.
  • Adapted public datasets. Map existing benchmarks onto your corpus where topics overlap. Limited use for specialized domains.
Synthetic data is often the quickest path to something working. The catch: LLM-generated questions have quirks. Phrasing that's too clean, questions that are trivially easy, assumptions that leak the answer. Filter aggressively and expect noise.

Chunking your knowledge base

Before evaluation works, your documents need to be split into retrievable pieces. How you chunk directly affects both retrieval quality and your metrics.
Trade-offs to think about:
  • Chunk size. Small chunks (100-200 tokens) give precise retrieval but might split relevant info across pieces. Large chunks (500-1000 tokens) keep more context but add noise.
  • Overlap. Some overlap between chunks (50 tokens, say) avoids cutting sentences at awkward boundaries.
  • Deduplication. Near-duplicate content clutters retrieval results.
  • Metadata. Source info, timestamps, document structure—useful for filtering and attribution.
Chunking choices affects your numbers. Too aggressive and recall suffers because answers span multiple chunks. Too loose and precision drops because chunks contain mostly irrelevant text. Log your chunking config alongside results so you can trace cause and effect.

Generating synthetic Q&A

Many teams bootstrap evaluation by having an LLM generate questions and answers from their documents. For each chunk, prompt the model to create questions that can only be answered using that specific text.
Prompt design matters. Questions should be specific enough to test retrieval (vague questions could match many documents) but phrased like real user queries. They should stand alone—readers shouldn't need the source chunk to understand what's being asked.
A generation prompt might say:
Read this passage. Write a factual question that requires this specific text to answer. Make it standalone, someone who hasn't seen the passage should still understand the question.
You need volume. A dozen synthetic examples won't tell you much. Hundreds or thousands give you statistical confidence. Try different LLMs and prompts, log everything to Weights & Biases, and compare what you get.
Filtering bad synthetic questions
Raw LLM output includes garbage. Questions that are too easy, too hard, ambiguous, or answerable without the source text.
A filtering step helps. Have another LLM (or same one, different prompt) score questions:
  • Groundedness - does the passage actually answer this?
  • Relevance - main content or tangential detail?
  • Standalone clarity - understandable without seeing the source?
  • Non-triviality - requires reading the passage, or anyone could guess?
Set thresholds, toss what fails. Log the scores so you can investigate later if results look off. A test set full of easy questions gives inflated metrics that mean nothing.

Measuring retrieval quality

To evaluate the retriever by itself, compare what it returns against the ground-truth context for each question. Does your system find the right stuff before the LLM ever sees it?
Retrieval works like this: embed the query, search your index, maybe rerank, return top-K chunks. Errors happen at every step.
Frameworks like deepeval give you retrieval-specific metrics.
  • ContextualPrecisionMetric: what fraction of retrieved passages were actually relevant?
  • ContextualRecallMetric: What fraction of relevant passages did you retrieve?
  • ContextualRelevancyMetric: how well does the retrieved set as a whole support answering the question?
The point is running these tests without touching the generation. Give the retriever a question, get passages back, and compare to the ground truth. Generator stays out of it. When retrieval metrics tank but generation looks fine, you know where to dig.

Retrieval metrics in detail

  • Contextual precision. Out of everything you retrieved, how much was actually useful? Low precision means you're padding prompts with noise, wasting tokens, and maybe confusing the generator.
  • Contextual recall. Out of everything you needed, how much did you get? Low recall means missing critical information.
  • Contextual relevancy. Taking the whole retrieved set, how well does it support answering this question? More holistic than precision or recall alone.
  • You might also track hit@K (does the right passage appear anywhere in top K?), MRR (mean reciprocal rank—how high does the correct passage rank?), and breakdowns by query type or topic.
  • LLMs help compute these when ground-truth annotations are incomplete. Have a judge model label which passages are necessary or sufficient.
Track per-query, slice by difficulty, and category. A retriever that nails simple factual questions might fail on multi-hop reasoning. Aggregates hide that.

Measuring generation quality

To evaluate the generator alone, give it a known-good context and score what it produces. This decouples generation problems from retrieval problems.
Take a question and its ground-truth context, the passages that actually contain the answer. Pass both to your generator. Evaluate the output.
Bad answers despite perfect context?
That's a generation problem, not a retrieval problem. Two metrics matter most:
  • Answer relevancy. Does the answer address what was asked? Correct and well-written doesn't help if it's answering the wrong question.
  • Faithfulness. Is the answer grounded in the provided context? This is the hallucination check. Did the model stick to retrieved text or invent things?
  • Correctness and faithfulness aren't the same. An answer can be factually true but unfaithful—the model knew it from training, not from your documents. For RAG, you usually want both: correct and derived from your sources.
  • Prompt template matters a lot here. Small wording changes swing faithfulness scores dramatically. Log everything so you can trace what changed.

Generation metrics: the full picture

  • Factual correctness. Does it match the ground truth? Primary metric when clear right answers exist.
  • Groundedness. Is every claim supported by context? Unsupported statements are hallucinations even if true.
  • Completeness. Did you answer the whole question? Partial answers often frustrate more than "I don't know."
  • Clarity. Easy to understand? Correct, but convoluted isn't great.
  • Style. Matches expected tone and format? Enterprise apps often have voice requirements.
You can score these with LLM-as-a-judge, human reviewers, or both. Amazon Bedrock offers this pattern with configurable rubrics.
Production systems might add responsible AI checks: toxicity, bias, and privacy leaks. Harder to measure systematically, but matters for real deployments.

End-to-end RAG evaluation

End-to-end scores your system on real queries using whatever context it actually retrieves and whatever answer it actually generates. Catches interactions that component testing misses.
Here's the thing: weak retrieval makes strong generation look bad. If you fetch garbage, even the best LLM produces garbage answers. The reverse happens too—perfect retrieval can hide a mediocre generator because the context does most of the work.
E2E metrics tell you whether users get correct answers, regardless of where problems originate. Overall accuracy against ground truth, user satisfaction signals (thumbs up/down, follow-up rate), and task completion for goal-oriented systems.
Latency and cost matter at this level too. Perfect answers in 30 seconds don't work for interactive use. Retrieving 50 chunks per query burns through your budget.
Deepeval emphasizes this E2E view, combining retrieval and generation judgments into composite scores. One number for "does it work," component metrics for "why doesn't it."

LLM-as-a-judge

You can't have humans review thousands of answers. LLM-as-a-judge scales: a strong model scores outputs against rubrics you define.
Setup is straightforward. Give the judge the question, retrieved context, candidate's answer, and, optionally, a reference. Ask it to score correctness, groundedness, and completeness. Get back a number, maybe with an explanation.
Why this works:
  • Scale. Thousands of examples in minutes, not days.
  • Consistency. Same rubric applied uniformly. Human annotators drift; LLM judges don't, given fixed prompts.
  • Cost. Cheaper than human annotation at volume.
  • Limitations exist. LLM judges have biases, longer answers, certain phrasings, and outputs from similar models. They need calibration against human judgments. Fluent nonsense can fool them when careful humans wouldn't be fooled.
Practical approach: LLM judges for broad coverage, spot-check with humans. Amazon Bedrock and open-source frameworks implement this with configurable rubrics.

Writing good judge prompts

Vague instructions produce inconsistent scores. A solid evaluation prompt needs:
  • Clear framing. Tell the judge exactly what it's evaluating and what role it's playing.
  • Explicit criteria. Define score levels. "5 = fully correct and grounded; 1 = incorrect or hallucinated."
  • All inputs. Question, context, answer, reference—everything the judge needs.
  • Output format. Single number, structured JSON, score with explanation—specify exactly.
  • Calibration matters. Before trusting your judge at scale, run it on examples where you know the right score. Check agreement rates. If the judge systematically disagrees with humans, adjust prompts or thresholds.
Track judge versions and prompts. Same evaluation run last month might give different results if you changed the rubric. Weights & Biases helps maintain this lineage.

Tutorial: RAG evaluation with W&B Weave

Time to build something. We'll create a RAG evaluation pipeline measuring both retrieval and generation quality, using W&B Weave for tracing and scoring.

What we're building

  1. Simple RAG system with retriever and generator
  2. Evaluation dataset: questions, ground-truth contexts, reference answers
  3. Retrieval metrics: context precision, context recall
  4. Generation metrics: faithfulness and relevancy via LLM-as-a-judge
  5. Weave Evaluation to run everything and log results

Step 0: Install and set up

First things first, get the packages installed and authenticate with Weights & Biases. Weave handles the evaluation orchestration, OpenAI gives us embeddings and the LLM, and numpy does the similarity math.
pip install weave openai numpy python-dotenv
import wandb
wandb.login()
Create a .env file to keep your API key out of the code:
OPENAI_API_KEY=your-key-here

Step 1: Initialize Weave

Now we set up the project. The weave.init() call creates a project in your Weights & Biases account where all traces, evaluations, and assets will live. Pick a name that makes sense; you'll be looking at this in dashboards later.
import os
import json
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI
import weave
from weave import Dataset, Evaluation, Model

load_dotenv()
client = OpenAI()

weave.init("rag-evaluation-demo")

Step 2: Knowledge base and evaluation dataset

Here's where you'd normally load your actual documents. For this tutorial, we're using a fake company's policies, return policy, HR handbook, support guide, that kind of thing. Five chunks, each with an ID, content, and source file. Small enough to see what's happening, big enough to show the patterns.
KNOWLEDGE_BASE = {
"chunk_1": {
"id": "chunk_1",
"content": "Acme Corp offers a 30-day return policy for all products purchased online. "
"Items must be in original packaging and unused condition. Refunds are processed "
"within 5-7 business days after we receive the returned item.",
"source": "return_policy.md"
},
"chunk_2": {
"id": "chunk_2",
"content": "Employee vacation policy: Full-time employees receive 15 days of paid vacation "
"per year, accruing at 1.25 days per month. Unused vacation days can be carried "
"over up to a maximum of 5 days into the next calendar year.",
"source": "hr_handbook.md"
},
"chunk_3": {
"id": "chunk_3",
"content": "Technical support is available Monday through Friday, 9 AM to 6 PM Eastern Time. "
"For urgent issues outside business hours, premium support customers can call our "
"24/7 emergency hotline at 1-800-555-0199.",
"source": "support_guide.md"
},
"chunk_4": {
"id": "chunk_4",
"content": "Shipping rates: Standard shipping (5-7 business days) is free for orders over $50. "
"Express shipping (2-3 business days) costs $12.99. Overnight shipping is available "
"for $24.99. International shipping rates vary by destination.",
"source": "shipping_info.md"
},
"chunk_5": {
"id": "chunk_5",
"content": "Password requirements: All passwords must be at least 12 characters long and include "
"at least one uppercase letter, one lowercase letter, one number, and one special "
"character. Passwords expire every 90 days and cannot be reused within 12 months.",
"source": "security_policy.md"
}
}

rows = [
{
"id": "q1",
"question": "What is the return policy for online purchases?",
"ground_truth_context": ["chunk_1"],
"reference": "Acme Corp offers a 30-day return policy for online purchases. Items must be in original packaging and unused. Refunds are processed within 5-7 business days."
},
{
"id": "q2",
"question": "How many vacation days do full-time employees get?",
"ground_truth_context": ["chunk_2"],
"reference": "Full-time employees receive 15 days of paid vacation per year, accruing at 1.25 days per month."
},
{
"id": "q3",
"question": "What are the technical support hours?",
"ground_truth_context": ["chunk_3"],
"reference": "Technical support is available Monday through Friday, 9 AM to 6 PM Eastern Time."
},
{
"id": "q4",
"question": "How much does express shipping cost?",
"ground_truth_context": ["chunk_4"],
"reference": "Express shipping costs $12.99 and takes 2-3 business days."
},
{
"id": "q5",
"question": "What are the password requirements?",
"ground_truth_context": ["chunk_5"],
"reference": "Passwords must be at least 12 characters with uppercase, lowercase, number, and special character. They expire every 90 days."
},
{
"id": "q6",
"question": "Can I get free shipping?",
"ground_truth_context": ["chunk_4"],
"reference": "Yes, standard shipping is free for orders over $50."
},
{
"id": "q7",
"question": "How long do refunds take to process?",
"ground_truth_context": ["chunk_1"],
"reference": "Refunds are processed within 5-7 business days after the returned item is received."
},
{
"id": "q8",
"question": "Can I carry over unused vacation days?",
"ground_truth_context": ["chunk_2"],
"reference": "Yes, up to 5 unused vacation days can be carried over into the next calendar year."
}
]

dataset = Dataset(name="rag_eval_dataset_v1", rows=rows)
weave.publish(dataset)
The evaluation dataset pairs questions with ground-truth contexts and reference answers. Each row says "for this question, the answer should come from these specific chunks, and here's what a good answer looks like." This is what lets us measure both retrieval (did we get the right chunks?) and generation (did the answer match the reference?).
Publishing the dataset to Weave versions it automatically. Run this evaluation six months from now and you'll know exactly which test cases you used.

Step 3: Build a simple RAG system

Two pieces here: a retriever that finds relevant chunks, and a generator that writes answers from them. The retriever embeds the question, computes cosine similarity against all chunks, and returns the top-K. Nothing fancy—production systems would use a proper vector database, maybe a reranker. But this shows the pattern.
@weave.op()
def get_embedding(text: str) -> list:
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return response.data[0].embedding


@weave.op()
def retrieve(question: str, top_k: int = 2) -> list:
question_embedding = get_embedding(question)
similarities = []
for chunk_id, chunk in KNOWLEDGE_BASE.items():
chunk_embedding = get_embedding(chunk["content"])
similarity = np.dot(question_embedding, chunk_embedding) / (
np.linalg.norm(question_embedding) * np.linalg.norm(chunk_embedding)
)
similarities.append((chunk_id, similarity, chunk["content"]))
similarities.sort(key=lambda x: x[1], reverse=True)
return [
{"chunk_id": s[0], "content": s[2], "score": float(s[1])}
for s in similarities[:top_k]
]


class RAGSystem(Model):
model_name: str = "gpt-5-mini"
top_k: int = 2
@weave.op()
def predict(self, question: str) -> dict:
retrieved_chunks = retrieve(question, self.top_k)
context = "\n\n".join([
f"[Source: {chunk['chunk_id']}]\n{chunk['content']}"
for chunk in retrieved_chunks
])
messages = [
{
"role": "system",
"content": "You are a helpful assistant. Answer questions based only on the "
"provided context. If the context doesn't contain the answer, say so."
},
{
"role": "user",
"content": f"Context:\n{context}\n\nQuestion: {question}"
}
]
response = client.chat.completions.create(
model=self.model_name,
messages=messages
)
return {
"answer": response.choices[0].message.content.strip(),
"retrieved_chunks": [c["chunk_id"] for c in retrieved_chunks],
"context": context
}
The @weave.op() decorator is doing important work here. Every call to retrieve() and predict() gets logged automatically—inputs, outputs, timing, the lot. When something goes wrong, you can trace exactly what happened.
The RAGSystem class wraps everything into a Weave Model. The predict() method is what the evaluation will call for each test question. It retrieves chunks, builds a context string, and asks the LLM to answer based only on that context.

Step 4: Retrieval metrics

Now we measure how well the retriever does its job. Precision asks: of everything we retrieved, how much was actually useful? Recall asks: of everything we needed, how much did we actually get? Both matter. High precision with low recall means you're missing important context. High recall with low precision means you're padding prompts with noise.
@weave.op()
def context_precision(ground_truth_context: list, model_output: dict) -> dict:
retrieved = set(model_output.get("retrieved_chunks", []))
relevant = set(ground_truth_context)
if not retrieved:
return {"context_precision": 0.0}
relevant_retrieved = retrieved.intersection(relevant)
precision = len(relevant_retrieved) / len(retrieved)
return {"context_precision": precision}


@weave.op()
def context_recall(ground_truth_context: list, model_output: dict) -> dict:
retrieved = set(model_output.get("retrieved_chunks", []))
relevant = set(ground_truth_context)
if not relevant:
return {"context_recall": 1.0}
relevant_retrieved = retrieved.intersection(relevant)
recall = len(relevant_retrieved) / len(relevant)
return {"context_recall": recall}
These scorers compare what the model retrieved against what it should have retrieved. Simple set intersection math. The ground truth comes from our evaluation dataset; we told it which chunks contain the answer for each question.

Step 5: Generation metrics with LLM-as-a-judge

Retrieval metrics are straightforward set comparisons. Generation metrics are trickier; you need to judge whether an answer is actually good. That's where LLM-as-a-judge comes in. We ask gpt-5-mini to score answers on two dimensions: faithfulness (did it stick to the context or make stuff up?) and relevancy (did it actually answer the question?).
The prompts are specific about what each score level means. Vague rubrics produce inconsistent scores. We normalize everything to 0-1 so metrics are comparable.
FAITHFULNESS_PROMPT = """You are evaluating whether an answer is faithful to the provided context.

Context:
{context}

Question: {question}

Answer: {answer}

Rate faithfulness from 1-5:
1 = Contains significant information not in context (hallucination)
2 = Contains some unsupported claims
3 = Mostly supported but has minor unsupported details
4 = Well-supported with only trivial additions
5 = Completely faithful to the context

Return only a number."""


RELEVANCY_PROMPT = """You are evaluating whether an answer is relevant to the question.

Question: {question}

Answer: {answer}

Reference: {reference}

Rate relevancy from 1-5:
1 = Does not address the question
2 = Partially addresses but misses key points
3 = Addresses question but incomplete or has irrelevant parts
4 = Addresses well with minor issues
5 = Perfectly addresses the question

Return only a number."""


@weave.op()
def faithfulness_score(question: str, model_output: dict) -> dict:
answer = model_output.get("answer", "")
context = model_output.get("context", "")
prompt = FAITHFULNESS_PROMPT.format(
context=context,
question=question,
answer=answer
)
response = client.chat.completions.create(
model="gpt-5-mini",
messages=[{"role": "user", "content": prompt}]
)
try:
score = int(response.choices[0].message.content.strip())
normalized = (score - 1) / 4
except ValueError:
normalized = None
return {"faithfulness": normalized}


@weave.op()
def relevancy_score(question: str, reference: str, model_output: dict) -> dict:
answer = model_output.get("answer", "")
prompt = RELEVANCY_PROMPT.format(
question=question,
answer=answer,
reference=reference
)
response = client.chat.completions.create(
model="gpt-5-mini",
messages=[{"role": "user", "content": prompt}]
)
try:
score = int(response.choices[0].message.content.strip())
normalized = (score - 1) / 4
except ValueError:
normalized = None
return {"relevancy": normalized}
Notice that faithfulness only needs the question and model output (which includes the context). Relevancy also takes the reference answer so the judge can compare. Both return dictionaries that Weave aggregates into mean scores across the dataset.

Step 6: Run the evaluation

Time to wire everything together. The Evaluation object takes our dataset and list of scorers. When you call evaluate(), it runs the RAG system on every question, passes outputs through each scorer, and logs everything to Weave.
evaluation = Evaluation(
dataset=dataset,
scorers=[
context_precision,
context_recall,
faithfulness_score,
relevancy_score
]
)

async def run_eval():
rag_system = RAGSystem(top_k=2)
results = await evaluation.evaluate(
rag_system,
__weave={"display_name": "rag-eval-top2"}
)
print("Done!")
return results

import asyncio
asyncio.run(run_eval())
The display_name parameter gives this run a human-readable label in the UI. You'll thank yourself later when you're comparing twenty different experiments.

Step 7: Compare configurations

Here's where evaluation pays off. Same dataset, same metrics, different settings. Does retrieving more chunks help or hurt? Run all three, look at the numbers, and decide based on evidence instead of gut feeling.
async def compare_configs():
for k in [1, 2, 3]:
rag_system = RAGSystem(top_k=k)
await evaluation.evaluate(
rag_system,
__weave={"display_name": f"rag-eval-top{k}"}
)
print(f"Finished top_k={k}")

asyncio.run(compare_configs())
After this run, you'll have three evaluation runs in Weave. Compare them side by side. Maybe top_k=1 has perfect precision but terrible recall. Maybe top_k=3 retrieves everything you need but adds so much noise that faithfulness drops. The numbers tell the story.

Reading results in Weave

Open the URL Weave prints after running.

Traces View

Every operation logged. Click any trace to view the question, the chunks that came back with their scores, the generated answer, and all metrics for that example.
Screenshot by the Author. Traces view of Weights and Biases.

Evals View

Summary per evaluation run. Aggregate metrics: context_precision.mean, context_recall.mean, faithfulness.mean, relevancy.mean. Compare runs to see how top_k affects each metric.
Screenshot of Evals View. Evals view of Weights and Biases.

Assets View

Registered datasets, models, and evaluation configs. Reuse across experiments.
Screenshot by the Author. Assets view of Weights and Biases.
The separation matters: if retrieval metrics are low but generation looks fine, focus on your embeddings or chunking. If retrieval is solid but faithfulness tanks, work on your prompt.

Hyperparameters and failure modes

RAG pipelines break in quiet ways when you change settings without measuring.

Retrieval Parameters:

  • Embedding model. Different models encode similarity differently. General-purpose embeddings may miss domain-specific vocabulary.
  • Top-K. Too few chunks risk missing the answer. Too many adds noise and cost.
  • Reranker. Helps precision, costs latency.

Generation Parameters:

  • Prompt template. Huge effect on faithfulness. Small wording changes matter.
  • Max tokens. Caps output length, can truncate answers.

Common Failures:

  • Irrelevant context. Keywords match, but the content doesn't help.
  • Missing key evidence. Right passage ranks just below your cutoff.
  • Hallucinations. Generator ignores context, makes stuff up.
  • Verbosity. Model pads answers with caveats and hedging.
Systematic evaluation surfaces all of these. Patterns show up across queries that you'd miss spot-checking.

Optimizing with Weights & Biases

The workflow:
  • Define configs to test: embedding models, top-K values, rerankers, prompt variants.
  • Run evaluation for each config, log to Weights & Biases.
  • Visualize trade-offs. Does higher top-K help recall but hurt precision?
  • Pick the config that balances your goals.
W&B Weave lets you trace individual queries through the pipeline, see exactly what happened, link traces to aggregate metrics. When numbers look off, drill into specific examples.
Wire evaluation into CI/CD. Run tests on every PR touching RAG code. Block merges if metrics regress.

Other use cases

The same principles work beyond basic Q&A:
  • Multi-hop questions. Require info from multiple passages. Recall becomes even more important.
  • Tool-using agents. Decide when to search, what to search for, how to combine results. Evaluation extends to tool selection.
  • Domain-specific assistants. Legal, medical, technical—where accuracy is critical. May need expert reviewers alongside automated metrics.
  • Conversational RAG. Multi-turn with accumulating context. Evaluate across dialogue, not just single turns.
  • Summarization. Synthesize retrieved docs instead of answering specific questions. Faithfulness and coverage still apply.
Core pattern holds: separate retrieval from generation metrics, use LLM judges for scale, calibrate against humans, track everything.

Practical tips

Lessons from teams who've done this:
  • Don't rely only on synthetic questions. Good starting point, but they don't capture how users actually ask things. Mix in real queries.
  • Don't ignore retrieval metrics. Tempting to focus on final answer quality, but that hides the source of problems.
  • Calibrate your judges. Verify they agree with humans on a sample. Uncalibrated judges mislead.
  • Cover diverse query types. Test sets heavy on simple factual questions miss problems with complex reasoning.
  • Document your choices. Chunking strategy, prompt template, judge rubric—future you needs this context.
  • Start simple. Basic test suite that catches obvious regressions beats nothing. Iterate from there.
Hugging Face's RAG evaluation cookbook, Amazon Bedrock's evaluation features, and deepeval's metrics, among others, offer solid implementations. Build on what exists.

Conclusion

RAG evaluation turns retrieval-augmented generation from "seems to work" into something you can actually trust. The whole point is to verify that you retrieve relevant context and generate accurate, grounded answers, and to know which part fails when things go wrong. You need a knowledge base, an evaluation dataset with ground-truth contexts and reference answers, the RAG system you're testing, metrics for both retrieval and generation, and some way to run it all. Measure retrieval and generation separately, so you know where problems live. Precision and recall indicate retrieval quality; correctness and faithfulness indicate generation quality. LLM judges let you scale evaluation beyond what humans can review, but calibrate them against human judgments first, or they'll mislead you.
Start with a small test set, a few key metrics, and basic scoring.
Use Weights & Biases for tracking, LLM judges for scale. Run evaluations on every change.
As your system grows, your evaluation should too: more test cases, more edge cases, dashboards that catch regressions before users notice. RAG systems that work reliably aren't accidents. They're built by people who measure what matters and fix what they find.