Evaluating RAG Quality

Test retrieval and answer quality in an existing RAG application, and use a fixed set of questions to compare results before and after optimization.

🎯 Introduction

We have built a RAG application, but how can we tell whether its answers are accurate? This article uses test questions with known answers to check whether RAG retrieves the right material and answers correctly, then uses comparative testing to assess later optimizations.


🧱 How Do You Evaluate a RAG Response?

Continue using the four passages stored in rag_docs by 05.seed.mjs in “Similarity Search”:

MaterialText
Refund policyYou can request a refund within 7 days of purchase. Sale items are nonrefundable.
Refund requirementsRefund requests require an order number and proof of purchase.
Shipping instructionsStandard orders ship within 48 hours of payment.
Support hoursCustomer support is available daily from 9:00 to 18:00.

Start with this question:

Can I get a refund for sale items?

The refund policy establishes the expected answer in advance: “Sale items are nonrefundable.” Now inspect what RAG actually retrieves and answers.

Open 06.answer.mjs from “Retrieval and Answers,” set question to the question above, and change the Qdrant query’s limit to 2, allowing at most two passages per query.

Ensure Qdrant is running and that rag_docs and your .env configuration are available, then run:

node --env-file=.env 06.answer.mjs

Suppose the program returns the following (a teaching example; use your actual runtime output):

Retrieved material:
[1] Source: guide.md
Refund requests require an order number and proof of purchase.

[2] Source: guide.md
Refunds
You can request a refund within 7 days of purchase. Sale items are nonrefundable.

Model answer: Sale items are nonrefundable.[2]

Compare the expected answer with the retrieved material and response:

CheckResultReason
Was the right material retrieved?YesPassage 2 contains the refund rule for sale items
Is the model’s answer correct?YesSale items are indeed nonrefundable
Is the citation supported?YesThe cited passage 2 supports the conclusion

That is one RAG evaluation: establish the expected answer first, then inspect the returned material and answer.


🛠 Prepare a Fixed Set of Test Questions

One question cannot establish the quality of the entire application. Prepare several questions with known answers and label the correct source material for each.

The point IDs below come from the id fields in the documents array in 05.seed.mjs, identifying records already stored in Qdrant.

Test questionCorrect materialPoint IDReference answer
Can I get a refund for sale items?Refund policyfb1359e8-82d1-4c7a-9e67-eeabe6fc47bcSale items are nonrefundable
How long do standard orders take to ship?Shipping instructions3dc3e6da-a3e1-43ac-8a9f-656110ccf96fWithin 48 hours of payment

These prepared questions and criteria form our test set. If you have changed the knowledge base IDs, use the actual IDs of your current records.

Manually inspecting retrieval becomes tedious as questions accumulate. We can automate retrieval and use IDs to check whether the correct material was found.


🔍 Automate Retrieval Evaluation

1. What Is Hit@2?

Hit@2 measures the proportion of test questions for which at least one correct passage appears in the top two retrieval results.

For example, if only one of two answerable questions retrieves the right material, Hit@2 is 1 ÷ 2 = 50%.

2. Initialize the Clients

Create 10.evaluate.mjs. Reuse Node.js 24.x, openai@7.62.0, and @qdrant/js-client-rest@1.20.0; no new dependencies are needed.

import OpenAI from "openai";
import { QdrantClient } from "@qdrant/js-client-rest";

const ai = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_BASE_URL
});

const qdrant = new QdrantClient({ url: "http://127.0.0.1:6333" });

3. Add the Test Questions

Append cases to the same file, using the questions and point IDs from the test set:

const cases = [
    {
        question: "Can I get a refund for sale items?",
        expectedId: "fb1359e8-82d1-4c7a-9e67-eeabe6fc47bc"
    },
    {
        question: "How long do standard orders take to ship?",
        expectedId: "3dc3e6da-a3e1-43ac-8a9f-656110ccf96f"
    }
];

question is the test question; expectedId is the manually labeled ID of the correct material. Each question here requires only one passage to answer.

Fill in these two fields manually; do not fill in retrieval results. The next step queries Qdrant for them.

4. Run Retrieval and Calculate the Hit Rate

Append the code below. It performs vector search for each question, checks whether the results include the correct material, and calculates the hit rate.

let hitCount = 0;

for (const item of cases) {
    // Generate a vector for the test question
    const embedding = await ai.embeddings.create({
        model: process.env.AI_EMBEDDING_MODEL,
        input: item.question
    });

    // Retrieve the top two passages from Qdrant
    const results = await qdrant.query("rag_docs", {
        query: embedding.data[0].embedding,
        limit: 2,
        with_payload: true
    });

    // Extract the retrieved IDs and check for the expected ID
    const retrievedIds = results.points.map(point => point.id);
    const hit = retrievedIds.includes(item.expectedId);

    if (hit) {
        hitCount++;
    }

    // Print passage text for manual verification
    console.log(`Test question: ${item.question}`);
    console.log("Retrieval results:");
    results.points.forEach((point, index) => {
        console.log(`${index + 1}. ${point.payload.text}`);
    });
    console.log(`Hit: ${hit ? "Yes" : "No"}\n`);
}

const hitRate = hitCount / cases.length * 100;
console.log(`Hit@2:${hitCount}/${cases.length}(${hitRate.toFixed(1)}%)`);

results.points contains the material returned by Qdrant, and retrievedIds contains its IDs. includes() checks for the labeled expectedId, while payload.text prints the actual retrieved text.

Run the complete file:

node --env-file=.env 10.evaluate.mjs

Suppose the first question retrieves the refund policy, but the second misses the shipping instructions. The terminal output would look like this (illustrative, not measured):

Test question: Can I get a refund for sale items?
Retrieval results:
1. Refund requests require an order number and proof of purchase.
2. Refunds
You can request a refund within 7 days of purchase. Sale items are nonrefundable.
Hit: Yes

Test question: How long do standard orders take to ship?
Retrieval results:
1. Refunds
You can request a refund within 7 days of purchase. Sale items are nonrefundable.
2. Customer support is available daily from 9:00 to 18:00.
Hit: No

Hit@2:1/2(50.0%)

Only the first question finds its required material, so there is one hit. Add more questions to cases to recalculate the hit rate over a larger set.


💬 Evaluate Answer Quality

The evaluation program performs retrieval without generating answers. Next, test each question with 06.answer.mjs and manually compare the response with the reference answer and the material supplied to the model for that request.

Here is an example evaluation log with hypothetical answers and retrieval results:

Test questionRetrieved materialModel answerCorrect answerSupported answer
Can I get a refund for sale items?Refund requirements, refund policySale items are nonrefundable.YesYes
How long do standard orders take to ship?Refund policy, support hoursWithin 24 hours of payment.NoNo
How long do standard orders take to ship?Refund policy, support hoursWithin 48 hours of payment.YesNo

The third answer happens to be correct, but the supplied material contains no shipping time. We therefore cannot treat it as grounded in the retrieved sources. If an answer includes citations, also verify that the cited text supports its conclusions.

Test unanswerable questions too, such as “How long does it take to receive the money after a refund request is approved?” The current material does not specify this, so a reasonable answer is “The available material does not state when the refund will arrive.” Exclude such questions from Hit@2 and separately check whether the model fabricates answers when evidence is insufficient.


📊 How Can You Tell Whether an Optimization Helps?

When studying hybrid retrieval, RRF, and rerankers later, record the current vector search results first. Then change the retrieval or ranking method and reevaluate retrieval and answer quality using the same questions.

For example, a comparison of vector and hybrid retrieval might produce the following (illustrative, not measured):

Evaluation itemVector retrievalHybrid retrieval
Can I get a refund for sale items? (retrieval)HitHit
How long do standard orders take to ship? (retrieval)MissHit
Hit@250%100%
Answer accuracy (manual review)50%100%

Keep the questions, knowledge base, maximum number of passages sent to the model, answer model, and prompt unchanged. Change only the retrieval or ranking method under evaluation. Consider added latency as well as accuracy. Results from two questions describe only that test set, not all possible questions.


❓ Knowledge Check

Q1: What if a question has multiple correct passages?

Store the correct IDs in an array and count a hit if either of the top two results matches any of them. If the answer requires multiple passages together, separately check that all required material was retrieved.


🧪 Exercise

Add this case to cases in 10.evaluate.mjs. Its ID identifies the support hours passage stored by 05.seed.mjs:

{
    question: "What are the daily customer support hours?",
    expectedId: "2be00876-0ba9-4f3a-9ca2-2c70fec4f15a"
}

Rerun evaluation and check whether the support hours appear in the top two results. The Hit@2 denominator should now be 3. Then test the same question with 06.answer.mjs, checking that it answers “daily from 9:00 to 18:00” and that the supplied material supports that answer.


🎉 Congratulations! You can now evaluate basic RAG retrieval and answer quality and compare performance before and after optimization.