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

LLM as a Judge

Grading with a model.

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

Checking hundreds of answers by hand is slow. An LLM judge grades them for us, by comparing each answer with the known fact. It's not perfect, but it's fast, and good enough to track changes.

LLM as a Judge
From the video: LLM as a Judge
  • Hand checking is slow
  • A model grades
  • Fast and consistent

Grading the test set

For the first five test questions, our RAG system writes an answer. The judge compares it with the reference fact, and says correct or not. Run it. We see a grade for each question, and a total. The wrong answers come from the questions where retrieval missed.

judge.pypython
import json
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import llm, answer

class Grade(BaseModel):
    correct: bool

tests = json.load(open("eval_set.json"))[:5]
index = Index(make_chunks(load_docs()))
judge = llm.with_structured_output(Grade)

grades = []
for t in tests:
    a = answer(t["question"], [c for s, c in index.search(t["question"])])
    g = judge.invoke(f"Question: {t['question']}\nReference fact: {t['fact']}\n"
                     f"Answer: {a}\nIs the answer correct?")
    grades.append(g.correct); print(g.correct, "|", t["question"])
print(f"correct: {sum(grades)} of {len(tests)}")
Output
False | What does E03 mean?
False | What is the APR?
True | Can I spread the payments?
False | How many hours until my e-bike is full again?
True | How long until my money comes back?
correct: 2 of 5
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()
Also uses eval_set.json
[
 {"question": "What does E03 mean?", "source": "ebike_errors.md", "fact": "speed sensor"},
 {"question": "What is the APR?", "source": "finance.md", "fact": "9.9"},
 {"question": "Can I spread the payments?", "source": "finance.md", "fact": "spread the cost"},
 {"question": "How many hours until my e-bike is full again?", "source": "ebike_battery.md", "fact": "4 hours"},
 {"question": "How long until my money comes back?", "source": "returns.md", "fact": "7 working days"},
 {"question": "Can I get next-day delivery on a bike?", "source": "shipping.md", "fact": "Next-day"},
 {"question": "How much is a rental deposit?", "source": "rentals.md", "fact": "£150"},
 {"question": "When is the York shop open?", "source": "stores.md", "fact": "5:30pm"},
 {"question": "How much is a Basic service?", "source": "servicing.md", "fact": "£49"},
 {"question": "Do you deliver bikes to France?", "source": "shipping.md", "fact": "complete bikes"}
]

Trusting the judge

Check a sample of the judge's grades by hand. Give it a reference answer whenever you can. Use temperature zero, so grades are repeatable. And use a strong model as the judge.

keyvalue
Spot checkby hand
Referencealways helps
Temperaturezero
Judge modela strong one

Summary

An LLM judge grades answers against reference facts, quickly and consistently. Next, an experiment with chunk size.

Key takeaways
  • Compare to reference
  • Correct or not
  • Spot check
Next up: Comparing Settings — a chunk size experiment