Write Tests and Evals for an LLM Function
Test the code around the model with ordinary unit tests, then score its answers with evals over real labelled cases, explained for your AI interview.
In short
Write two kinds of tests. Ordinary unit tests check the code around the model, using a fake model that always gives the same reply. Evals run the real model on a labelled set of cases, score each answer, and track the pass rate, so a change that makes things worse can be blocked.
12 min readIntermediateCommon ยท estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
I test an LLM function in two layers. First, ordinary unit tests on the code around the model, using a fake model that always gives the same reply. Second, evals: the real model runs on labelled cases, like past insurance claims, and I score each answer and track the pass rate. A change ships only if every bar still holds. Every real mistake then becomes a new case.
An LLM function is a normal function with a model call inside. Take one that reads an insurance claim email and returns the policy number, the incident date, the amount claimed and whether anyone was hurt. Some of its code is ordinary: parsing the reply, and deciding what to do when the reply is broken. That part gets unit tests. The model's answers are different, because they can change from run to run, so they get evals.
For the ordinary code, I swap the model for a fake that returns fixed text. I test a clean reply and a reply with extra chatter, and check that the broken one goes to a person instead of crashing. These tests run in seconds, so they run on every change.
For the model, I build a labelled set of past claims, with typical cases, awkward ones such as dates written two ways, and a few hostile ones. I run the real model, score each field, and compare the pass rate with the last run. If the policy number drops, the change is blocked, and each new failure becomes a new case.
Where the answer is free text, exact matching fails. I use a rule where I can, and a grader model with a clear rubric where I can't. Before I trust the grader, I check it against human labels, because graders tend to favour longer answers.
What are tests and evals, in plain words?
An LLM, or large language model, is the AI that reads and writes text, like the one behind a chatbot. A test checks that a piece of code gives the right result for a known input. An eval, short for evaluation, is a test of a model's answers across many real cases. Each answer is scored, and you watch the pass rate, which is the share of cases that pass.
Think of a bank training a new teller. Fixed sums check the till, which is like a unit test. A month of recorded calls, each scored against a checklist, is like an eval. You need both, because a teller can count the cash perfectly and still quote the wrong fee. For a claims assistant, the fixed sums test the code around the model, and the recorded calls test what the model says.
Key words
- Unit test
- A small check of ordinary code, with a known input and a known output.
- Eval
- A set of labelled cases run through the model, with each answer scored.
- Labelled case
- An input plus the answer a person says is right, such as a claim and its policy number.
- Grader
- The rule or model that decides whether an answer passes.
- Pass rate
- The share of cases that pass, such as 386 out of 400.
Why aren't normal tests enough, and what do you test?
A function that calls a model has two parts. Some of it is ordinary code: it builds the prompt, reads the reply, checks the fields and picks a fallback. The rest is the model's answer, and that can change from run to run. Each part needs its own kind of test.
Two test layers for one LLM function
Code or prompt change
edits the function or its prompt
Layer 1: code around the model
Fake model
same fixed reply on every run
Plain asserts
parsing, fallbacks, safe routes
Layer 2: the model's answers
Labelled cases
real inputs with the right answer
Score each case
rule or grader, pass or fail
Ship or block
every bar must still hold
- 1The change feeds the fake model tests.
- 2The same change also runs the labelled cases.
- 3The fake's fixed reply goes into the plain asserts.
- 4Each case's real answer is scored.
- 5Passing code tests count toward shipping.
- 6Every eval pass rate must clear its bar.
For the ordinary code, a unit test swaps the model for a fake that returns fixed text. Test a clean reply and a reply with extra chatter, and check that the function sends the broken one to a person. An assert is a line that fails the test if a check is false. These run in seconds, so they can run on every change.
OpenAI's guide on evals explains why the model needs more than normal tests. Python's testing docs say each test case should stand alone:
โGenerative AI is variable. Models sometimes produce different output from the same input, which makes traditional software testing methods insufficient for AI architectures.โ
OpenAI
โThe testing code of a TestCase instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases.โ
Python documentation
How do you build the eval set and grade the answers?
Start by writing down what good means for each field. Anthropic's guide says to define success criteria first, then build evaluations that measure them. Then build the set:
- 1
Define good, field by field
The policy number must match exactly. The date must be the right day, read the way the claims team reads it.
- 2
Collect real cases and label them
Use past claims with personal details removed, and have a claims handler write the right answer for each one.
- 3
Mix in the hard ones
Keep typical cases, awkward ones such as dates written two ways, and hostile ones that try to change the output.
- 4
Score each case
Use a rule for exact fields and a grader for free text. Report the pass rate for each field, not one number.
- 5
Run it on every change
Each new production mistake becomes a new case, so the set grows and the same mistake is caught if it comes back.
Anthropic's guide gives two rules of thumb for this part:
โPrioritize volume over quality: More questions with slightly lower signal automated grading is better than fewer questions with high-quality human hand-graded evals.โ
Anthropic
โTest to ensure reliability first, then scale.โ
Anthropic, on LLM-based grading
Grading is where the choices matter. A rule checks what it can, and a grader model reads what a rule can't:
- Rule
Exact match or field check
Fastest and most reliable, and it scales. It lacks nuance for judgments a rule can't capture.
- Grader model
A model that marks against a checklist
Flexible for free text such as summaries. It needs a detailed rubric (a written checklist of what a good answer does), and its scores are checked against human labels first.
Tip
Before you trust a grader model, check it against human labels. Graders tend to favour longer answers, so control for length. OpenAI's guide also recommends pairwise comparison or pass/fail for more reliability.
What does a real eval run look like?
Made-up numbers, but a real shape. An insurance firm uses a model to read claim emails and fill four fields: policy number, incident date, amount claimed and whether anyone was hurt. The team has 400 past claims, each labelled with the right answers.
- 1
Run 1, current prompt
386 of 400 cases pass all four fields.
- 2
Run 2, new prompt
390 of 400 pass all four fields, but the policy-number check fell from 400 to 396.
- 3
Run 2 is blocked
The rule is that no field may drop, however much the others gain. Before the block stands, rerun the same prompt to make sure the 4 cases fail every time and are not noise.
- 4
Fix and run 3
The policy-number instruction is reworded and the date rule now reads day first, as the claims team does. Run 3 passes 399 of 400, and the policy number is back to 400 of 400.
The code below runs the same idea on a small scale. A stub (a stand-in that returns fixed text) takes the place of the real model call, so the file runs anywhere with Python 3. Its first two checks are unit tests, and the eval scores five labelled claims against a 95 per cent bar.
import json
def extract_policy(text, ask_model):
# The code around the model: read its JSON reply, or return None so a person takes the claim.
try:
return json.loads(ask_model(text))["policy"]
except (json.JSONDecodeError, KeyError, TypeError):
return None
# Unit tests: a fake model gives fixed replies, so the result never changes.
assert extract_policy("any text", lambda t: '{"policy": "PX-220417"}') == "PX-220417"
assert extract_policy("any text", lambda t: "Sure! The policy is PX-220417") is None
print("unit tests: 2 of 2 passed")
# Eval: labelled claims, scored to a pass rate. Each reply stands in for a real model call.
cases = [
("Policy PX-220417, fell on the stairs", "PX-220417", '{"policy": "PX-220417"}'),
("Ref PX-109882, car hit a wall", "PX-109882", '{"policy": "PX-109882"}'),
("Policy PX-550013, flood in the cellar", "PX-550013", '{"policy": "PX-550013"}'),
("Policy PX-771204, stolen bike", "PX-771204", '{"policy": "PX-771240"}'),
("Policy PX-330918, hail on the roof", "PX-330918", '{"policy": "PX-330918"}'),
]
passed = sum(extract_policy(text, lambda t, r=reply: r) == want for text, want, reply in cases)
rate = passed / len(cases)
print(f"eval: {passed} of {len(cases)} passed ({rate:.0%})")
print("gate:", "ship" if rate >= 0.95 else "block, below 95%")Output
unit tests: 2 of 2 passed eval: 4 of 5 passed (80%) gate: block, below 95%
The unit tests pass. The eval scores 4 of 5, and the gate blocks the change, because the one wrong policy number fails the bar.
What does the interviewer want to hear?
A strong answer covers
- Two layers: ordinary tests for the code, evals for the model's answers.
- A fake model in unit tests, so their results never change.
- A labelled set with typical, awkward and hostile cases.
- A pass rate per field, a bar set before the run, and a block on any drop.
- Graders checked against human labels, model graders especially.
- Every production mistake turned into a new case.
Common traps
Trap"Unit tests with the real model cover the model too."
BetterThey can't. A real model can answer differently on different runs, so a fixed assert can fail. Score its wording with evals.
Trap"Ten examples I checked by eye are enough."
BetterToo few cases hide small drops. Use enough labelled cases to see a change on each field, and read the failures.
Trap"The grader says it is good, so it is."
BetterCheck the grader against human labels first. Graders favour longer answers, so control for length.
Can you spot the weak test?
Spot the weak test
A unit test calls the real model and asserts one exact sentence. It passes on Monday and fails on Tuesday with the same input and no code change. What is wrong?
Quick check
You change the prompt. The policy-number field drops from 400 of 400 to 396, and the other three fields improve. What do you do?
Can you answer these from memory?
Flash cards ยท tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 27 November 2026
Shipping an LLM feature without a test set yet?
I design and build AI products and agents, including the UI and the system behind them. Book a short call and say what you need.