AI Hints
Home›RAG Tutorial›Judging Answers
RAG · Lesson 76 of 120

Answer Relevance

Did it answer.

⏱ 2 min read▶ Video at 1:14:52🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

An answer can be perfectly grounded, and still miss the point. If someone asks about delivery costs, store addresses won't help. Answer relevance asks, does the answer actually address the question?

Answer Relevance
From the video: Answer Relevance
  • Grounded isn't enough
  • Must address the question
  • Answer relevance

Scoring relevance

Score is a number from one to five. The judge rates how directly each answer addresses the question. We try a direct answer, an off topic one, and a vague one. Run it. The direct answer scores highest, and the other two score low.

relevance.pypython
from pydantic import BaseModel, Field
from llm import llm

class Score(BaseModel):
    relevance: int = Field(ge=1, le=5)

judge = llm.with_structured_output(Score)
q = "How much is UK delivery?"
for ans in ["Standard UK delivery costs £4.99, and is free over £50.",
            "Northwind has stores in Leeds and York.",
            "Delivery is available."]:
    s = judge.invoke(f"Question: {q}\nAnswer: {ans}\n"
                     "Rate from 1 to 5 how directly the answer addresses the question.")
    print(s.relevance, "|", ans)
Output
5 | Standard UK delivery costs £4.99, and is free over £50.
1 | Northwind has stores in Leeds and York.
1 | Delivery is available.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()

Three answer checks

Faithfulness asks if it's grounded. Relevance asks if it answers the question. Correctness asks if it matches the truth. A good answer passes all three.

keyvalue
Faithfulnessgrounded
Relevanceon topic
Correctnesstrue
Good answerall three

Summary

Answer relevance checks the answer addresses the question, not just that it's grounded. Next, using a model as a judge.

Key takeaways
  • On topic?
  • Score 1 to 5
  • Three checks
Next up: LLM as a Judge — grading with a model