LLM evaluation starts with a golden dataset of real questions with expected answers and sources. Score your application on it with task metrics (exact match, faithfulness, answer relevance, retrieval recall@k), use a calibrated LLM-as-a-judge for open-ended answers, rerun the set on every change as a regression gate, and monitor live traffic.
Summary: the short version
- You evaluate the whole application (prompt, retrieval, model, tools), not the model alone, because most failures come from the parts around the model.
- A golden dataset of 50 to 200 real, tagged questions with expected facts and source IDs is the single most valuable evaluation asset.
- Score retrieval and generation separately: recall@k tells you whether the right passage was found, faithfulness tells you whether the answer stuck to it.
- LLM judges agree with humans often enough to be useful, but they show position, verbosity and self-enhancement biases, so calibrate them against human labels.
- Offline evals gate releases; online evals on sampled live traffic find the failures your golden set did not anticipate, which then become new golden cases.
What is LLM evaluation, and how is it different from testing a normal ML model?
LLM evaluation is the practice of measuring whether an LLM-powered application gives correct, grounded, useful and safe outputs on the inputs it will really see, and it differs from classic ML testing because outputs are open-ended text with no single right label.
A churn model outputs a probability you can compare with what happened. An HR assistant asked about leave encashment can be right in many wordings and wrong in subtle ones. Outputs vary between runs, and quality has several dimensions (correctness, faithfulness, format, tone, safety, latency, cost) that no single accuracy number captures. Stanford's HELM benchmark (Liang et al., 2022) made the same point at model level, scoring calibration, robustness, fairness, toxicity and efficiency alongside accuracy.
The bigger shift is what you evaluate. Most bad weeks trace back to a changed chunk size, prompt or retrieval order, with the model itself unchanged, so the unit under test is the whole application.
What is a golden dataset, and how do you build one?
A golden dataset is a fixed, version-controlled set of realistic inputs with the facts a good answer must contain and the sources it should use, which you score your application against on every change. It is your test suite.
Build the first version in a week, not a quarter:
- Pull 100 to 300 real questions from logs, tickets or emails, and keep the users' actual wording.
- Have domain owners write the must-include facts and the source passage for each.
- Add hard cases: ambiguous questions, Hinglish, false premises, out-of-scope requests.
- Include questions whose correct answer is "not in our documents".
- Tag every case by topic and difficulty so you can score slices, then freeze and version it.
Fifty well-chosen cases beat five hundred generated ones. LLM-written synthetic questions can widen coverage, but they are cleaner and easier than real users, so never let them dominate.
In Ivy Professional School's enterprise workshops, the slowest step is getting a policy owner to agree, in writing, what the correct answer to 50 questions is. Teams that manage it discover contradictions in their own documents before the model does.
What is the difference between offline and online LLM evaluation?
Offline evaluation scores your application on a fixed dataset before release; online evaluation scores samples of real production traffic after release. You need both, and they feed each other.
| Aspect | Offline evaluation | Online evaluation |
|---|---|---|
| Data | Golden dataset with expected answers | Live user inputs, usually without labels |
| When | Every prompt, model or retrieval change, in CI | Continuously, on a sample of traffic |
| Metrics | Exact match, fact coverage, recall@k, judge scores against references | Reference-free judge scores, user feedback, escalations, latency, cost |
| Catches | Regressions on known cases | New question types, drift, real-world failures |
| Main risk | Dataset goes stale and stops reflecting users | Privacy of logged conversations; noisy signals |
Which metrics should you use to evaluate an LLM application?
Use the cheapest metric that captures what "correct" means for each task: deterministic checks first, retrieval metrics for RAG, and judge-based scores only for qualities code cannot check.
| Metric | What it measures | How it is computed | Use it for |
|---|---|---|---|
| Exact match | Output equals the expected value | String or field comparison | Classification, extraction, IDs, dates |
| Key-fact coverage | Required facts appear in the answer | Checklist match per case | Policy and FAQ answers |
| Format validity | Output parses and matches the schema | JSON parse plus schema check | Anything feeding another system |
| Faithfulness | Every claim is supported by retrieved context | LLM judge or claim-level check | RAG answers |
| Answer relevance | The answer addresses the question asked | LLM judge, or embedding similarity | Open-ended assistants |
| Retrieval recall@k | Share of the relevant passages found in the top k results | |relevant ∩ top-k| ÷ |relevant| | Any retrieval step |
| Abstention accuracy | Says "not found" when the answer is absent | Score on out-of-scope cases | High-stakes domains |
| Tool-call accuracy | An agent called the right tool with the right arguments | Compare logged tool calls with expected calls | Agents and tool-using assistants |
| Latency and cost | Seconds and tokens per request | Logged per run | Every release decision |
Recall@k deserves special attention in retrieval-augmented generation (RAG). If the right passage is not in the top five results, no prompt can save the answer. Measuring it separately tells you whether to fix retrieval (chunking, embeddings, the vector database) or generation, which are very different jobs. Faithfulness is the metric that catches LLM hallucinations against your own documents. The Ragas paper (Es et al., 2023) formalised this split into context, faithfulness and answer-quality dimensions. For agents (our agentic AI explainer covers why they fail differently), add tool-call accuracy: our LangGraph agent tutorial shows the trace you would score.
How does LLM-as-a-judge work, and can you trust it?
An LLM judge is a second model prompted with a rubric to grade an answer, and you can trust it only after checking its verdicts against human labels on your own data.
The best-known study, Zheng et al. (2023), found that strong judges such as GPT-4 reached over 80% agreement with human preferences, about the same level at which humans agree with each other. The same paper documented biases you must design around:
- Position bias: in pairwise comparisons, judges favour an answer because of where it appears. Run both orders and count only consistent verdicts.
- Verbosity bias: longer answers look better to judges. Tell the judge to ignore length and grade against a reference.
- Self-enhancement bias: judges can favour outputs from their own model family. Use a different family for judging where you can.
- Limited reasoning: judges miss maths and logic errors. Check numbers with code, not with a judge.
Keep the judge's job narrow. A yes/no question ("Is every claim supported by the extract?") with a list of unsupported claims is far more reliable than a 1 to 10 quality score.
import json
from openai import OpenAI
JUDGE_PROMPT = """You are checking an HR policy assistant for faithfulness.
POLICY EXTRACT:
[CONTEXT]
ASSISTANT ANSWER:
[ANSWER]
Is every factual claim in the answer supported by the policy extract?
Ignore tone and length. Reply in JSON only, in this shape:
{"faithful": true, "unsupported_claims": []}"""
def judge_faithfulness(client: OpenAI, model: str, context: str, answer: str) -> dict:
prompt = JUDGE_PROMPT.replace("[CONTEXT]", context).replace("[ANSWER]", answer)
response = client.chat.completions.create(
model=model, # ideally a different model family from the one judged
temperature=0, # drop if your judge model only accepts its default
response_format={"type": "json_object"},
messages=[{"role": "user", "content": prompt}],
)
return json.loads(response.choices[0].message.content)Never ship a judge you have not calibrated. Label 50 answers by hand, run the judge on them, and read every disagreement. If agreement is poor, fix the rubric before trusting a single dashboard built on it.
How do you build a simple LLM eval harness in Python?
Loop over the golden cases, call your application, compute per-case metrics, aggregate them by tag, and exit with an error when a threshold is missed so CI blocks the change. It needs only the standard library.
import json
import statistics
import sys
from collections import defaultdict
# In practice, keep these in golden.jsonl under version control.
GOLDEN = [
{"id": "leave-01", "tag": "leave", "question": "How many casual leaves do I get in a year?",
"must_include": ["12"], "relevant_docs": ["leave-s2"]},
{"id": "travel-03", "tag": "travel", "question": "What is the daily meal allowance in a metro city?",
"must_include": ["1,200"], "relevant_docs": ["travel-s4"]},
{"id": "posh-01", "tag": "posh", "question": "Whom do I contact to report harassment?",
"must_include": ["Internal Committee"], "relevant_docs": ["posh-s1", "posh-s3"]},
]
def answer_question(question: str) -> dict:
"""Replace with a call to your real application. Return the answer text and
the ids of the chunks the retriever returned, best first."""
canned = {
"How many casual leaves do I get in a year?":
("You get 12 casual leaves per calendar year.", ["leave-s2", "leave-s5"]),
"What is the daily meal allowance in a metro city?":
("The meal allowance is Rs 1,000 per day.", ["travel-s2", "travel-s4"]),
"Whom do I contact to report harassment?":
("Write to the Internal Committee at [email protected].", ["posh-s1", "hr-s9"]),
}
answer, retrieved = canned[question]
return {"answer": answer, "retrieved": retrieved}
def fact_coverage(answer: str, must_include: list[str]) -> float:
hits = [fact for fact in must_include if fact.lower() in answer.lower()]
return len(hits) / len(must_include)
def recall_at_k(retrieved: list[str], relevant: list[str], k: int = 5) -> float:
return len(set(retrieved[:k]) & set(relevant)) / len(set(relevant))
def run(golden: list[dict], k: int = 5) -> list[dict]:
rows = []
for case in golden:
out = answer_question(case["question"])
rows.append({
"id": case["id"], "tag": case["tag"], "answer": out["answer"],
"coverage": fact_coverage(out["answer"], case["must_include"]),
"recall": recall_at_k(out["retrieved"], case["relevant_docs"], k),
})
return rows
def report(rows: list[dict]) -> dict:
by_tag = defaultdict(list)
for row in rows:
by_tag[row["tag"]].append(row)
for tag, group in sorted(by_tag.items()):
cov = statistics.mean(r["coverage"] for r in group)
rec = statistics.mean(r["recall"] for r in group)
print(f"{tag:10} n={len(group):<4} coverage={cov:.2f} recall@5={rec:.2f}")
return {"coverage": statistics.mean(r["coverage"] for r in rows),
"recall": statistics.mean(r["recall"] for r in rows)}
THRESHOLDS = {"coverage": 0.90, "recall": 0.80} # agree these with the business owner
if __name__ == "__main__":
results = run(GOLDEN)
overall = report(results)
print("overall", {m: round(v, 2) for m, v in overall.items()})
for row in results:
if row["coverage"] < 1:
print("FAIL", row["id"], "->", row["answer"])
with open("eval_results.jsonl", "w", encoding="utf-8") as f:
f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in results)
if any(overall[m] < t for m, t in THRESHOLDS.items()):
sys.exit("Eval gate failed: do not ship this change.")Running it against the stub shows the shape of a useful report:
$ python eval_harness.py
leave n=1 coverage=1.00 recall@5=1.00
posh n=1 coverage=1.00 recall@5=0.50
travel n=1 coverage=0.00 recall@5=1.00
overall {'coverage': 0.67, 'recall': 0.83}
FAIL travel-03 -> The meal allowance is Rs 1,000 per day.
Eval gate failed: do not ship this change.
$ echo $?
1Two different failures surface. The travel answer retrieved the right section but stated the wrong allowance, a generation problem. The harassment question got a correct answer while missing one of two relevant passages, a retrieval problem worth watching. Then point answer_question at your real system and move the cases into golden.jsonl.
How do you run regression tests on prompts and models?
Run the full golden set on every change to prompts, models, retrieval settings or tools, compare each slice with the last accepted baseline, and block the release if any slice drops beyond an agreed tolerance. The averages hide regressions; the slices reveal them.
Practical rules we use:
- Pin the model version and set temperature to 0 for eval runs, so differences come from your change.
- Run judge-scored cases two or three times and average, since judges vary too.
- Store every run's outputs alongside the scores, so you can diff answers between versions.
- Treat a model provider's upgrade like your own code change: rerun the suite before switching. Providers retire model snapshots on a schedule, so this happens more often than teams expect.
- Score a LoRA fine-tuned model on the same golden set as the prompted base model it is meant to beat.
Put the gate where releases happen. In Ivy Professional School's Advanced Generative AI course, learners deploy their applications as FastAPI services in Docker; our advice is to wire a suite like this into that same pipeline, so each redeploy is a decision backed by scores rather than a hope.
Which tools can help with LLM evaluation?
Open-source libraries cover most metric needs, and hosted platforms add tracing, dataset management and online evaluation; start with a script and adopt a tool when the script becomes a chore.
| Tool | What it is | Good fit when |
|---|---|---|
| Ragas | Open-source Python library with LLM-based RAG metrics such as faithfulness and context quality | You run RAG and want standard retrieval and faithfulness scores quickly |
| promptfoo | Open-source CLI and library for test cases, assertions, side-by-side prompt and model comparison, and red-teaming | You want config-driven tests in CI without much code |
| LangSmith | Commercial platform from LangChain for tracing, datasets, and offline and online evaluation | You build with LangChain or LangGraph and want traces and evals in one place |
| OpenAI Evals | Open-source framework and registry of benchmarks for evaluating models and LLM systems | You want reusable eval templates and benchmark-style runs |
| Your own harness | A script like the one above, plus pytest | You are starting out or need full control |
Worked example: how would a Pune manufacturer evaluate its HR policy assistant?
By turning real employee questions into a tagged golden set, scoring retrieval and answers separately, and gating every change on slice-level thresholds agreed with HR. Imagine a manufacturing company near Pune with about 1,200 employees across a plant and a head office. HR has built a RAG assistant over its leave, travel, payroll and POSH policies, and shop-floor staff often ask in Hinglish.
The team pulls 150 questions from six months of HR helpdesk emails, masks names and employee IDs, and asks policy owners to write the must-include facts and source sections. They add 15 out-of-scope questions ("Can you approve my leave?") and tag everything by policy and language. Thresholds, agreed with the HR head: fact coverage at least 0.90 overall and 0.85 in every slice, recall@5 at least 0.85, abstention correct on every out-of-scope case, and zero POSH answers without a cited section.
Illustrative first run: coverage 0.86, recall@5 0.91, and the Hinglish slice at 0.74. Because retrieval is healthy, the team focuses on generation: the prompt answered in formal English and dropped amounts. A revised prompt that replies in the user's language and quotes the policy line lifts Hinglish coverage. A calibrated judge then samples 5% of live conversations weekly, and every miss goes to HR for review and into the golden set.
What should you do to start evaluating your LLM application?
Ship a small, honest eval this week rather than a perfect one next quarter.
- Collect 50 real questions and get a domain owner to write the must-include facts and sources.
- Add ten hard cases and five questions whose answer is not in your documents.
- Tag every case by topic and language, and store the set in version control.
- Adapt the harness above, measuring fact coverage and recall@k first.
- Calibrate one narrow judge (faithfulness, yes or no) against 50 human labels.
- Agree release thresholds per slice with the business owner and enforce them in CI.
- Sample live conversations weekly and turn every confirmed failure into a golden case.
Frequently asked questions
What is an LLM eval?
An LLM eval is a repeatable test that runs an LLM application on a set of inputs and scores the outputs against defined criteria, such as correctness, faithfulness to sources, format or safety. Teams rerun evals after every prompt, model or retrieval change to catch regressions before users see them.
How many test cases do I need to evaluate an LLM application?
Start with 50 to 200 real, carefully labelled cases covering your main topics and known hard cases. Grow the set over time from production failures, and make sure each important slice, such as a language or product line, has enough cases to be scored on its own.
Is LLM-as-a-judge reliable?
It can be, for narrow and clearly defined questions. Research on MT-Bench found strong judges agreed with human preferences over 80% of the time, similar to agreement between humans. Judges also show position, verbosity and self-enhancement biases, so calibrate yours against human labels on your own data before relying on it.
What is the difference between faithfulness and answer relevance?
Faithfulness asks whether every claim in the answer is supported by the retrieved context, which catches hallucinations. Answer relevance asks whether the answer actually addresses the question. An answer can be perfectly faithful to the documents yet irrelevant to what was asked, so measure both.
How do you evaluate a RAG system?
Evaluate retrieval and generation separately. For retrieval, measure recall@k and precision against labelled relevant passages. For generation, measure fact coverage, faithfulness to the retrieved context and answer relevance. This split tells you whether to fix chunking and search, or the prompt and model.
Sources
- Zheng, L. et al. "Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena." 2023. https://arxiv.org/abs/2306.05685
- Es, S. et al. "Ragas: Automated Evaluation of Retrieval Augmented Generation." 2023. https://arxiv.org/abs/2309.15217
- Liang, P. et al. "Holistic Evaluation of Language Models." 2022. https://arxiv.org/abs/2211.09110
- Ragas documentation. https://docs.ragas.io/en/stable/
- promptfoo documentation. https://www.promptfoo.dev/docs/intro/
- LangChain. "LangSmith Evaluation." Documentation. https://docs.langchain.com/langsmith/evaluation
- OpenAI. "Evals" repository. https://github.com/openai/evals

By