In this article, you will learn how to build a lightweight, reusable LLM evaluation harness in Python that combines exact-match scoring, an LLM-as-a-judge, and versioned regression tracking to catch prompt regressions.
Topics we will cover include:
- How to score deterministic tasks like ticket routing with a normalized exact-match scorer.
- How to grade open-ended responses with a rubric-based LLM-as-a-judge that returns structured Pydantic output.
- How to log each prompt version’s results and compare runs case by case to detect regressions that an overall pass rate can hide.

Introduction
When teams need to evaluate prompts passed to LLMs, they typically do so “by eye”: they run several examples in a playground environment while tweaking a system instruction, pick the one that looks better, and ship it. This might seem to work at first, but a tiny wording change can silently break a case that passed just a few days before.
The good news: we don’t need a heavy MLOps stack or observability platform to make this evaluation procedure more robust. This article will guide you through constructing, in under 150 lines of Python code, a reusable evaluation harness that combines multiple metrics:
- For deterministic tasks like entity extraction or classification, we use Exact-Match (EM) scoring.
- For open-ended response generation with varying wording, we consider rubric-based LLM-as-a-judge.
- To catch any
PASSthat flips toFAILin successive prompt versions, we will use versioned regression tracking.
Setup
The code example accompanying this article, which consists of a lightweight LLM evaluation harness, is ready to copy and run in a Python notebook environment, such as Colab. It runs on the Gemini API’s free tier, and it also includes a built-in “mock mode” that lets you test the harness without creating and using your own API key. Let’s start by installing some necessary packages:
|
1 2 |
# Installing dependencies !pip install -q google-genai pydantic |
Next, notice that we use USE_MOCK_LLM=True to run this code on the fly with simulated outputs. To run live calls to Gemini LLMs at no cost, get a free API key from Google AI Studio, add it as a new secret in Google Colab (the key icon in the left-hand menu) named GEMINI_API_KEY, and set USE_MOCK_LLM=False.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Setup client and model wrapper import json import os import re from datetime import datetime, timezone import pandas as pd from pydantic import BaseModel, Field pd.set_option("display.max_colwidth", None) # Set to False if you later add GEMINI_API_KEY to Colab Secrets USE_MOCK_LLM = True MODEL_NAME = "gemini-2.5-flash" client = None if not USE_MOCK_LLM: from google import genai from google.genai import types try: from google.colab import userdata api_key = userdata.get("GEMINI_API_KEY") except Exception: api_key = os.getenv("GEMINI_API_KEY") if not api_key: raise ValueError("Add GEMINI_API_KEY to Colab Secrets or set USE_MOCK_LLM = True.") client = genai.Client(api_key=api_key) |
LLM Evaluation Harness Step-by-Step
The first building block for our LLM evaluation harness is a wrapper function that decouples the overall harness from the model calls. The third argument, version_tag, indicates the specific version of a prompt or use case being tested via multiple model calls.
To make the code accessible and help readers understand the rationale of the evaluation framework, we will use, by default, a set of mock LLM outputs — for real, generated LLM outputs, you will need to use your own Gemini API key and perform model calls for inference, as stated earlier. My main purpose is to have you learn the key steps and elements to consider throughout the process of building the framework:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
def call_llm(system_prompt: str, user_input: str, version_tag: str = "v1") -> str: """Calls the target LLM (or returns deterministic mock outputs for free offline testing).""" if USE_MOCK_LLM: mock_outputs = { "v1_baseline": { "My invoice #4021 charged me twice this month.": "Category: BILLING.", "The mobile app crashes every time I tap 'Export PDF'.": "BUG_REPORT", "Cancel my plan immediately, I'm frustrated with the downtime.": ( "Sorry to hear that. You can cancel in Settings." ), "Can I switch from monthly to annual billing mid-cycle?": ( "Yes! Go to Billing > Plan to switch. We prorate your remaining days automatically." ), }, "v2_strict": { "My invoice #4021 charged me twice this month.": "BILLING", "The mobile app crashes every time I tap 'Export PDF'.": "BUG_REPORT", "Cancel my plan immediately, I'm frustrated with the downtime.": ( "I'm really sorry about the downtime. I can help you cancel right away—please " "confirm your account email, or go to Settings > Subscription > Cancel Plan." ), "Can I switch from monthly to annual billing mid-cycle?": ( "BILLING" # Simulated regression: strict label instruction bled into an open-ended reply ), }, } return mock_outputs.get(version_tag, {}).get(user_input, "UNKNOWN") response = client.models.generate_content( model=MODEL_NAME, contents=user_input, config=types.GenerateContentConfig( system_instruction=system_prompt, temperature=0.0, ), ) return response.text.strip() |
Importantly, setting temperature=0.0 helps keep the evaluation runs as deterministic as possible, avoiding noise between runs so that score changes reflect prompt edits instead of random sampling.
Next, to build a golden test dataset, we don’t really need hundreds or thousands of examples, as long as we have a few high-signal ones. Our set of examples mixes two types of tasks for a support assistant: ticket routing that requires an exact label (exact_match) and replies where facts and tone matter the most (rubric).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Defining the golden test dataset TEST_CASES = [ { "id": "tc_01_billing_route", "task_type": "exact_match", "input": "My invoice #4021 charged me twice this month.", "expected": "BILLING", }, { "id": "tc_02_bug_route", "task_type": "exact_match", "input": "The mobile app crashes every time I tap 'Export PDF'.", "expected": "BUG_REPORT", }, { "id": "tc_03_angry_cancel", "task_type": "rubric", "input": "Cancel my plan immediately, I'm frustrated with the downtime.", "expected": ( "1. Empathetically acknowledges the user's frustration about downtime. " "2. Gives clear next steps to cancel without being pushy or defensive." ), }, { "id": "tc_04_plan_switch", "task_type": "rubric", "input": "Can I switch from monthly to annual billing mid-cycle?", "expected": ( "1. Answers the question directly in full sentences. " "2. Mentions where to change the plan or how billing adjustment/proration works." ), }, ] |
Time to implement the first main pillar of the evaluation harness: a deterministic exact-match scorer. This is a cheap and fast approach aimed at catching outputs such as Category: BILLING.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Exact-match scorer def normalize_text(text: str) -> str: text = text.strip().upper() text = re.sub(r"[^\w\s]", "", text) return re.sub(r"\s+", " ", text) def score_exact_match(output: str, expected: str) -> dict: passed = normalize_text(output) == normalize_text(expected) return { "score": 5 if passed else 1, "passed": passed, "reasoning": "Exact match" if passed else f"Expected '{expected}', got '{output}'", } |
The exact-match scorer returns 5 or 1 to keep every scorer on the same 1-5 scale used by the rubric-based LLM judge we will add next, so no normalization logic is needed when we aggregate the scores of all metrics.
Meanwhile, instead of using string matching to assess open-ended answers, we will pass the user prompt, model response, and rubric to a judge model. This forces the judge to return JSON matching a Pydantic schema that includes a 1-5 score, a boolean flag indicating whether the test is passed, and a brief reasoning string. Having structured model outputs at this point is important, as it saves us from writing brittle parsers based on complex regular expressions:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# Rubric-based LLM-as-a-judge scorer class JudgeVerdict(BaseModel): score: int = Field(ge=1, le=5, description="Quality score from 1 (poor) to 5 (meets all rubric criteria)") passed: bool = Field(description="True if score is 4 or 5, False otherwise") reasoning: str = Field(description="One-sentence justification grounded in the rubric") JUDGE_PROMPT_TEMPLATE = """You are a strict QA evaluator. Grade the assistant's response against the rubric. USER INPUT: {user_input} ASSISTANT RESPONSE: {output} RUBRIC: {rubric} Scoring guide: - 5: Fully satisfies every rubric requirement. - 4: Satisfies requirements with minor wording flaws. - 3: Partially satisfies requirements; misses a key detail. - 1-2: Fails requirements, wrong format, or unhelpful. Set passed=true only if score is 4 or 5. """ def score_with_judge(user_input: str, output: str, rubric: str) -> dict: if USE_MOCK_LLM: # Simple deterministic simulation of a judge for mock mode if len(output.split()) < 3: return { "score": 1, "passed": False, "reasoning": "Output is just a bare label instead of a helpful answer.", } if "downtime" in rubric.lower() and "downtime" not in output.lower(): return { "score": 2, "passed": False, "reasoning": "Did not acknowledge the user's frustration about downtime.", } return { "score": 5, "passed": True, "reasoning": "Meets all rubric criteria clearly and concisely.", } prompt = JUDGE_PROMPT_TEMPLATE.format( user_input=user_input, output=output, rubric=rubric, ) response = client.models.generate_content( model=MODEL_NAME, contents=prompt, config=types.GenerateContentConfig( temperature=0.0, response_mime_type="application/json", response_schema=JudgeVerdict, ), ) verdict = JudgeVerdict.model_validate_json(response.text) return verdict.model_dump() |
Time to wire the scorers and the dataset into an overarching run_eval() function. At each run, the results are logged to a local file named eval_history.json, using the prompt version as the key. This output log acts as the regression ledger, but it could be replaced by a database if you migrate this approach to a production setting:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# Evaluation runner with local JSON history HISTORY_FILE = "eval_history.json" def run_eval(prompt_version: str, system_prompt: str, test_cases: list) -> pd.DataFrame: rows = [] for case in test_cases: output = call_llm(system_prompt, case["input"], version_tag=prompt_version) if case["task_type"] == "exact_match": result = score_exact_match(output, case["expected"]) else: result = score_with_judge(case["input"], output, case["expected"]) rows.append({ "id": case["id"], "task_type": case["task_type"], "output": output, "score": result["score"], "passed": result["passed"], "reasoning": result["reasoning"], }) df = pd.DataFrame(rows) pass_rate = df["passed"].mean() * 100 avg_score = df["score"].mean() # Load existing history and save this version snapshot history = {} if os.path.exists(HISTORY_FILE): with open(HISTORY_FILE, "r") as f: history = json.load(f) history[prompt_version] = { "timestamp": datetime.now(timezone.utc).isoformat(), "system_prompt": system_prompt, "pass_rate": round(pass_rate, 1), "avg_score": round(avg_score, 2), "results": rows, } with open(HISTORY_FILE, "w") as f: json.dump(history, f, indent=2) print(f"[{prompt_version}] Pass Rate: {pass_rate:.1f}% | Avg Score: {avg_score:.2f}/5.00") return df |
Now we start the real evaluation, using two prompt versions for the same scenario: the first, baseline version is a loose prompt, while the second version is stricter and also asks for empathy in one of its rules.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Run v1 and v2 prompts through the harness PROMPT_V1 = """You are a customer support assistant. If the user reports a bug or billing error, classify it as BUG_REPORT or BILLING. Otherwise, answer their question briefly.""" PROMPT_V2 = """You are a customer support assistant. Rule 1: For ticket routing (billing errors or bug reports), output ONLY the single label BILLING or BUG_REPORT with no extra words. Rule 2: For cancellations, acknowledge the user's frustration empathetically and provide clear steps. Rule 3: For general questions, answer clearly in full sentences.""" df_v1 = run_eval("v1_baseline", PROMPT_V1, TEST_CASES) display(df_v1[["id", "task_type", "score", "passed", "reasoning"]]) print("\n" + "-" * 60 + "\n") df_v2 = run_eval("v2_strict", PROMPT_V2, TEST_CASES) display(df_v2[["id", "task_type", "score", "passed", "reasoning"]]) |
Let’s see the evaluation results:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[v1_baseline] Pass Rate: 50.0% | Avg Score: 3.25/5.00 id task_type score passed reasoning 0 tc_01_billing_route exact_match 1 False Expected 'BILLING', got 'Category: BILLING.' 1 tc_02_bug_route exact_match 5 True Exact match 2 tc_03_angry_cancel rubric 2 False Did not acknowledge the user's frustration about downtime. 3 tc_04_plan_switch rubric 5 True Meets all rubric criteria clearly and concisely. ------------------------------------------------------------ [v2_strict] Pass Rate: 75.0% | Avg Score: 4.00/5.00 id task_type score passed reasoning 0 tc_01_billing_route exact_match 5 True Exact match 1 tc_02_bug_route exact_match 5 True Exact match 2 tc_03_angry_cancel rubric 5 True Meets all rubric criteria clearly and concisely. 3 tc_04_plan_switch rubric 1 False Output is just a bare label instead of a helpful answer. |
Although the code uses mocked examples to avoid API costs, the failure mode is a realistic one: tc_04_plan_switch returns a bare label in response to an open-ended billing question. This is a classic, easily identifiable bug in prompt engineering. Overall, a pass rate that increases from 50% to 75% might look like a good reason to celebrate.
Finally, we add the regression tracker: a function that compares two saved runs from the evaluation history log and explicitly flags status changes:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# Per-case regression tracker def compare_versions(base_version: str, new_version: str, history_file: str = HISTORY_FILE) -> pd.DataFrame: with open(history_file, "r") as f: history = json.load(f) base_run = history[base_version] new_run = history[new_version] base_df = pd.DataFrame(base_run["results"]).set_index("id") new_df = pd.DataFrame(new_run["results"]).set_index("id") comparison = [] for tc_id in base_df.index: b_pass = bool(base_df.loc[tc_id, "passed"]) n_pass = bool(new_df.loc[tc_id, "passed"]) b_score = int(base_df.loc[tc_id, "score"]) n_score = int(new_df.loc[tc_id, "score"]) if b_pass and not n_pass: status = "REGRESSION (PASS -> FAIL)" elif not b_pass and n_pass: status = "FIXED (FAIL -> PASS)" elif b_pass and n_pass: status = "STILL PASSING" else: status = "STILL FAILING" comparison.append({ "id": tc_id, "status": status, f"{base_version}_score": b_score, f"{new_version}_score": n_score, "score_delta": n_score - b_score, "new_reasoning": new_df.loc[tc_id, "reasoning"], }) diff_df = pd.DataFrame(comparison) pass_delta = new_run["pass_rate"] - base_run["pass_rate"] regressions = (diff_df["status"] == "REGRESSION (PASS -> FAIL)").sum() print(f"Comparison: {base_version} -> {new_version}") print(f"Pass Rate Delta: {pass_delta:+.1f}% ({base_run['pass_rate']}% -> {new_run['pass_rate']}%)") print(f"Regressions Detected: {regressions}\n") return diff_df diff_df = compare_versions("v1_baseline", "v2_strict") display(diff_df) |
Output:
|
1 2 3 4 5 6 7 8 9 10 |
Comparison: v1_baseline -> v2_strict Pass Rate Delta: +25.0% (50.0% -> 75.0%) Regressions Detected: 1 id status v1_baseline_score v2_strict_score score_delta new_reasoning 0 tc_01_billing_route FIXED (FAIL -> PASS) 1 5 4 Exact match 1 tc_02_bug_route STILL PASSING 5 5 0 Exact match 2 tc_03_angry_cancel FIXED (FAIL -> PASS) 2 5 3 Meets all rubric criteria clearly and concisely. 3 tc_04_plan_switch REGRESSION (PASS -> FAIL) 5 1 -4 Output is just a bare label instead of a helpful answer. |
At first glance, the second, stricter version looks like the winner, but the per-case analysis shows that this conclusion might be a mistake. Two examples flipped from failure to pass, and these are real wins. However, one case shows a score drop from 5 to 1, i.e. the stricter rule bled into an open-ended question about billing, causing the model to reply with a bare label where an actual answer was expected.
Next Steps
The lightweight LLM evaluation harness shown throughout this article is designed to be incrementally expanded into a production-ready workflow. Ways to do this include adding an automated CI gate — a checkpoint that runs the tests before updated prompt or model versions go live — turning real bugs into new test cases to ensure the same errors don’t quietly return, and tracking cost and speed to avoid paying twice as much for a marginal improvement.






No comments yet.