AI Agents & LLMsHard
How do you evaluate a RAG system?
Learning path, stage 3 of 5: RAG and fine-tuning · question 5 of 10Evaluate retrieval and generation separately. For retrieval, check whether the right chunks are in the top k (recall@k, MRR). For generation, check whether the answer is faithful to those chunks and actually answers the question (faithfulness or groundedness, answer relevance, correctness). Build a labelled test set from real user questions and run it on every change.
Retrieval metrics
- Recall@k / hit rate: is a gold chunk in the top k?
- MRR / nDCG: how high is it ranked?
- Context precision: how much of what you retrieved is actually relevant? Noise hurts the answer.
Generation metrics
- Faithfulness / groundedness: is every claim supported by the retrieved context?
- Answer relevance: does it address the question?
- Correctness: compared with a reference answer, when you have one.
- Citation accuracy: do the cited sources really support each claim?
How to score
- Use exact or programmatic checks where possible.
- Use an LLM-as-judge with a clear rubric for the rest. Calibrate it against human labels.
- Frameworks like RAGAS package these metrics. You still need your own questions.
- Include unanswerable questions to test abstention, plus adversarial ones (prompt injection inside documents).
Sources
Code example
tsx
1// Retrieval recall@k + an LLM-judge faithfulness score.2import Anthropic from "@anthropic-ai/sdk";3import { z } from "zod";4import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";56interface EvalCase { question: string; goldChunkIds: string[] }78export function recallAtK(retrievedIds: string[], gold: string[], k = 5) {9 const top = new Set(retrievedIds.slice(0, k));10 return gold.some((id) => top.has(id)) ? 1 : 0;11}1213const Verdict = z.object({ unsupported_claims: z.array(z.string()), faithful: z.boolean() });14const client = new Anthropic();1516export async function judgeFaithfulness(context: string, answer: string) {17 const res = await client.messages.parse({18 model: "claude-opus-5-5",19 max_tokens: 2048,20 messages: [{21 role: "user",22 content: `<context>\n${context}\n</context>\n<answer>\n${answer}\n</answer>\n` +23 "List every claim in the answer that the context does not support. faithful = none found.",24 }],25 output_config: { format: zodOutputFormat(Verdict) },26 });27 return res.parsed_output;28}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.