AI & Machine Learning 6 min read 83 viewsReviewed

Building a Repeatable LLM Eval Harness: A Practical Guide

Manual prompt inspection is not a regression test. Here is how to build a small, language-agnostic eval harness that scores outputs, compares to a baseline, and fails loudly when quality drops.

Building a Repeatable LLM Eval Harness: A Practical Guide

Manual prompt inspection is not a regression test. Here is how to build a small, language-agnostic eval harness that scores outputs, compares to a baseline, and fails loudly when quality drops.

In this article (7)Expand ↓

What happened

Real Python published a tutorial on building an LLM (large language model) evaluation harness from scratch. The tutorial makes a simple point. Changing a system prompt and eyeballing a few outputs is not enough. You cannot tell whether you fixed a bug or introduced a regression in a different class of requests. The tutorial walks through building a repeatable evaluation process. That process turns product expectations into verifiable tests.

Why it matters to you

If you maintain an LLM feature, you have probably done this. You tweak the system prompt, try a handful of examples, decide the outputs look better, and deploy. That workflow feels productive. But it gives you no repeatable signal. You cannot tell whether the change improved things on average. You also cannot tell whether it only helped the examples you happened to check. And you cannot separate a real improvement from stochastic variation, which is the natural randomness in model outputs.

The habit that changes is how you verify a prompt change. Instead of eyeballing a few responses, you run a small eval harness before you commit. The harness sends a fixed set of inputs to your model. It scores the outputs. Then it compares the scores to a stored baseline. If the new scores fall below the baseline, the script exits with a non-zero status and you stop.

This is not about building a large benchmarking platform. It is about having a pass/fail gate that runs in seconds and catches obvious regressions. Real Python frames it as turning product expectations into verifiable tests. That framing is useful. An eval is a test for non-deterministic output.

The example below is written in Node.js, not Python. The logic is language-agnostic, and the four pieces are the same in any language. I use JavaScript here because it runs with no extra setup on most machines.

What to do about it

Start with four pieces. You need a small set of representative inputs, a scoring function, a stored baseline, and a pass/fail gate. Keep each piece as simple as possible. You can extend later.

1. Pick representative inputs. Choose inputs that cover the classes of requests your feature handles. If your feature answers questions about orders, include questions about refunds, shipping, and order status. A reasonable starting point is roughly ten to twenty inputs. Store them in a JSON file so you can edit them without touching code.

2. Write a scoring function. The scoring function takes a model output and returns a number. Start with exact-match scoring where you can. For example, if the model must output a JSON object with a specific field, check that the field is present and has the right value. Exact-match scoring is fast, deterministic, and easy to trust. Its limit is brittleness. A correct answer phrased differently fails. That is acceptable for structured outputs and unacceptable for free-form text.

For free-form text, consider model-graded scoring. You ask a second model to compare the output to a reference answer and return a score. This is flexible but introduces its own failure modes. The grader model can be wrong, inconsistent, or biased toward longer answers. You also pay for the extra calls. Use model-graded scoring only after you have checked the grader against a few human-labeled examples. The Real Python tutorial discusses evaluation approaches and their tradeoffs.

3. Store a baseline. Run the harness once on your current prompt and save the scores to a file. That file is your baseline. When you change the prompt, run the harness again and compare. A simple rule: if the average score drops by more than a small threshold, fail. You can also fail if any single input's score drops below a minimum. The threshold is a judgment call. Start with a small threshold, like 5%, so you catch small regressions. Loosen it later if you get false alarms.

4. Add the gate. Make the script exit with code 1 when the comparison fails. Then run it before every prompt change, either locally or in CI (continuous integration). The script below reads inputs, calls a mock scoring function, compares to a baseline, and exits non-zero on regression. It includes a mix of passing and failing mock outputs so you can watch the gate actually fire.

🟨JavaScript
// eval-harness.js
// Run with: node eval-harness.js
// Uses only Node.js built-ins (fs/promises).

import { readFile, writeFile } from 'fs/promises';

const INPUTS_PATH = './eval-inputs.json';
const BASELINE_PATH = './eval-baseline.json';
const THRESHOLD = 0.05; // fail if average score drops by more than 5%

async function loadJson(path) {
  try {
    const raw = await readFile(path, 'utf8');
    return JSON.parse(raw);
  } catch (err) {
    if (err.code === 'ENOENT') return null;
    throw err;
  }
}

// Mock scoring: replace with your real scoring logic.
// Here we score 1 if the output contains the expected keyword, else 0.
async function scoreOutput(input, output) {
  return output.includes(input.expectedKeyword) ? 1 : 0;
}

async function runEval() {
  const inputs = await loadJson(INPUTS_PATH);
  if (!inputs) throw new Error(`Missing ${INPUTS_PATH}`);

  const scores = [];
  for (const item of inputs) {
    // Replace with a real model call. The mock below returns a mix of
    // passing and failing outputs so the gate path is exercised.
    const output = item.mockOutput ?? item.expectedKeyword;
    const score = await scoreOutput(item, output);
    scores.push({ id: item.id, score });
  }

  const average = scores.reduce((sum, s) => sum + s.score, 0) / scores.length;
  return { scores, average };
}

async function main() {
  const result = await runEval();
  const baseline = await loadJson(BASELINE_PATH);

  if (!baseline) {
    await writeFile(BASELINE_PATH, JSON.stringify(result, null, 2));
    console.log('Baseline saved. Run again after a prompt change.');
    return;
  }

  const drop = baseline.average - result.average;
  console.log(`Baseline average: ${baseline.average.toFixed(3)}`);
  console.log(`Current average:  ${result.average.toFixed(3)}`);

  if (drop > THRESHOLD) {
    console.error(`Regression detected: average dropped by ${drop.toFixed(3)}`);
    process.exit(1);
  }

  console.log('No regression detected.');
}

main().catch((err) => {
  console.error('Eval failed:', err.message);
  process.exit(1);
});

To see the gate fire, create eval-inputs.json with a few items. Give some of them a mockOutput that omits the expected keyword. Run the script once to save a baseline. Then edit an input so its mockOutput fails, and run again. The average drops and the script exits with code 1.

JSON
[
  { "id": "refund", "expectedKeyword": "refund", "mockOutput": "You can request a refund." },
  { "id": "shipping", "expectedKeyword": "shipping", "mockOutput": "Shipping takes 3 days." },
  { "id": "status", "expectedKeyword": "status", "mockOutput": "I cannot help with that." }
]

This example uses a mock model call so you can run it without an API key. In practice, replace the mock with a call to your model provider. Keep the scoring function separate so you can swap it later.

Failure modes to watch

  • Overfitting to the eval set. If you tune the prompt until the eval passes, you may just be memorizing the inputs. Rotate in new inputs occasionally.
  • Scoring the wrong thing. A score that does not match what users care about gives false confidence. Start with a few human-labeled examples to check your scorer.
  • Ignoring variance. LLM outputs vary between runs. A single run can look better or worse by chance. For critical features, run each input a few times and compare averages. Real Python discusses how stochastic variation makes it hard to distinguish real improvement.
  • Model-graded scoring drift. If you use a model as a grader, its behavior can change when the provider updates the model. Pin the grader model version if you can.

What not to do

Do not build a large harness before you have a working feature. Start with a handful of inputs and one scoring function. Do not treat the eval as a one-time task. It is a gate you run repeatedly. And do not assume a passing eval means the feature is correct. It means the feature did not regress on the inputs you chose.

For more on testing non-deterministic systems, see The test passed. You still don't know what happened. and Testing What Your LLM Agent Actually Did in CI.

Further reading

Sources

Share

About the Author

Comments (0)

Loading comments...