DEV Community

AI Spec Kit
AI Spec Kit

Posted on Originally published at aispeckit.substack.com

Your LLM Eval Rubric Is a Test Fixture: Score It and Check Grader Agreement in Python

Every LLM feature ends up answering "is this output good?" hundreds of times: in offline evals, in sampled production audits, and every time someone changes a prompt or swaps a model. If the answer depends on who's reading, your eval numbers measure the reviewer as much as the output. Hand that same vague question to an LLM judge and you've automated the noise.

A rubric fixes this, and the useful way to think about it as an engineer is as a test fixture: a fixed, versioned scoring spec that every candidate output gets run against. Like any fixture, it can be wrong. The difference is that a broken rubric doesn't throw an error; it just produces scores that two people can't reproduce. This post covers how to build a rubric that holds up, then gives you about 150 lines of standard-library Python that scores a batch of graded outputs, checks whether the graders actually agree, and turns it all into a GO / NO-GO.

About the numbers: the rubric, the weights, every grader score, and every threshold below are made-up example data for a fictional support-ticket summarizer. They're picked to make the checks easy to follow, not taken from any real product or study. Replace them with your own before you trust a GO.

Why a rubric, and not a thumbs-up?

Binary pass/fail is tempting because it's easy to collect. It's fine for narrow checks ("is the output valid JSON?"), but for anything involving judgment it hides two things you need: why an output is weak, and whether a change made things slightly better or slightly worse. A prompt tweak that turns a "barely acceptable" summary into a "good" one shows up as no change at all in a thumbs-up metric.

A rubric breaks "good" into a few separately scored dimensions, each with written anchors, combined by explicit weights, with a short list of critical failures that override everything. That gives you a number you can diff between runs and a breakdown that tells you where to look.

Anatomy of a rubric that holds up

Four parts. The script's DATA["rubric"] and DATA["critical_failures"] map one-to-one onto them.

1. Three to five dimensions

Derive them from what the user needs from the output, not from a generic list. Most dimensions come from five families: correctness (faithful to the source), completeness, relevance, format, and tone/safety. Three to five is the useful range: fewer and you lose diagnostic detail, more and graders slow down and dimensions start overlapping.

A cheap overlap test: if two dimensions get the same score on nearly every output, merge them. They're one assertion written twice.

2. Anchors that describe the output, not the grader's mood

"1 = poor, 5 = excellent" is the rubric equivalent of assert output_is_fine(). Anchors should describe observable features of the output, ideally countable ones, and be specific to the feature. Write 1, 3 and 5 first (easiest to tell apart), then define 2 and 4 as "in between" with one distinguishing detail each.

Here's the fictional summarizer rubric used throughout this post:

Dimension Weight 5 3 1
Faithfulness 40% Every statement supported by the thread One minor unsupported detail; agent would act the same Unsupported claim that would mislead the next agent
Completeness 30% Issue, steps tried, status and next step all present One of the four elements missing Two or more missing, or main issue missing
Concision 15% Short and to the point A bit wordy Far too long
Format 15% All four UI labels present and correct One label missing or mislabeled Unstructured paragraph the UI can't render

Look at Concision before reading on. It's deliberately bad, and the script is going to catch it.

3. Weights that encode the cost of failure

For a summarizer, a fabricated fact is worse than an extra sentence, so Faithfulness carries 40% and Concision 15%. Weights sum to 1.0 (the script refuses to run otherwise), and the overall score is the weighted average. Put the reason for each weight in a comment next to it; when someone challenges the rubric in six months, the reasoning is what they'll need.

Worked by hand, a summary scored Faithfulness 5, Completeness 3, Concision 3, Format 5 comes out to:

5*0.40 + 3*0.30 + 3*0.15 + 5*0.15 = 2.00 + 0.90 + 0.45 + 0.75 = 4.10
Enter fullscreen mode Exit fullscreen mode

That's grader A's score for item T02 in the sample data below.

4. Critical failures that short-circuit the score

Some outputs should fail no matter how they average out. A beautifully formatted summary that promises the customer a refund they never asked for is a fail. For the summarizer: an invented promise (refund, credit, timeline), payment card details in the output, or the wrong customer or account. In code terms these are hard assertions that run before the weighted score matters.

Keep the list short and unambiguous. If graders argue about whether something counts as critical, it belongs in a dimension's anchors instead.

Encode it in Python

Save this as rubric_score.py (standard library only, Python 3.8+). It embeds the fictional rubric and ten outputs, each scored independently by two graders, A and B. Pass a JSON file with the same shape to score your own:

# rubric_score.py -- score LLM outputs against a weighted rubric and check grader agreement.
# The rubric, scores and thresholds below are made-up example data for a fictional
# support-ticket summarizer. Pass a JSON file with the same shape to score your own.

import json
import sys
from collections import Counter

DATA = {
    "rubric": {
        "faithfulness": {"weight": 0.40, "anchors": {
            5: "every statement supported by the thread",
            3: "one minor unsupported detail; agent would act the same",
            1: "unsupported claim that would mislead the next agent"}},
        "completeness": {"weight": 0.30, "anchors": {
            5: "issue, steps tried, status and next step all present",
            3: "one of the four elements missing",
            1: "two or more missing, or main issue missing"}},
        "concision": {"weight": 0.15, "anchors": {
            5: "short and to the point",
            3: "a bit wordy",
            1: "far too long"}},
        "format": {"weight": 0.15, "anchors": {
            5: "all four UI labels present and correct",
            3: "one label missing or mislabeled",
            1: "unstructured paragraph the UI can't render"}},
    },
    "critical_failures": ["invented_promise", "card_details", "wrong_customer"],
    "thresholds": {"pass_score": 4.0, "dimension_floor": 3.5,
                   "min_kappa": 0.6, "min_within_one": 0.9},
    # Each output was scored independently by two graders (A and B), 1-5 per dimension.
    "outputs": [
        {"id": "T01", "A": [5, 5, 4, 5], "B": [5, 5, 5, 5], "critical": []},
        {"id": "T02", "A": [5, 3, 3, 5], "B": [5, 3, 5, 5], "critical": []},
        {"id": "T03", "A": [3, 5, 2, 5], "B": [3, 5, 4, 5], "critical": []},
        {"id": "T04", "A": [5, 4, 5, 3], "B": [5, 4, 3, 3], "critical": []},
        {"id": "T05", "A": [1, 3, 4, 5], "B": [1, 3, 4, 5], "critical": ["invented_promise"]},
        {"id": "T06", "A": [5, 5, 3, 5], "B": [5, 5, 3, 5], "critical": []},
        {"id": "T07", "A": [4, 3, 5, 1], "B": [4, 3, 2, 1], "critical": []},
        {"id": "T08", "A": [5, 5, 4, 5], "B": [5, 4, 2, 5], "critical": []},
        {"id": "T09", "A": [5, 4, 3, 5], "B": [5, 4, 5, 5], "critical": []},
        {"id": "T10", "A": [3, 3, 5, 3], "B": [3, 3, 3, 3], "critical": []},
    ],
}


def validate(data):
    rubric = data["rubric"]
    total = sum(d["weight"] for d in rubric.values())
    if abs(total - 1.0) > 1e-9:
        sys.exit(f"weights sum to {total:.2f}, expected 1.00")
    for o in data["outputs"]:
        for g in ("A", "B"):
            if len(o[g]) != len(rubric) or not all(1 <= s <= 5 for s in o[g]):
                sys.exit(f"{o['id']} grader {g}: need {len(rubric)} scores in 1-5")
        unknown = set(o["critical"]) - set(data["critical_failures"])
        if unknown:
            sys.exit(f"{o['id']}: unknown critical failure(s) {sorted(unknown)}")


def weighted(scores, weights):
    return sum(s * w for s, w in zip(scores, weights))


def cohen_kappa(a, b):
    """Unweighted Cohen's kappa for two graders' labels on the same items."""
    n = len(a)
    observed = sum(x == y for x, y in zip(a, b)) / n
    ca, cb = Counter(a), Counter(b)
    expected = sum(ca[k] * cb[k] for k in set(a) | set(b)) / (n * n)
    if expected == 1:
        return 1.0
    return (observed - expected) / (1 - expected)


def score_outputs(data):
    names = list(data["rubric"])
    weights = [data["rubric"][n]["weight"] for n in names]
    t = data["thresholds"]
    rows = []
    print(f"{'ID':<4} {'A':>5} {'B':>5} {'final':>6}  verdict")
    for o in data["outputs"]:
        a, b = weighted(o["A"], weights), weighted(o["B"], weights)
        final = (a + b) / 2
        if o["critical"]:
            verdict = "FAIL  critical: " + ", ".join(o["critical"])
        elif final >= t["pass_score"]:
            verdict = "PASS"
        else:
            verdict = f"FAIL  below {t['pass_score']:.1f}"
        rows.append((o, final, verdict.startswith("PASS")))
        print(f"{o['id']:<4} {a:>5.2f} {b:>5.2f} {final:>6.2f}  {verdict}")
    return names, rows


def dimension_report(data, names):
    t = data["thresholds"]
    outs = data["outputs"]
    floor_fails, vague = [], []
    print(f"\n{'dimension':<13} {'weight':>6} {'mean':>5} {'exact':>6} {'within1':>8} {'kappa':>6}  flag")
    for i, name in enumerate(names):
        a = [o["A"][i] for o in outs]
        b = [o["B"][i] for o in outs]
        mean = (sum(a) + sum(b)) / (2 * len(outs))
        exact = sum(x == y for x, y in zip(a, b)) / len(outs)
        within = sum(abs(x - y) <= 1 for x, y in zip(a, b)) / len(outs)
        kappa = cohen_kappa(a, b)
        flags = []
        if mean < t["dimension_floor"]:
            flags.append(f"mean < {t['dimension_floor']}")
            floor_fails.append(name)
        if kappa < t["min_kappa"] or within < t["min_within_one"]:
            flags.append("rewrite anchors")
            vague.append(name)
        print(f"{name:<13} {data['rubric'][name]['weight']:>6.0%} {mean:>5.2f} "
              f"{exact:>6.0%} {within:>8.0%} {kappa:>6.2f}  {'; '.join(flags) or 'ok'}")
    return floor_fails, vague


def main():
    data = DATA
    if len(sys.argv) > 1:
        with open(sys.argv[1], encoding="utf-8") as f:
            data = json.load(f)
    validate(data)
    names, rows = score_outputs(data)
    floor_fails, vague = dimension_report(data, names)

    t = data["thresholds"]
    avg = sum(final for _, final, _ in rows) / len(rows)
    passed = sum(ok for _, _, ok in rows)
    criticals = sum(bool(o["critical"]) for o, _, _ in rows)
    print(f"\n{passed}/{len(rows)} outputs pass | average {avg:.2f} | critical failures {criticals}")
    for name in vague:
        print(f"  anchors too vague to trust: {name} -> "
              f"{data['rubric'][name]['anchors']}")

    gates = [
        (f"average >= {t['pass_score']:.1f}", avg >= t["pass_score"]),
        (f"no dimension mean < {t['dimension_floor']}", not floor_fails),
        ("zero critical failures", criticals == 0),
        ("graders agree on every dimension", not vague),
    ]
    print()
    for label, ok in gates:
        print(f"{'PASS' if ok else 'FAIL'}  {label}")
    go = all(ok for _, ok in gates)
    print(f"\nLaunch decision -> {'GO' if go else 'NO-GO'}")
    return 0 if go else 1


if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

Run it against the embedded data:

$ python3 rubric_score.py
ID       A     B  final  verdict
T01   4.85  5.00   4.92  PASS
T02   4.10  4.40   4.25  PASS
T03   3.75  4.05   3.90  FAIL  below 4.0
T04   4.40  4.10   4.25  PASS
T05   2.65  2.65   2.65  FAIL  critical: invented_promise
T06   4.70  4.70   4.70  PASS
T07   3.40  2.95   3.17  FAIL  below 4.0
T08   4.85  4.25   4.55  PASS
T09   4.40  4.70   4.55  PASS
T10   3.30  3.00   3.15  FAIL  below 4.0

dimension     weight  mean  exact  within1  kappa  flag
faithfulness     40%  4.10   100%     100%   1.00  ok
completeness     30%  3.95    90%     100%   0.85  ok
concision        15%  3.70    20%      30%  -0.08  rewrite anchors
format           15%  4.20   100%     100%   1.00  ok

6/10 outputs pass | average 4.01 | critical failures 1
  anchors too vague to trust: concision -> {5: 'short and to the point', 3: 'a bit wordy', 1: 'far too long'}

PASS  average >= 4.0
PASS  no dimension mean < 3.5
FAIL  zero critical failures
FAIL  graders agree on every dimension

Launch decision -> NO-GO
Enter fullscreen mode Exit fullscreen mode

The script exits 1 on NO-GO, so it can gate a pipeline as-is.

Reading the output

The per-output table. Each row shows both graders' weighted scores and their mean. Four outputs fail: three on score, and T05 on a critical failure. T05 is the case that justifies having critical failures at all: its 2.65 would fail on score anyway here, but on a slightly better-written version of the same invented refund, the weighted average alone could have let it through.

The average gate passes, and that's the trap. The average is 4.01, just over the 4.0 bar. If the rubric only had a weighted score, this batch would ship. Two other gates stop it: one critical failure, and a dimension the graders can't agree on.

The agreement columns are the point of the exercise. For each dimension the script reports:

  • exact: share of outputs where A and B gave the identical score.
  • within1: share where they were at most one point apart.
  • kappa: Cohen's kappa, which is exact agreement corrected for the agreement you'd expect by chance given how often each grader uses each score. 1.0 is perfect agreement; 0 is no better than chance; below 0 is worse than chance.

Faithfulness, Completeness and Format look healthy. Concision does not: the graders matched on 2 of 10 outputs, were more than a point apart on 7 of them, and kappa is slightly negative. That's not a grader problem, it's an anchor problem. "Short and to the point," "a bit wordy" and "far too long" are three opinions, so each grader brought their own definition of short.

The 0.6 kappa and 90% within-one cutoffs in thresholds are example values for this post, not a standard. Pick yours deliberately and write down why, the same way you would a coverage threshold.

Fix the anchor, not the graders

When a dimension fails the agreement check, rewrite its anchors in countable terms and re-run the same items. For the fictional summarizer, something like this (the word counts are example numbers; use your UI's real limit):

Concision Before After
5 Short and to the point Under 80 words, no repeated facts, no filler sentence
3 A bit wordy 80-120 words, or one repeated fact, or one filler sentence
1 Far too long Over 120 words, or mostly restates the thread

Now two graders can check the same output and land on the same number, because the anchor tells them what to count. The loop is the same one you'd use for a flaky test: find the dimension with low agreement, look at the specific items where graders were more than a point apart, rewrite the anchor that caused it, and re-score. Twenty to thirty outputs spanning a range of quality is a reasonable size for this calibration pass; ten is only enough for a demo.

Two variations worth knowing about. Cohen's kappa treats a 4-vs-5 disagreement the same as a 1-vs-5; a weighted kappa gives partial credit for near-misses on an ordinal scale, which is why the script also prints within-one. And with more than two graders you'd reach for a multi-rater statistic instead. Either way, the statistic is a pointer to ambiguous anchors, not the goal itself.

Grader B can be an LLM judge

Once human graders agree, you'll want an LLM judge to score larger samples. The script doesn't care who grader B is. Put your best-calibrated human's scores in A, the judge's scores in B, and run it on the same items: the per-dimension kappa is now a direct measure of whether the judge applies your rubric the way your team does.

A few rules make judges more consistent and easier to audit:

  • Give the judge the full rubric: every anchor and the critical-failure list, verbatim. Generate the prompt from the same DATA["rubric"] dict so the two can't drift apart.
  • Score one dimension per call when you can afford it, instead of asking for everything at once.
  • Ask for a short reason before the score, and log it. When the judge and a human disagree, the reason tells you whether the anchor or the judge is at fault.
  • Re-run the agreement check after any judge model or prompt change. A judge swap is a dependency upgrade; treat it like one.

Keep humans on threshold-setting and on reviewing anything the judge flags as a critical failure.

Write the thresholds before the run

The thresholds block exists so the launch bar is committed before anyone sees the results. Moving the bar after a disappointing run is the eval equivalent of deleting a failing test. Typical gates (values here are illustrative):

  • weighted average at or above a target
  • no single dimension averaging below a floor
  • zero critical failures, at least in the high-risk slice of the test set
  • graders (or human vs. judge) agreeing on every dimension

If you score by slice (long threads, ambiguous threads, adversarial inputs), add a gate that no slice falls more than a set margin below the overall average. Averages hide the slice that's failing.

Version the rubric alongside the prompt and the golden set. Changing an anchor or a weight mid-comparison makes before-and-after scores meaningless, so bump a version and re-score the baseline instead.

What the script can't do

It can't tell you the dimensions are the right ones, that the weights reflect real user cost, or that a high-agreement rubric is measuring something that matters. Two graders can agree perfectly on a useless criterion. It takes the "can we even trust these scores?" question off the table so the review can spend its time on "are we scoring the right things?"

Checklist before you trust a rubric score

  • [ ] Three to five dimensions, derived from what users need
  • [ ] Anchors for at least 1, 3 and 5 on every dimension, in observable, countable terms
  • [ ] Weights sum to 1.0, with the reason for each written down
  • [ ] A short, unambiguous critical-failure list that overrides the score
  • [ ] Two graders scored the same 20-30 outputs independently
  • [ ] Every dimension clears your agreement bar; low-agreement anchors rewritten
  • [ ] LLM judge validated against human scores before it scores anything alone
  • [ ] Launch thresholds committed before the final run
  • [ ] Rubric versioned alongside the prompt and golden set

Skip writing the first ten rubrics

Writing anchors from scratch is the slow part. The LLM Eval Rubrics & Golden Dataset Pack ($19) has 10 rubrics for common LLM tasks (summarization, RAG Q&A, classification, extraction, support chat, code assist, rewriting and tone, agent task completion, content drafting, and safety), each with weighted dimensions, 1-5 anchors, critical failures and two scored examples. It also includes a Golden Dataset Builder spreadsheet with a rater-agreement tab and a GO/NO-GO check, plus nine LLM-as-judge prompts.

👉 Get the LLM Eval Rubrics & Golden Dataset Pack

Disclosure: we make and sell that pack. You don't need it for anything in this article. The script above will score outputs and check agreement on its own.

If you're still defining what the feature should do, the rubric's dimensions should come straight from the behavior table in your spec. The free AI Feature PRD Template has that table, every section heading, guidance prompts and a pre-filled failure-mode table.

👉 Get the free AI Feature PRD Template

A PM-focused version of this guide first appeared on the AI Spec Kit Substack.

Which dimension in your current rubric would fail an agreement check first? We'd bet on whatever your version of "concise" is, but we'd like to hear yours.


This article was written with the help of AI tools, then reviewed and edited before publishing.

Top comments (0)