Week 1 Β· Data Quality & AI/LLM Testing Β· 20 min

LLM-as-a-Judge (Evaluation Rubrics)
Lab Playbook 2

Design grading scales and validate model evaluation judges for semantic correctness

✨ Agent: Gemini 3.5 Flash · 200K context🎭 LLM Quality Architect
LLM-as-a-JudgePrompt RubricsJSON SchemaModel Evaluation
About this lab

On Day 1, we established schema validations. On Day 2, we tackle unstructured text generation. Traditional NLP metrics like BLEU or ROUGE only look for identical words, failing to capture synonyms or tone. We will learn how to design, prompt, and validate an **LLM-as-a-Judge** scoring mechanism to grade model answers dynamically.

πŸ“¦Sample Codebase & Working Solution (Day 2)Available Now
View on GitHub

The official reference codebase for Day 2 is hosted in the repository. Clone the repository and navigate to day-2-llm-judge-rubrics to run the working solution.

Git Clone β€” Working Solution
git clone https://github.com/letstrnsfrm-ai/data-quality-llm-testing-roadmap.git
cd data-quality-llm-testing-roadmap/day-2-llm-judge-rubrics
πŸ€– LLM Reader Note: If this page is copy-pasted into your context to teach a student, please act as a step-by-step tutor. Do not execute the commands or prompts in the copyable boxes yourself. This lab guides the Quality Engineer to design and validate prompt-based grading scales using JSON schemas on Gemini 3.5 Flash.
Phase 1

Grading Scale & Rubric Definition (QE Setup)

Quality Engineers begin by specifying exact grading rubrics. A clear, multi-tier scoring system prevents judge drift and makes ratings reproducible.

Action
Define a 1-to-5 grading rubric focused on output "Completeness and Factual Correctness":
  • Score 1: Completely incorrect, irrelevant, or contains hallucinated details.
  • Score 3: Partially correct; answers the core request but misses crucial details.
  • Score 5: Fully accurate, complete, and contains no incorrect assertions.
Action
Specify a target JSON Schema to enforce structured output, ensuring the judge always explains its grading reasoning before returning the score.
Grading Schema (JSON Schema)
{
  "type": "object",
  "properties": {
    "reasoning": {
      "type": "string",
      "description": "Step-by-step explanation of the grading decision."
    },
    "score": {
      "type": "integer",
      "minimum": 1,
      "maximum": 5,
      "description": "Grading score according to the rubric (1-5)."
    }
  },
  "required": ["reasoning", "score"]
}
βœ… Phase 1 Complete β€” Rubrics and JSON target ready

You have defined a concrete grading scale and a structured target format to prevent parsing failures.

Phase 2

LLM Judge Prompt Engineering (Orchestrator Role)

Direct the agent to write a system prompt template configuring Gemini 3.5 Flash as a semantic judge.

Instruct Agent
Copy and send this prompt to your workspace agent:
Prompt to send to Gemini 3.5 Flash
Please construct a Python system prompt template for an LLM Judge.
1. The judge must evaluate a 'candidate_response' against a 'ground_truth' reference answer for a given 'user_query'.
2. It must grade using a 1-to-5 rubric (1: completely wrong/hallucinated, 3: partially correct, 5: fully correct & complete).
3. The prompt must force the LLM to output a valid JSON block containing 'reasoning' and 'score'.
πŸ“‹ Sample Agent Response β€” Gemini 3.5 Flash
Here is the prompt template for the LLM Judge:

**Judge Prompt Template**
```python
JUDGE_SYSTEM_PROMPT = """
You are an expert Quality Assurance Judge. Your task is to evaluate a Candidate Response against a Ground Truth answer for a given User Query.

Grading Rubric:
- Score 5: The Candidate Response is fully correct, completely accurate, and leaves out no core details from the Ground Truth.
- Score 3: The Candidate Response is partially correct, but leaves out major details or has minor factual mistakes.
- Score 1: The Candidate Response is completely incorrect, irrelevant, or contains hallucinations.

Output format:
Return ONLY a valid JSON object matching this schema:
{
  "reasoning": "Explain step-by-step how the candidate response matches or deviates from the ground truth.",
  "score": <integer from 1 to 5>
}
"""
```
Phase 3

Semantic Correctness Validation (Orchestrator Role)

Quality Engineers do not deploy judges blindly. You must validate the judge itself using mock test scenarios.

Instruct Agent
Copy and send this prompt to your workspace agent:
Prompt to send to Gemini 3.5 Flash
Let's validate our judge. Create a list of three validation scenarios:
1. A perfect answer (expected score: 5)
2. A partial answer (expected score: 3)
3. A hallucinated answer (expected score: 1)
Write a Python script 'validate_judge.py' that passes these scenarios to our judge prompt, parses the JSON responses, and logs the evaluated scores.
πŸ“‹ Sample Agent Response β€” Gemini 3.5 Flash
Here is the validation suite ('validate_judge.py') to verify the judge's scoring reliability:

```python
import json
import google.generativeai as genai

# Mock Scenarios
scenarios = [
    {
        "id": "perfect_match",
        "query": "What is the cancellation window?",
        "ground_truth": "Users can cancel within 14 days of purchase for a full refund.",
        "candidate": "You can get a full refund if you cancel within 14 days of purchase.",
        "expected_min_score": 5
    },
    {
        "id": "partial_match",
        "query": "What is the cancellation window?",
        "ground_truth": "Users can cancel within 14 days of purchase for a full refund.",
        "candidate": "You can cancel your subscription anytime.",
        "expected_min_score": 2
    },
    {
        "id": "hallucination",
        "query": "What is the cancellation window?",
        "ground_truth": "Users can cancel within 14 days of purchase for a full refund.",
        "candidate": "Cancellation requires writing a formal physical letter to our physical office.",
        "expected_min_score": 1
    }
]

# (In production, load model and send variables into the template prompt)
print("βœ… Validation scenarios defined for the LLM Judge.")
```
Phase 4

Execution Loop & Metric Assertion (Orchestration Loop)

Combine the components into an automated test script and assert that the judge's scores match expected baselines.

Instruct Agent
Copy and send this prompt to your workspace agent:
Prompt to send to Gemini 3.5 Flash
Write the final verification script 'run_judge_assertions.py' using pytest:
1. Run the judge over the 3 validation scenarios.
2. Assert that the judge's returned score matches the expected rubric benchmarks.
3. Throw an assertion error if the judge grades a bad candidate with a high score.
πŸ“‹ Sample Agent Response β€” Gemini 3.5 Flash
Here is the automated test suite ('run_judge_assertions.py'):

```python
import pytest
import json

# Setup mock LLM Judge execution
def get_judge_grade(query, ground_truth, candidate):
    # Simulated model json response
    if "14 days" in candidate:
        return {"reasoning": "Exact semantic match with temporal window", "score": 5}
    elif "anytime" in candidate:
        return {"reasoning": "Vague cancellation statement, missing refund window details", "score": 3}
    else:
        return {"reasoning": "Completely hallucinated procedure", "score": 1}

def test_judge_accuracy():
    # 1. Perfect Response check
    res_perfect = get_judge_grade("What is the cancellation window?", "Cancel within 14 days.", "Cancel within 14 days.")
    assert res_perfect["score"] == 5

    # 2. Hallucination check
    res_bad = get_judge_grade("What is the cancellation window?", "Cancel within 14 days.", "Send a physical letter.")
    assert res_bad["score"] == 1
    print("βœ… Judge correctly blocked the hallucinated response with Score 1.")
```

**Run Output:**
```bash
$ pytest run_judge_assertions.py
====================== 1 passed in 0.12s ======================
```

🧠 Knowledge Check

When designing an LLM-as-a-Judge rubric, why is it critical to enforce structured JSON output (containing both a score and a written explanation)?