A RAG system with an LLM searches for information in a collection of documents and uses the retrieved passages to draft a response. To evaluate it, check three things separately: whether it finds the necessary evidence, whether the response uses it correctly, and how long the complete process takes. A fluent response alone proves none of these.
This guide explains how the RAG–LLM combination works and proposes a set of questions in Spanish, metrics with explicit denominators, and a dependency-free Python script. The example documents and timings are fictional educational data: they make it possible to verify the calculations, but do not represent measurements of a model, GPU, or provider.
What RAG Is and What It Adds to an LLM
RAG stands for retrieval-augmented generation. The LLM is the model that generates text; RAG is an architecture that provides it with external information during a query. They are not two competing models: you can add retrieval to an application that already uses an LLM.
The AWS explanation of RAG describes adding external knowledge to the generation context. The original paper by Lewis and colleagues studied a combination of parametric memory and retrieval over a document index. In an application, the practical goal is to answer with identifiable evidence and update the collection without retraining the generator with every change.
Think of an assistant for consulting a technical manual. The model may know what a backup is, but the frequency of backups for your product must come from the current manual. Adding RAG makes it easier to provide that information; the application still has to verify that it retrieves the correct version and does not invent a different frequency.
Indexing, Retrieval, and Generation
The basic flow has three stages:
- Indexing. You extract the content, split it into passages, and store identifiers, version, date, and permissions. You can build vector representations, a lexical index, or both.
- Retrieval. You search for candidates for the question and select those that will enter the context. Record both the candidates and the result after filtering and possible reranking.
- Generation. You send the LLM the question and selected passages, with instructions about citations and what to do when information is missing.
To explore the first part in more depth, see our guide to embeddings and semantic search. A vector representation does not replace preserving the source: the evaluator needs to know what text was retrieved and which version it came from.
RAG, Fine-Tuning, and Long Context
| Approach | What changes | What you need to check |
|---|---|---|
| RAG | The evidence retrieved for each query | Retrieval, permissions, currency, and use of sources |
| Fine-tuning | The model parameters through training | Learned behavior and generalization on separate examples |
| Long context | The amount of text you can provide in a request | Content selection, limits, cost, and latency |
The table is a decision framework, not a performance classification. Giving the model more text also does not prove that it used the correct passage. A RAG system can use a fine-tuned model and have a long context window.
How to Evaluate RAG and LLMs Without Mixing Up Failures
Separate retrieval from the final response. The Microsoft documentation on RAG evaluators distinguishes evaluation of the retrieval process from evaluation of the system. This separation makes it possible to locate the problem before changing models.
| Observed signal | What to review first |
|---|---|
| The required document is not in the context | Extraction, chunking, index, filters, and retrieval |
| The evidence is present, but the response contradicts it | Instructions, generator, and conflict handling |
| There are citations, but they do not support the claim | Relationship between claim and passage, version, and attribution |
| The response is correct but too slow | Per-stage traces, queues, context length, and generation |
| It responds when the collection does not contain the answer | Detection of missing evidence and abstention policy |
For each query, retain: question, retrieved identifiers and texts, order, response, citations, model, configuration, index version, and timings. When comparing two configurations, use the same questions and references; change one variable at a time so that you can interpret the difference.
A Set of Questions in Spanish with Verifiable Evidence
To get started, use this fictional collection for an imaginary service. Its terms do not describe Flatkey services or real policies.
| ID | Excerpt from the fictional manual |
|---|---|
| d1 | Backups are performed every 24 hours. They are retained for 7 days. |
| d2 | To export data, open Settings and select Export. |
| d3 | Example support is available Monday through Friday. |
| d4 | Exports are downloaded in CSV format. |
| d5 | The storage region specified in this manual is Madrid. |
The reference questions and answers are:
| Question | Required evidence | Reference answer |
|---|---|---|
| How often are backups performed and how long are they retained? | d1 | Every 24 hours; retained for 7 days |
| How do I export data and in what format? | d2 and d4 | Settings → Export; CSV format |
| In which region is data stored? | d5 | Madrid |
| What compensation is offered for an outage? | None | The manual does not specify this |
The final question tests abstention. It should not be included in the average retrieval score for relevant documents because its reference set is empty. Evaluate it separately: does the system recognize that evidence is missing?
For a real dataset, add questions with acronyms, accents, paraphrases, references to older versions, and answers spread across documents. Include unanswerable queries and documents with access restrictions. Set aside a test set that you do not use to tune instructions or select examples.
Retrieval, citation, and response metrics
Document Recall@k: number of relevant IDs retrieved among the top k, divided by all relevant reference IDs. If you need d2 and d4 and only d4 appears, the result is 1/2. The Ragas documentation on context recall explains why a reference is needed and distinguishes variants based on IDs and content. Here we use unique document IDs, not a judge's semantic score.
MRR@k: for each answerable question, take the inverse of the position of the first relevant document, or zero if it does not appear. Then calculate the average. Finding d5 in second position contributes 1/2. MRR does not indicate whether you retrieved all the necessary pieces.
Citation validity: valid claim–citation pairs divided by all emitted pairs. In this example, a citation is valid if it belongs to the provided context and supports the claim. An existing URL can be an incorrect citation.
Citation coverage: factual claims that have at least one valid citation, divided by all factual claims in the responses. A response can provide one correct citation and leave other claims unsupported.
Context support: claims supported by the context divided by all factual claims. This idea is related to the Ragas faithfulness metric. It does not prove that the source is true or up to date: that requires additional controls. Nor does it by itself measure whether the answer is complete.
You can use an LLM as a judge to propose annotations, but provide the question, the answer, the excerpts, and an explicit rubric. Ask it to cite the text that supports each decision and allow “not determinable.” Compare a sample against human review. Do not turn the evaluation of the same generator into an automatic ground truth.
Runnable example: calculate the metrics with Python
Save the following block as evaluar_rag.py and run python3 evaluar_rag.py with Python 3.10 or later. It does not install packages, call an API, or require a GPU. It scores previously annotated synthetic results; it does not implement a search engine or automatically judge the meaning of a citation.
Each citas pair contains the cited ID and a human label indicating whether it supports the claim. apoyadas and con_cita_valida are also reference annotations. When replacing the data with real responses, you must obtain those labels through review or a calibrated judge.
from math import ceil
from statistics import mean, median
# Datos sintéticos: no son mediciones de un LLM ni de hardware.
casos = [
dict(pregunta="¿Cada cuánto se hacen las copias y cuánto se conservan?",
relevantes={"d1"}, recuperados=["d1", "d3"],
respuesta="Cada 24 horas [d1]; se conservan 7 días [d1].",
citas=[("d1", True), ("d1", True)],
afirmaciones=2, apoyadas=2, con_cita_valida=2,
abstencion=False, latencia_ms=900),
dict(pregunta="¿Cómo exporto los datos y en qué formato?",
relevantes={"d2", "d4"}, recuperados=["d4", "d3"],
respuesta="Abre Ajustes y Exportar [d2]; descarga el CSV [d4].",
citas=[("d2", True), ("d4", True)],
afirmaciones=2, apoyadas=1, con_cita_valida=1,
abstencion=False, latencia_ms=1500),
dict(pregunta="¿En qué región se almacenan los datos?",
relevantes={"d5"}, recuperados=["d3", "d5"],
respuesta="En Madrid [d5]; se replica en París [d3].",
citas=[("d5", True), ("d3", False)],
afirmaciones=2, apoyadas=1, con_cita_valida=1,
abstencion=False, latencia_ms=1100),
dict(pregunta="¿Qué compensación se ofrece por una interrupción?",
relevantes=set(), recuperados=["d1", "d3"],
respuesta="El manual no lo especifica.", citas=[],
afirmaciones=0, apoyadas=0, con_cita_valida=0,
abstencion=True, latencia_ms=700),
]
k = 2
con_respuesta = [c for c in casos if c["relevantes"]]
recall, rr = [], []
for c in con_respuesta:
top = c["recuperados"][:k]
recall.append(len(set(top) & c["relevantes"]) / len(c["relevantes"]))
rr.append(next((1 / i for i, doc in enumerate(top, 1)
if doc in c["relevantes"]), 0))
pares = [(doc in c["recuperados"][:k] and respalda)
for c in casos for doc, respalda in c["citas"]]
n_afirmaciones = sum(c["afirmaciones"] for c in casos)
def ratio(n, d):
return n / d if d else None # Sin denominador: no evaluable.
latencias = sorted(c["latencia_ms"] for c in casos)
sin_respuesta = [c for c in casos if not c["relevantes"]]
resultados = {
"recall@2_macro": mean(recall),
"mrr@2": mean(rr),
"validez_citas_micro": ratio(sum(pares), len(pares)),
"cobertura_citas_micro": ratio(
sum(c["con_cita_valida"] for c in casos), n_afirmaciones),
"apoyo_contexto_micro": ratio(
sum(c["apoyadas"] for c in casos), n_afirmaciones),
"abstencion_correcta": ratio(
sum(c["abstencion"] for c in sin_respuesta), len(sin_respuesta)),
"p50_ms_sintetico": median(latencias),
"p95_ms_sintetico": latencias[ceil(0.95 * len(latencias)) - 1],
}
for nombre, valor in resultados.items():
print(f"{nombre}: {valor:.4f}" if valor is not None
else f"{nombre}: no evaluable")
Expected output:
recall@2_macro: 0.8333
mrr@2: 0.8333
validez_citas_micro: 0.6667
cobertura_citas_micro: 0.6667
apoyo_contexto_micro: 0.6667
abstencion_correcta: 1.0000
p50_ms_sintetico: 1000.0000
p95_ms_sintetico: 1500.0000
You can reproduce the fractions: mean recall is (1 + 0,5 + 1) / 3; MRR is (1 + 1 + 0,5) / 3. There are four valid claim–citation pairs out of six, and four supported claims out of six. The second answer mentions d2 even though the retriever did not provide it: getting a fact right is not the same as justifying it with the received context. The third one invents a replica in Paris.
Retrieval averages are macro, one contribution per question with an answer; citation and claim ratios are micro, adding their respective numerators and denominators. With four timings, p95 using the nearest-rank method matches the maximum. This is an arithmetic demonstration, not a stable estimate of production latency.
Measure latency and decide whether you need another GPU
In a real test, measure from when the application receives the query until it delivers the complete response. Also record retrieval, reranking, waiting, time to first token, and generation. NVIDIA’s documentation on inference metrics distinguishes the first token from full latency and warns that tools may use different definitions.
Run the same suite with representative load and concurrency. Publish the number of requests, errors, and retries, along with p50 and p95. Separate cold and warm cache. Keep the exact model, quantization, GPU and VRAM, inference engine, output limits, and number of context tokens. The sum of the p95 values for each stage is not the p95 for the full path: calculate the latter from the complete traces for each request.
If evidence is missing, start with the index and the retriever. If evidence is available and waiting is concentrated in the generator, compare inference configurations while keeping the quality set fixed. A GPU with more memory may allow a different configuration, but it does not fix an invented citation or by itself guarantee lower latency.
If you are going to host the generator, review Flatkey's GPU options and validate the configuration with your workload. To explore models via API, use the model catalog. Compare observed quality and latency before choosing the infrastructure.
Frequently asked questions
Does RAG eliminate LLM hallucinations?
There is no general guarantee. The system may retrieve irrelevant text, use an outdated version, or generate claims that do not appear in the context. Check evidence, citations, and abstention separately.
Is it enough to check that citations open a page?
Also check that the cited excerpt supports the claim, was available for that answer, and corresponds to the appropriate version. The script distinguishes a present citation from one labeled as valid.
How many questions do I need to evaluate RAG with an LLM?
The four in the example are enough to verify the calculations. To make production decisions, build a sample that represents your topics, query types, and important failures, report its size, and review variation across runs. Do not extrapolate a stable accuracy rate from this minimal set.
What change should I try first if the result is poor?
Identify the stage: missing evidence, poorly used evidence, or excessive latency. Change that part and repeat the same questions. Evaluating RAG with an LLM is useful when each score helps explain a failure and verify whether the next change resolves it.



