{"slug": "build-a-lightweight-llm-evaluation-harness-in-python", "title": "Build a Lightweight LLM Evaluation Harness in Python", "summary": "A tutorial demonstrates building a lightweight LLM evaluation harness in under 150 lines of Python that combines normalized exact-match scoring for deterministic tasks like ticket routing, rubric-based LLM-as-a-judge grading with structured Pydantic output for open-ended responses, and versioned regression tracking that compares runs case by case to catch prompt regressions an overall pass rate can hide. The harness runs on the Gemini API free tier using the gemini-2.5-flash model and includes a mock mode (USE_MOCK_LLM=True) so it can be tested without an API key. The approach targets teams that currently evaluate prompts by eye in a playground, where a small wording change can silently break a previously passing case.", "body_md": "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.\n\nTopics we will cover include:\n\n- How to score deterministic tasks like ticket routing with a normalized exact-match scorer.\n- How to grade open-ended responses with a rubric-based LLM-as-a-judge that returns structured Pydantic output.\n- How to log each prompt version’s results and compare runs case by case to detect regressions that an overall pass rate can hide.\n\n## Introduction\n\nWhen 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.\n\nThe 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:\n\n- For deterministic tasks like entity extraction or classification, we use **Exact-Match (EM) scoring** .\n- For open-ended response generation with varying wording, we consider **rubric-based LLM-as-a-judge** .\n- To catch any `PASS` that flips to`FAIL` in successive prompt versions, we will use**versioned regression tracking** .\n\n## Setup\n\nThe 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:\n\n```\n# Installing dependencies\n!pip install -q google-genai pydantic\n\n12\n\n# Installing dependencies!pip install -q google-genai pydantic\n```\n\nNext, 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`.\n\n``` python\n# Setup client and model wrapper\nimport json\nimport os\nimport re\nfrom datetime import datetime, timezone\nimport pandas as pd\nfrom pydantic import BaseModel, Field\n\npd.set_option(\"display.max_colwidth\", None)\n\n# Set to False if you later add GEMINI_API_KEY to Colab Secrets\nUSE_MOCK_LLM = True\nMODEL_NAME = \"gemini-2.5-flash\"\n\nclient = None\nif not USE_MOCK_LLM:\n    from google import genai\n    from google.genai import types\n\n    try:\n        from google.colab import userdata\n        api_key = userdata.get(\"GEMINI_API_KEY\")\n    except Exception:\n        api_key = os.getenv(\"GEMINI_API_KEY\")\n\n    if not api_key:\n        raise ValueError(\"Add GEMINI_API_KEY to Colab Secrets or set USE_MOCK_LLM = True.\")\n    client = genai.Client(api_key=api_key)\n\n12345678910111213141516171819202122232425262728\n\n# Setup client and model wrapperimport jsonimport osimport refrom datetime import datetime, timezoneimport pandas as pdfrom pydantic import BaseModel, Field pd.set_option(\"display.max_colwidth\", None) # Set to False if you later add GEMINI_API_KEY to Colab SecretsUSE_MOCK_LLM = TrueMODEL_NAME = \"gemini-2.5-flash\" client = Noneif 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)\n```\n\n## LLM Evaluation Harness Step-by-Step\n\nThe 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.\n\nTo 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:\n\n``` php\ndef call_llm(system_prompt: str, user_input: str, version_tag: str = \"v1\") -> str:\n    \"\"\"Calls the target LLM (or returns deterministic mock outputs for free offline testing).\"\"\"\n    if USE_MOCK_LLM:\n        mock_outputs = {\n            \"v1_baseline\": {\n                \"My invoice #4021 charged me twice this month.\": \"Category: BILLING.\",\n                \"The mobile app crashes every time I tap 'Export PDF'.\": \"BUG_REPORT\",\n                \"Cancel my plan immediately, I'm frustrated with the downtime.\": (\n                    \"Sorry to hear that. You can cancel in Settings.\"\n                ),\n                \"Can I switch from monthly to annual billing mid-cycle?\": (\n                    \"Yes! Go to Billing > Plan to switch. We prorate your remaining days automatically.\"\n                ),\n            },\n            \"v2_strict\": {\n                \"My invoice #4021 charged me twice this month.\": \"BILLING\",\n                \"The mobile app crashes every time I tap 'Export PDF'.\": \"BUG_REPORT\",\n                \"Cancel my plan immediately, I'm frustrated with the downtime.\": (\n                    \"I'm really sorry about the downtime. I can help you cancel right away—please \"\n                    \"confirm your account email, or go to Settings > Subscription > Cancel Plan.\"\n                ),\n                \"Can I switch from monthly to annual billing mid-cycle?\": (\n                    \"BILLING\"  # Simulated regression: strict label instruction bled into an open-ended reply\n                ),\n            },\n        }\n        return mock_outputs.get(version_tag, {}).get(user_input, \"UNKNOWN\")\n\n    response = client.models.generate_content(\n        model=MODEL_NAME,\n        contents=user_input,\n        config=types.GenerateContentConfig(\n            system_instruction=system_prompt,\n            temperature=0.0,\n        ),\n    )\n    return response.text.strip()\n\n12345678910111213141516171819202122232425262728293031323334353637\n\ndef 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()\n```\n\nImportantly, 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.\n\nNext, 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`).\n\n```\n# Defining the golden test dataset\nTEST_CASES = [\n    {\n        \"id\": \"tc_01_billing_route\",\n        \"task_type\": \"exact_match\",\n        \"input\": \"My invoice #4021 charged me twice this month.\",\n        \"expected\": \"BILLING\",\n    },\n    {\n        \"id\": \"tc_02_bug_route\",\n        \"task_type\": \"exact_match\",\n        \"input\": \"The mobile app crashes every time I tap 'Export PDF'.\",\n        \"expected\": \"BUG_REPORT\",\n    },\n    {\n        \"id\": \"tc_03_angry_cancel\",\n        \"task_type\": \"rubric\",\n        \"input\": \"Cancel my plan immediately, I'm frustrated with the downtime.\",\n        \"expected\": (\n            \"1. Empathetically acknowledges the user's frustration about downtime. \"\n            \"2. Gives clear next steps to cancel without being pushy or defensive.\"\n        ),\n    },\n    {\n        \"id\": \"tc_04_plan_switch\",\n        \"task_type\": \"rubric\",\n        \"input\": \"Can I switch from monthly to annual billing mid-cycle?\",\n        \"expected\": (\n            \"1. Answers the question directly in full sentences. \"\n            \"2. Mentions where to change the plan or how billing adjustment/proration works.\"\n        ),\n    },\n]\n\n123456789101112131415161718192021222324252627282930313233\n\n# Defining the golden test datasetTEST_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.\"        ),    },]\n```\n\nTime 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`.\n\n``` php\n# Exact-match scorer\ndef normalize_text(text: str) -> str:\n    text = text.strip().upper()\n    text = re.sub(r\"[^\\w\\s]\", \"\", text)\n    return re.sub(r\"\\s+\", \" \", text)\n\ndef score_exact_match(output: str, expected: str) -> dict:\n    passed = normalize_text(output) == normalize_text(expected)\n    return {\n        \"score\": 5 if passed else 1,\n        \"passed\": passed,\n        \"reasoning\": \"Exact match\" if passed else f\"Expected '{expected}', got '{output}'\",\n    }\n\n1234567891011121314\n\n# Exact-match scorerdef 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}'\",    }\n```\n\nThe 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.\n\nMeanwhile, 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:\n\n```\n# Rubric-based LLM-as-a-judge scorer\nclass JudgeVerdict(BaseModel):\n    score: int = Field(ge=1, le=5, description=\"Quality score from 1 (poor) to 5 (meets all rubric criteria)\")\n    passed: bool = Field(description=\"True if score is 4 or 5, False otherwise\")\n    reasoning: str = Field(description=\"One-sentence justification grounded in the rubric\")\n\nJUDGE_PROMPT_TEMPLATE = \"\"\"You are a strict QA evaluator. Grade the assistant's response against the rubric.\n\nUSER INPUT:\n{user_input}\n\nASSISTANT RESPONSE:\n{output}\n\nRUBRIC:\n{rubric}\n\nScoring guide:\n- 5: Fully satisfies every rubric requirement.\n- 4: Satisfies requirements with minor wording flaws.\n- 3: Partially satisfies requirements; misses a key detail.\n- 1-2: Fails requirements, wrong format, or unhelpful.\n\nSet passed=true only if score is 4 or 5.\n\"\"\"\n\ndef score_with_judge(user_input: str, output: str, rubric: str) -> dict:\n    if USE_MOCK_LLM:\n        # Simple deterministic simulation of a judge for mock mode\n        if len(output.split()) < 3:\n            return {\n                \"score\": 1,\n                \"passed\": False,\n                \"reasoning\": \"Output is just a bare label instead of a helpful answer.\",\n            }\n        if \"downtime\" in rubric.lower() and \"downtime\" not in output.lower():\n            return {\n                \"score\": 2,\n                \"passed\": False,\n                \"reasoning\": \"Did not acknowledge the user's frustration about downtime.\",\n            }\n        return {\n            \"score\": 5,\n            \"passed\": True,\n            \"reasoning\": \"Meets all rubric criteria clearly and concisely.\",\n        }\n\n    prompt = JUDGE_PROMPT_TEMPLATE.format(\n        user_input=user_input,\n        output=output,\n        rubric=rubric,\n    )\n    response = client.models.generate_content(\n        model=MODEL_NAME,\n        contents=prompt,\n        config=types.GenerateContentConfig(\n            temperature=0.0,\n            response_mime_type=\"application/json\",\n            response_schema=JudgeVerdict,\n        ),\n    )\n    verdict = JudgeVerdict.model_validate_json(response.text)\n    return verdict.model_dump()\n\n1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465\n\n# Rubric-based LLM-as-a-judge scorerclass 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()\n```\n\nTime 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:\n\n```\n# Evaluation runner with local JSON history\nHISTORY_FILE = \"eval_history.json\"\n\ndef run_eval(prompt_version: str, system_prompt: str, test_cases: list) -> pd.DataFrame:\n    rows = []\n\n    for case in test_cases:\n        output = call_llm(system_prompt, case[\"input\"], version_tag=prompt_version)\n\n        if case[\"task_type\"] == \"exact_match\":\n            result = score_exact_match(output, case[\"expected\"])\n        else:\n            result = score_with_judge(case[\"input\"], output, case[\"expected\"])\n\n        rows.append({\n            \"id\": case[\"id\"],\n            \"task_type\": case[\"task_type\"],\n            \"output\": output,\n            \"score\": result[\"score\"],\n            \"passed\": result[\"passed\"],\n            \"reasoning\": result[\"reasoning\"],\n        })\n\n    df = pd.DataFrame(rows)\n    pass_rate = df[\"passed\"].mean() * 100\n    avg_score = df[\"score\"].mean()\n\n    # Load existing history and save this version snapshot\n    history = {}\n    if os.path.exists(HISTORY_FILE):\n        with open(HISTORY_FILE, \"r\") as f:\n            history = json.load(f)\n\n    history[prompt_version] = {\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        \"system_prompt\": system_prompt,\n        \"pass_rate\": round(pass_rate, 1),\n        \"avg_score\": round(avg_score, 2),\n        \"results\": rows,\n    }\n\n    with open(HISTORY_FILE, \"w\") as f:\n        json.dump(history, f, indent=2)\n\n    print(f\"[{prompt_version}] Pass Rate: {pass_rate:.1f}% | Avg Score: {avg_score:.2f}/5.00\")\n    return df\n\n1234567891011121314151617181920212223242526272829303132333435363738394041424344454647\n\n# Evaluation runner with local JSON historyHISTORY_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\n```\n\nNow 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.\n\n```\n# Run v1 and v2 prompts through the harness\nPROMPT_V1 = \"\"\"You are a customer support assistant.\nIf the user reports a bug or billing error, classify it as BUG_REPORT or BILLING.\nOtherwise, answer their question briefly.\"\"\"\n\nPROMPT_V2 = \"\"\"You are a customer support assistant.\nRule 1: For ticket routing (billing errors or bug reports), output ONLY the single label BILLING or BUG_REPORT with no extra words.\nRule 2: For cancellations, acknowledge the user's frustration empathetically and provide clear steps.\nRule 3: For general questions, answer clearly in full sentences.\"\"\"\n\ndf_v1 = run_eval(\"v1_baseline\", PROMPT_V1, TEST_CASES)\ndisplay(df_v1[[\"id\", \"task_type\", \"score\", \"passed\", \"reasoning\"]])\n\nprint(\"\\n\" + \"-\" * 60 + \"\\n\")\n\ndf_v2 = run_eval(\"v2_strict\", PROMPT_V2, TEST_CASES)\ndisplay(df_v2[[\"id\", \"task_type\", \"score\", \"passed\", \"reasoning\"]])\n\n1234567891011121314151617\n\n# Run v1 and v2 prompts through the harnessPROMPT_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\"]])\n```\n\nLet’s see the evaluation results:\n\n```\n[v1_baseline] Pass Rate: 50.0% | Avg Score: 3.25/5.00\nid\ttask_type\tscore\tpassed\treasoning\n0\ttc_01_billing_route\texact_match\t1\tFalse\tExpected 'BILLING', got 'Category: BILLING.'\n1\ttc_02_bug_route\texact_match\t5\tTrue\tExact match\n2\ttc_03_angry_cancel\trubric\t2\tFalse\tDid not acknowledge the user's frustration about downtime.\n3\ttc_04_plan_switch\trubric\t5\tTrue\tMeets all rubric criteria clearly and concisely.\n\n------------------------------------------------------------\n\n[v2_strict] Pass Rate: 75.0% | Avg Score: 4.00/5.00\nid\ttask_type\tscore\tpassed\treasoning\n0\ttc_01_billing_route\texact_match\t5\tTrue\tExact match\n1\ttc_02_bug_route\texact_match\t5\tTrue\tExact match\n2\ttc_03_angry_cancel\trubric\t5\tTrue\tMeets all rubric criteria clearly and concisely.\n3\ttc_04_plan_switch\trubric\t1\tFalse\tOutput is just a bare label instead of a helpful answer.\n\n1234567891011121314151617\n\n[v1_baseline] Pass Rate: 50.0% | Avg Score: 3.25/5.00id\ttask_type\tscore\tpassed\treasoning0 tc_01_billing_route\texact_match 1 False Expected 'BILLING', got 'Category: BILLING.'1 tc_02_bug_route\texact_match 5 True Exact match2 tc_03_angry_cancel\trubric 2 False Did not acknowledge the user's frustration about downtime.3 tc_04_plan_switch\trubric 5 True Meets all rubric criteria clearly and concisely.  ------------------------------------------------------------ [v2_strict] Pass Rate: 75.0% | Avg Score: 4.00/5.00id\ttask_type\tscore\tpassed\treasoning0 tc_01_billing_route\texact_match 5 True Exact match1 tc_02_bug_route\texact_match 5 True Exact match2 tc_03_angry_cancel\trubric 5 True Meets all rubric criteria clearly and concisely.3 tc_04_plan_switch\trubric 1 False Output is just a bare label instead of a helpful answer.\n```\n\nAlthough 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.\n\nFinally, we add the regression tracker: a function that compares two saved runs from the evaluation history log and explicitly flags status changes:\n\n``` python\n# Per-case regression tracker\ndef compare_versions(base_version: str, new_version: str, history_file: str = HISTORY_FILE) -> pd.DataFrame:\n    with open(history_file, \"r\") as f:\n        history = json.load(f)\n\n    base_run = history[base_version]\n    new_run = history[new_version]\n\n    base_df = pd.DataFrame(base_run[\"results\"]).set_index(\"id\")\n    new_df = pd.DataFrame(new_run[\"results\"]).set_index(\"id\")\n\n    comparison = []\n    for tc_id in base_df.index:\n        b_pass = bool(base_df.loc[tc_id, \"passed\"])\n        n_pass = bool(new_df.loc[tc_id, \"passed\"])\n        b_score = int(base_df.loc[tc_id, \"score\"])\n        n_score = int(new_df.loc[tc_id, \"score\"])\n\n        if b_pass and not n_pass:\n            status = \"REGRESSION (PASS -> FAIL)\"\n        elif not b_pass and n_pass:\n            status = \"FIXED (FAIL -> PASS)\"\n        elif b_pass and n_pass:\n            status = \"STILL PASSING\"\n        else:\n            status = \"STILL FAILING\"\n\n        comparison.append({\n            \"id\": tc_id,\n            \"status\": status,\n            f\"{base_version}_score\": b_score,\n            f\"{new_version}_score\": n_score,\n            \"score_delta\": n_score - b_score,\n            \"new_reasoning\": new_df.loc[tc_id, \"reasoning\"],\n        })\n\n    diff_df = pd.DataFrame(comparison)\n    pass_delta = new_run[\"pass_rate\"] - base_run[\"pass_rate\"]\n    regressions = (diff_df[\"status\"] == \"REGRESSION (PASS -> FAIL)\").sum()\n\n    print(f\"Comparison: {base_version} -> {new_version}\")\n    print(f\"Pass Rate Delta: {pass_delta:+.1f}% ({base_run['pass_rate']}% -> {new_run['pass_rate']}%)\")\n    print(f\"Regressions Detected: {regressions}\\n\")\n\n    return diff_df\n\ndiff_df = compare_versions(\"v1_baseline\", \"v2_strict\")\ndisplay(diff_df)\n\n12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849\n\n# Per-case regression trackerdef 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)\n```\n\nOutput:\n\n``` php\nComparison: v1_baseline -> v2_strict\nPass Rate Delta: +25.0% (50.0% -> 75.0%)\nRegressions Detected: 1\n\nid\tstatus\tv1_baseline_score\tv2_strict_score\tscore_delta\tnew_reasoning\n0\ttc_01_billing_route\tFIXED (FAIL -> PASS)\t1\t5\t4\tExact match\n1\ttc_02_bug_route\tSTILL PASSING\t5\t5\t0\tExact match\n2\ttc_03_angry_cancel\tFIXED (FAIL -> PASS)\t2\t5\t3\tMeets all rubric criteria clearly and concisely.\n3\ttc_04_plan_switch\tREGRESSION (PASS -> FAIL)\t5\t1\t-4\tOutput is just a bare label instead of a helpful answer.\n\n12345678910\n\nComparison: v1_baseline -> v2_strictPass Rate Delta: +25.0% (50.0% -> 75.0%)Regressions Detected: 1 id\tstatus\tv1_baseline_score\tv2_strict_score\tscore_delta\tnew_reasoning0 tc_01_billing_route\tFIXED (FAIL -> PASS) 1 5 4 Exact match1 tc_02_bug_route\tSTILL PASSING 5 5 0 Exact match2 tc_03_angry_cancel\tFIXED (FAIL -> PASS) 2 5 3 Meets all rubric criteria clearly and concisely.3 tc_04_plan_switch\tREGRESSION (PASS -> FAIL) 5 1 -4 Output is just a bare label instead of a helpful answer.\n```\n\nAt 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.\n\n## Next Steps\n\nThe 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.", "url": "https://wpnews.pro/news/build-a-lightweight-llm-evaluation-harness-in-python", "canonical_source": "https://machinelearningmastery.com/build-a-lightweight-llm-evaluation-harness-in-python/", "published_at": "2026-12-02 11:00:00+00:00", "updated_at": "2026-12-02 13:16:36.476565+00:00", "lang": "en", "topics": ["large-language-models", "ai-tools", "developer-tools", "mlops"], "entities": ["Gemini API", "Google AI Studio", "Google Colab", "gemini-2.5-flash", "Pydantic", "Python"], "also_reported_by": [], "takeaway": "Combine normalized exact-match scoring for deterministic tasks, a rubric-based LLM-as-a-judge returning structured Pydantic output for open-ended responses, and case-by-case comparison across prompt versions to catch PASS-to-FAIL regressions that an overall pass rate hides.", "recommendation": {"advice": "Log each prompt version's per-case results and diff runs case by case instead of relying on aggregate pass rates, so a single PASS-to-FAIL flip after a wording change is caught before shipping.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/build-a-lightweight-llm-evaluation-harness-in-python", "markdown": "https://wpnews.pro/news/build-a-lightweight-llm-evaluation-harness-in-python.md", "text": "https://wpnews.pro/news/build-a-lightweight-llm-evaluation-harness-in-python.txt", "jsonld": "https://wpnews.pro/news/build-a-lightweight-llm-evaluation-harness-in-python.jsonld"}}