LLM Evaluation Explained: How Evals Work, With Examples
Quick answer
A practical guide to LLM evaluation: build a test set, choose a grader, run a minimal eval in Python and avoid misleading scores.
LLM evaluation is the practice of testing a language model application against a fixed set of inputs and scoring its outputs, so you can tell whether a prompt, model or retrieval change made things better or worse. These tests are called evals. Good evals combine code checks, human review and a model acting as a judge.
Key takeaways
- An eval is a dataset of test inputs plus a grader. Without both, you are judging by feel.
- Use code-based checks wherever the answer can be verified by a rule. Keep human review for building the ground truth and for spot checks.
- An LLM judge must be compared with human labels before you trust its scores.
- Thirty real, messy test cases from your own use case teach you more than a public benchmark score.
On this page:
- What is LLM evaluation, and why can't you just test by trying a few prompts?
- How do you build a test set for your own use case?
- What does a minimal eval look like in code?
- When should you use an LLM as a judge?
- How do you evaluate a RAG pipeline or an agent?
- What mistakes make eval scores misleading?
- How can a student or working developer practise evals?
- Frequently asked questions
| Grading method | How it works | Use it when | Main weakness |
|---|---|---|---|
| Code-based check | Exact match, substring, regex, JSON schema, unit tests on generated code | The correct output can be defined by a rule | Misses meaning: a correct answer in different words can fail |
| Overlap metrics (BLEU, ROUGE) | Counts shared words or phrases with a reference answer | Translation or summarisation with trusted reference texts | Rewards similar wording, not correctness |
| Human review | A person scores outputs against a written rubric | Creating the first labelled set, checking tone, auditing the judge | Slow and costly, and reviewers disagree |
| LLM as judge | A second model scores the output using a rubric prompt | Open-ended answers at volume | Has its own biases and needs calibration against humans |
What is LLM evaluation, and why can't you just test by trying a few prompts?
LLM evaluation replaces "it looked fine when I tried it" with a repeatable score. You need it because model output varies between runs, and a change that fixes one question often breaks another.
OpenAI's evaluation best practices guide describes evals as "structured tests for measuring a model's performance" and lists "vibe-based evals" among the anti-patterns to avoid. The same guide breaks the work into five steps: define the objective, collect a dataset, define metrics, run and compare, and evaluate continuously.
It helps to separate two things people both call evaluation:
- Model evaluation compares base models on public benchmarks. It answers "which model is generally stronger?"
- Application evaluation tests your prompt, your retrieval and your data together. It answers "does my HR chatbot give the right notice period?"
Most working engineers spend their time on the second kind. If the difference between a model and an application built on it is still fuzzy, start with this explainer on what an LLM is in simple words.
How do you build a test set for your own use case?
Collect real inputs, write down what a good output must contain, and include the awkward cases on purpose. Anthropic's documentation on developing test cases advises designing evals that "mirror your real-world task distribution" and reminds you not to forget edge cases.
Say you are building a support assistant for a Jaipur-based edtech startup. A workable first test set could look like this:
- 20 common questions pulled from actual support tickets, such as refund timelines and class schedules.
- 5 edge cases: a question in Hinglish, a question with a typo, a very long message, a question with two intents, an empty message.
- 5 should-refuse cases: a request for another student's phone number, a medical question, a prompt asking the bot to ignore its instructions.
For each case, record the expected behaviour in a form a grader can check: a fact that must appear, a format that must hold, or a refusal that must happen. Anthropic's guidance also favours volume: more questions with automated grading beat a handful of perfectly hand-graded ones.
What does a minimal eval look like in code?
A minimal eval is a loop: run each test case through the model, grade the output, and print the totals. The Python below runs as it is. It uses a stand-in function instead of a real API call so you can see the mechanics first.
import json
def fake_model(question):
# Stand-in for a real LLM call. Swap this for your API client.
canned = {
"What is the notice period?": '{"answer": "60 days", "source": "hr_policy.pdf"}',
"How many casual leaves per year?": '{"answer": "12", "source": "hr_policy.pdf"}',
"Who approves travel claims?": "Your manager approves them.",
}
return canned.get(question, "")
test_cases = [
{"q": "What is the notice period?", "must_contain": "60 days"},
{"q": "How many casual leaves per year?", "must_contain": "12"},
{"q": "Who approves travel claims?", "must_contain": "manager"},
]
def grade(output, case):
try:
data = json.loads(output)
except json.JSONDecodeError:
return {"valid_json": False, "correct": False}
answer = str(data.get("answer", ""))
return {
"valid_json": True,
"correct": case["must_contain"].lower() in answer.lower(),
}
results = [grade(fake_model(c["q"]), c) for c in test_cases]
total = len(results)
print("valid_json:", sum(r["valid_json"] for r in results), "/", total)
print("correct:", sum(r["correct"] for r in results), "/", total)Running it prints:
valid_json: 2 / 3
correct: 2 / 3Trace the third case. The model replied in a plain sentence, json.loads raised an error, and the grader marked it as invalid and incorrect, even though the sentence contains the word "manager". That is intended. The application needs JSON, so a right answer in the wrong format is still a failure. Replace fake_model with your real client, keep the test cases in a file, and you have a regression suite you can run before every prompt change.
When should you use an LLM as a judge?
Use a judge model when quality cannot be captured by a rule, for example whether a reply is polite, complete or grounded in the retrieved document. Do not use it where a code check would do, because code is cheaper and consistent.
A judge is only as good as its rubric. Four habits make it dependable:
- Ask for a narrow verdict. Anthropic's examples end the judge prompt with instructions such as "Output only 'yes' or 'no'", which keeps the result easy to parse.
- Score one criterion at a time. "Is every claim supported by the context?" works better than "Rate this answer out of 10".
- Use a different model to judge from the one that produced the answer, which Anthropic's documentation calls generally best practice.
- Calibrate against people. OpenAI's guide says to validate agreement against your human labels before optimising for cost or latency, and it names position bias and verbosity bias as known judge problems.
A practical calibration routine: you and a teammate label 50 outputs as pass or fail. Run the judge on the same 50. Read every disagreement. Usually the rubric was vague, and tightening it fixes both the judge and your own thinking.
How do you evaluate a RAG pipeline or an agent?
Evaluate each stage separately, then the whole flow. A wrong final answer can come from bad retrieval or bad generation, and one combined score will not tell you which.
For retrieval-augmented generation, the open-source Ragas library lists metrics that map neatly to the two stages:
- Context Precision and Context Recall ask whether the retriever fetched the right chunks.
- Faithfulness asks whether the answer sticks to those chunks.
- Response Relevancy asks whether the answer addresses the question.
Low recall with high faithfulness means the generator is behaving and the search is failing, so you fix chunking or embeddings, and your choice among vector databases for RAG may matter. The reverse pattern points at the prompt. For background, see what RAG is and how it compares with prompt engineering and fine-tuning.
Agents add a third layer. Check the final outcome (was the ticket actually created?), the path (did it call the right tool with valid arguments?) and the cost (how many steps and tokens?). Outcome checks are often plain code: query the database and see whether the row exists.
What mistakes make eval scores misleading?
Most misleading scores come from a test set that does not resemble real traffic, or a metric that measures the wrong thing.
- Testing only easy cases. A 95 percent score on questions you wrote yourself says little about real users.
- Tuning on the test set. If you keep editing the prompt until the same 30 cases pass, hold back a second set you never look at.
- Generic metrics. OpenAI's guide lists overly generic metrics as an anti-pattern. "Helpfulness" is too vague. "Mentions the refund window" is checkable.
- Single runs. Run each case a few times. One pass can hide an output that fails every third attempt.
- Stopping at launch. Sample production conversations every week and add the failures to the test set.
How can a student or working developer practise evals?
Add an eval file to a project you already have. It is the quickest way to learn, and it is a strong signal in interviews, where evaluation now appears regularly among LLM interview questions.
A weekend plan: take your existing chatbot or RAG project, write 30 test cases, add two code checks and one judge prompt, and record the score in the README before and after one prompt change. That before-and-after table shows you can measure your work.
Next step: if you want to build and ship AI projects with this kind of discipline alongside mentors and peers, look at the Leap AI Residency Cohort by Masai, which runs for 8 weeks.
Frequently asked questions
What is the difference between LLM evaluation and benchmarking?
Benchmarking compares base models on shared public tests. LLM evaluation, in the application sense, tests your own prompts, retrieval and data against cases from your use case. A model can top a benchmark and still fail on your company's documents, so product teams need both.
How many test cases do I need to start?
Start with around 30 cases drawn from real inputs: mostly common questions, plus a few edge cases and a few requests the system should refuse. Grow the set every time you find a failure in production. Coverage of real situations matters more than the raw count.
Are BLEU and ROUGE good metrics for chatbots?
Usually not on their own. They count overlapping words with a reference answer, so a correct reply phrased differently scores low and a fluent wrong reply can score well. They suit translation and summarisation with trusted references. For chatbots, prefer fact checks and rubric-based grading.
Can I trust an LLM to grade another LLM?
Only after calibration. Label a sample by hand, run the judge on the same sample and study the disagreements. OpenAI's guidance is to validate agreement with human labels first. Use narrow yes or no rubrics, and re-check the judge whenever you change its prompt or model.
Which tools are used for LLM evals?
You can begin with plain Python and a spreadsheet. As the suite grows, teams adopt open-source libraries such as Ragas for RAG metrics, or the evaluation features offered by model providers. The tool matters less than having a versioned test set and a habit of running it.