# 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.

AI and LLM interview question Q485, Coding and practical. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/write-tests-and-evals-for-an-llm-function

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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.

*Diagram, Two test layers for one LLM function: Ordinary code gets unit tests with a fake model, so the result never changes. The model's answers get evals on labelled cases. A change ships only when both layers pass and every bar holds.*
1. The change feeds the fake model tests.
2. The same change also runs the labelled cases.
3. The fake's fixed reply goes into the plain asserts.
4. Each case's real answer is scored.
5. Passing code tests count toward shipping.
6. Every 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.

```python
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:

```text
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." Better: They 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." Better: Too 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." Better: Check 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?

A. The test runner needs a restart.
B. The reply can change from run to run, so the test needs a fake model, and the wording belongs to an eval.
C. The sentence is too long.
D. The claim date changed on Tuesday.

**Answer:** B. A real model can give different text from the same input. Keep the code test on a fake model with fixed replies, and score the model's wording with labelled cases.

**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?

A. Ship it, because most fields improved.
B. Block it, and read the four failing cases first.
C. Remove the policy-number field from the eval.
D. Lower the bar to 90 per cent.

**Answer:** B. A drop on a field that was right before counts as a regression (a new failure in something that used to work). Read the four failures, fix them, and rerun. Gains on other fields do not cover it.

## Can you answer these from memory?

**Flash cards**

- **What is a unit test here?** A check of the code around the model, with a fake model that gives fixed replies.
- **What is an eval?** Labelled cases run through the real model, each answer scored, and the pass rate tracked.
- **Why not assert the model's exact words?** Models can give different output from the same input, so a fixed assert can fail.
- **What is a grader?** The rule or model that decides whether an answer passes.
- **Why check a grader model?** It must agree with human labels, and graders often favour longer answers.
- **When does an eval run?** On every change, and each new production mistake becomes a new case.

## Likely follow-up questions

- Q249 What is LLM-as-a-judge? https://designervenkat.online/interview/ai/what-is-llm-as-a-judge
- Q251 How do you calibrate a judge against humans? https://designervenkat.online/interview/ai/how-do-you-calibrate-a-judge-against-humans
- Q257 How do you regression-test prompts? https://designervenkat.online/interview/ai/how-to-regression-test-prompts
- Q256 Capability evals vs regression evals? https://designervenkat.online/interview/ai/capability-evals-vs-regression-evals
- Q268 How many eval examples are enough? https://designervenkat.online/interview/ai/how-many-eval-examples-are-enough

## Learn it in depth

- [LLM Evaluations](https://designervenkat.online/learn/ai-engineering/llm-evaluations)
- [Deterministic Evals](https://designervenkat.online/learn/ai-engineering/deterministic-evals)
- [A model as the judge](https://designervenkat.online/learn/ai-engineering/model-based-evals)
