LevelUpWith

Explore / AI Evals as Infrastructure: LLM Apps and Agents / Lesson 2

Lesson 2: Anatomy of an Eval: Evals as Infrastructure

Break an eval into its parts (input, the system under test, output, check, score and aggregate) and see how it differs from a unit test when the system's output varies from run to run.

Free to read, no account needed. Part of AI Evals as Infrastructure: LLM Apps and Agents.

By the end of this level you'll be able to

  • Write a minimal eval loop in Python or TypeScript that runs a list of inputs through a model API and records a pass or fail for each one
  • Explain why an eval reports a pass rate across many cases, not one green or red result, and why you run cases more than once when output varies
  • Name the parts of an eval that must be versioned and kept, as you would any other infrastructure: dataset, prompt, model ID, checks and results

From one prompt to a measurement

In Level 1 you saw why trying a few prompts by hand misleads you: you remember the good answers, you try the cases you already expect to work, and nothing is written down. This level replaces that with the smallest thing that counts as an eval. It is a loop you can write in about 40 lines.

If you write unit tests, you already know most of the shape. There are six parts:

  1. Input: a case from your dataset, such as a support ticket.
  2. System under test (SUT): your prompt, the model and any code around them. Treat it as a black box.
  3. Output: whatever the system returned.
  4. Check: a function that decides whether that output is acceptable.
  5. Score: the result for one case, here pass or fail.
  6. Aggregate: the scores rolled up into a number across all cases and runs.

One thing breaks the unit-test analogy. add(2, 2) returns 4 every time. A model call can return different text for the same input. You might expect setting temperature to 0 to stop that. It doesn't. Anthropic, OpenAI and Google all say temperature 0 does not guarantee identical output. Several current models, including recent Claude and GPT-5-family models with reasoning on, don't accept a custom temperature at all. So you can't make the system deterministic. You have to measure it.

The running example: ticket triage

The SUT reads a support ticket and replies with one label: billing, bug, account or other. The dataset is a JSONL file kept in git:

{"id": "t-001", "input": "I was charged twice for March", "expected": "billing"}
{"id": "t-002", "input": "Export button does nothing on Safari", "expected": "bug"}
{"id": "t-003", "input": "How do I change the email on my login?", "expected": "account"}

The expected answer is one known label, so the check can be an exact match. That kind of check is cheap, fast and never wrong about itself.

Walkthrough: the loop in Python (Claude)

import json, os, hashlib, datetime, subprocess
import anthropic

MODEL = os.environ.get('MODEL_ID', 'claude-sonnet-5-5')  # read the model ID from config, never hard-code it deep in the code
PROMPT_PATH = 'prompts/triage.txt'
DATA_PATH = 'data/triage_golden.jsonl'
TRIALS = 3                                 # run each case several times because the output can vary

client = anthropic.Anthropic()             # reads ANTHROPIC_API_KEY from the environment
prompt = open(PROMPT_PATH).read()

def sut(ticket: str) -> str:
    resp = client.messages.create(
        model=MODEL, max_tokens=1024, system=prompt,
        messages=[{'role': 'user', 'content': ticket}],
    )
    # The reply can contain thinking blocks as well as text, so keep only the text blocks
    return ''.join(b.text for b in resp.content if b.type == 'text').strip()

def check(output: str, expected: str) -> bool:
    return output.lower() == expected      # binary: pass or fail, no partial credit

cases = [json.loads(line) for line in open(DATA_PATH)]
results = []
for case in cases:
    for trial in range(TRIALS):
        out = sut(case['input'])
        results.append({'id': case['id'], 'trial': trial,
                        'output': out, 'passed': check(out, case['expected'])})

pass_rate = sum(r['passed'] for r in results) / len(results)
print(f'pass rate: {pass_rate:.1%} over {len(results)} runs')

Here is a realistic result for 20 cases with 3 trials each:

pass rate: 88.3% over 60 runs
t-007  3/3 fail  output='Billing'... no: 'refund'   <- invented a label not in the list
t-014  2/3 pass                                    <- unstable

Compare the two cases. t-007 fails every time, so it is a real, repeatable defect. t-014 passes on some runs and fails on others. A single run would have given you either result for t-014, which is exactly why you run more than once.

Gotcha: small datasets jump around. With 20 cases, one case changing result moves the pass rate by 5 points. Don't celebrate or panic over a 3-point change on 20 cases. More cases and more trials make the number steadier.

Gotcha: don't rerun until it goes green. If you retry an unstable case until it passes, you have hidden the variation you set out to measure. Record every trial.

The same loop in TypeScript (OpenAI)

Only the sut function changes from provider to provider. The check and the aggregate stay the same, so you can compare models fairly. Gemini, and open-weight models served behind an OpenAI-compatible endpoint, fit into the same slot.

import OpenAI from "openai";
const client = new OpenAI();
const MODEL = process.env.MODEL_ID ?? "gpt-5.5-2026-04-23"; // a pinned snapshot, not a floating alias

async function sut(ticket: string, prompt: string): Promise<string> {
  const resp = await client.responses.create({ model: MODEL, instructions: prompt, input: ticket });
  return resp.output_text.trim(); // the SDK joins all text output; don't assume output[0] holds it
}

Evals are infrastructure: version the five parts

A pass rate means nothing unless you know what produced it. Suppose the score drops from 92% to 85% between Monday and Thursday. The first question is whether anything about the eval itself changed. You can only answer it if every run records:

  • Dataset: commit it to git and store its hash with each run.
  • Prompt: keep it in a file, not an inline string, and store its hash.
  • Model ID: use the exact pinned ID. OpenAI's docs recommend pinning a dated snapshot in production. Anthropic's newer dateless IDs, such as claude-sonnet-5-5, are already pinned snapshots.
  • Checks: they are code, so they live in git, and a changed check is a changed eval.
  • Results: save every output, not just the score, so you can diff two runs.
sha = lambda p: hashlib.sha256(open(p, 'rb').read()).hexdigest()[:12]
meta = {'model': MODEL, 'prompt_sha': sha(PROMPT_PATH), 'data_sha': sha(DATA_PATH),
        'git': subprocess.run(['git', 'rev-parse', '--short', 'HEAD'], capture_output=True, text=True).stdout.strip(),
        'trials': TRIALS, 'at': datetime.datetime.now(datetime.timezone.utc).isoformat()}
os.makedirs('results', exist_ok=True)
with open(f"results/run-{meta['at'][:19].replace(':', '')}.jsonl", 'w') as f:
    f.write(json.dumps({'meta': meta, 'pass_rate': pass_rate}) + '\n')
    f.writelines(json.dumps(r) + '\n' for r in results)

Never write API keys into run records. Secrets stay in the environment.

Hands-on exercise

  1. Write 15 triage tickets with expected labels. Include 3 deliberately ambiguous ones.
  2. Run the loop with TRIALS = 3 against one model, then change MODEL_ID and run it again against a second model from a different provider.
  3. For each model, report the overall pass rate, the cases that failed all 3 trials, and the cases that passed only some trials.
  4. Change one word in the prompt, run again, and confirm that the new results file shows a different prompt_sha.

Key takeaways

  • An eval has six parts: input, system under test, output, check, score and aggregate.
  • Model output varies even at temperature 0, so you report a pass rate across many cases and repeated trials, not one green or red result.
  • Cases that pass on some trials and fail on others are information. Record them, don't retry them away.
  • Version the dataset, prompt, model ID and checks, and keep the full results. Without them, two pass rates can't be compared.
  • Keep the check and the aggregate the same across providers so that only the system under test changes.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, Traces: Recording What Your App Actually Did.

Create a free account →See the whole course

More like this