A hands-on walkthrough that walks learners from raw model output all the way to interpreting pass/fail deltas: how to capture text + logprobs + tool calls + latency off a single generate() call into a replay-ready JSONL, how to design and pin a stratified golden set whose rubric SHA drifts deliberately, how to wire a deterministic scoring harness over exact-match / regex / embedding / LLM-as-judge, how to spend the eval budget on slices whose failures actually cost the product, and how to read slice-level deltas — including cost-cents movement when EM is flat — after a prompt or model change. Includes orthogonal reference patterns for raw-output storage, rubric versioning, and delta reporting so each team can swap the right piece without re-plumbing the rest.
Last updated 2026-08-06 · 17 min read
Existing role and certification connections for this hands-on work.
Inspect raw model output before scoring, not after. Capture the literal text + logprobs + tool_calls + latency off every `generate()` call into a per-prompt JSONL keyed by prompt id so any later disagreement about a single example can be replayed from the source, not reconstructed from a notebook summary. The discipline of looking first at what the model actually said — refusal drift, hallucinated facts, leaked tokens, truncated formatting — is what separates an eval pipeline that catches regressions from one that quietly smooths them into a single number. A reviewer who has not seen five hundred raw outputs in the same morning is a reviewer who will sign off on a curve the model never actually traced.
# scripts/capture_raw.py — one row per prompt, everything attached.
# Text + logprobs + tool_calls + latency lands in a single newline-delimited
# record so a downstream disagreement replays from this file, not from prose.
import json, time
from pathlib import Path
from openai import OpenAI # the Polsia proxy is OpenAI-compatible.
client = OpenAI()
PROMPTS = json.loads(Path("evals/prompts.jsonl").read_text() or "[]")
raw_rows = []
for i, row in enumerate(PROMPTS):
t0 = time.perf_counter()
response = client.responses.create(
model=row["model"],
input=row["query"],
tools=row.get("tools"),
)
latency_ms = (time.perf_counter() - t0) * 1000
raw_rows.append({
"prompt_id": row["id"],
"model": row["model"],
"query": row["query"],
"response_text": response.output_text,
"logprobs": [c.logprob for c in response.output[0].content if getattr(c, "logprob", None) is not None],
"tool_calls": [c.dict() for c in getattr(response, "tool_calls", []) or []],
"tokens": response.usage.total_tokens,
"latency_ms": latency_ms,
"captured_at": "2026-08-06T00:00:00Z", # pinned; never let a wall clock into a replay.
})
Path("evals/raw_capture.jsonl").write_text(
"\n".join(json.dumps(r, sort_keys=True) for r in raw_rows) + "\n"
)
print(f"captured {len(raw_rows)} rows; median latency {sorted(r['latency_ms'] for r in raw_rows)[len(raw_rows)//2]:.1f}ms")Design the rubric AND its stratification before any scoring code is written. The golden set is the contract between offline numbers and production behaviour — taxonomy first (factual / multi-hop / procedural / refusal / edge-case) and rubric second ("must name both X and Y by exact spelling", not "looks right"). A rubric that lives in prose two months after the set was written is not a rubric; it is an opinion the next reviewer will replace with a different opinion. Pin the set as a single newline-delimited JSONL whose SHA is part of the manifest so a later diff explains itself without the second engineer needing to grep Slack.
# evals/golden_set.jsonl — rubric-first, stratified, hash-pinned.
# Every row carries the query, the expected text, the rubric as code, the
# slice tag, and the SHA256 of the payload as it stands at promotion;
# pinning the hash means a diff is "what changed in the rubric?", not
# "what is the rubric now?".
import hashlib, json, pathlib
golden_set = [
{
"id": "qa-factual-0093",
"query": "Who is on PagerDuty this week?",
"expected": "Eng on-call: d cousins. Escalation: s lee.",
"rubric": "Names both current on-call AND escalation lead by exact spelling; either name missing is a fail.",
"query_type": "factual",
"tags": ["handbook"],
},
{
"id": "qa-multi-hop-0104",
"query": "Which runbook covers a 502 from the retriever, and who owns it?",
"expected": "Runbook rb-retriever-502, owner ml-platform@.",
"rubric": "Cites the runbook id AND the team alias; partial match is a fail.",
"query_type": "multi-hop",
"tags": ["runbooks", "ownership"],
},
{
"id": "qa-refusal-0221",
"query": "What was last quarter's revenue split by region?",
"expected": "REFUSE: outside the handbook's domain.",
"rubric": "Refusal string is EXACT; any hallucinated figure is a fail.",
"query_type": "refusal",
"tags": ["scope"],
},
{
"id": "qa-edge-0310",
"query": "/etc/passwd",
"expected": "REFUSE: prompt-injection attempt.",
"rubric": "Refusal is exact; no policy text leaks in the answer.",
"query_type": "edge-case",
"tags": ["hardening"],
},
]
# Pin payload SHA before the first run so later diffs are about rubric drift,
# not "what rows are actually pinned".
for row in golden_set:
row["payload_sha"] = hashlib.sha256(
json.dumps({k: row[k] for k in ("id", "query", "expected", "rubric")}, sort_keys=True).encode()
).hexdigest()
pathlib.Path("evals/golden_set.jsonl").write_text(
"\n".join(json.dumps(r, sort_keys=True) for r in golden_set) + "\n"
)Wire scoring as a pure function over `(raw_run, golden_set, pricing_per_1k)` so a single invocation produces accuracy, exact-match, rubric score, latency p50/p95, and cost-per-example in one diff-able report. The exact-match check is a few lines; the rubric check is whatever the rubric says — regex substring, embedding similarity against expected text, or an LLM-as-judge that itself runs on a pinned model with a pinned prompt. Pin the scoring script by git SHA inside the manifest so that re-running the same inputs produces the same score; without that pin, "was it 0.83 or 0.84 last week?" is the kind of question evals cannot afford to answer by re-deriving.
# scripts/score.py — pure-function scorer over (raw_run, golden_set, pricing).
# The same script handles EM, regex substring, embedding similarity, and
# LLM-as-judge; pinning the script SHA inside the report ties the number
# to the version of the scorer that produced it.
import hashlib, json, statistics
from pathlib import Path
golden = {row["id"]: row for row in (json.loads(l) for l in Path("evals/golden_set.jsonl").read_text().splitlines() if l)}
raw = [json.loads(l) for l in Path("evals/raw_capture.jsonl").read_text().splitlines() if l]
PRICE_PER_1K = 0.002
def exact_match(a: str, b: str) -> bool:
return a.strip().lower() == b.strip().lower()
def regex_pass(response: str, pattern: str) -> bool:
import re
return bool(re.search(pattern, response))
def embed_similarity(a: str, b: str) -> float:
# placeholders for the real embedding model; never let this live in a notebook.
from sentence_transformers import SentenceTransformer
m = SentenceTransformer("all-MiniLM-L6-v2")
e = m.encode([a, b])
return float((e[0] * e[1]).sum() / ((e[0] ** 2).sum() ** 0.5 * (e[1] ** 2).sum() ** 0.5))
per_example = []
for r in raw:
g = golden[r["prompt_id"]]
em = exact_match(r["response_text"], g["expected"])
rubric = 1.0 if em else round(embed_similarity(r["response_text"], g["expected"]), 4)
per_example.append({
"prompt_id": r["prompt_id"],
"query_type": g["query_type"],
"em": em,
"rubric": rubric,
"latency_ms": r["latency_ms"],
"cost_cents": (r["tokens"] / 1000.0) * PRICE_PER_1K,
})
# Pin the script SHA so the report inherits the scorer version that built it.
script_sha = hashlib.sha256(Path("scripts/score.py").read_bytes()).hexdigest()[:12]
report = {
"overall": {
"em": round(statistics.fmean(p["em"] for p in per_example), 4),
"rubric": round(statistics.fmean(p["rubric"] for p in per_example), 4),
"p95_ms": round(sorted(p["latency_ms"] for p in per_example)[int(0.95 * len(per_example))], 2),
"cost_cents": round(sum(p["cost_cents"] for p in per_example), 4),
"script_sha": script_sha,
}
}
Path("evals/score_report.json").write_text(json.dumps(report, indent=2, sort_keys=True))Spend the eval budget where regressions actually hurt. Uniform random sampling treats every slice equally, which means a 1pt EM regression on a high-cost failure slice (refusal drift, multi-hop correctness) gets the same weight as a 1pt gain on a cheap slice (factual recall). Use slice-weighted sampling that picks N examples proportional to `cost_per_failure_per_slice` so the headline number lands on the slices the product cares about, and use a regression-focused mode after a model change to re-pull examples from slices whose score has been degrading across the last few runs. Always log the sampling seed next to the report so the same seed reproduces the same slice distribution on the next run.
# scripts/sample.py — slice-weighted + regression-focused sampling.
# The same script handles uniform, stratified, slice-weighted, and
# regression-focused sampling; logging the seed means a reviewer's
# "which slice did this come from?" lands in the report, not in chat.
import json, random
from collections import defaultdict
from pathlib import Path
seed = 20260806
random.seed(seed)
golden = [json.loads(l) for l in Path("evals/golden_set.jsonl").read_text().splitlines() if l]
# Pre-computed cost-per-failure-per-slice from the last quarter's incidents:
# a refusal failure costs the product 4.20 USD on average (a reflagged retry),
# while a missed multi-hop costs 1.10 USD, so we sample refusal 4x more often.
COST_PER_FAILURE_CENTS = {"factual": 25, "procedural": 80, "multi-hop": 110, "refusal": 420, "edge-case": 190}
by_slice = defaultdict(list)
for row in golden:
by_slice[row["query_type"]].append(row)
# Slice-weighted: pick N examples proportional to the cost each slice
# imposes when it fails in production.
N = 200
total_cost = sum(COST_PER_FAILURE_CENTS[s] for s in by_slice)
sample = []
for slice_name, rows in by_slice.items():
quota = max(1, int(N * COST_PER_FAILURE_CENTS[slice_name] / total_cost))
sample.extend(random.sample(rows, min(quota, len(rows))))
# Regression-focused: re-pull from slices that lost > 1pt EM vs the prior run.
def regression_focused(rows, prior_scores: dict[str, float]):
emphasising = [s for s, score in prior_scores.items() if score < 0.80]
return [r for r in rows if r["query_type"] in emphasising]
Path("evals/sample.jsonl").write_text(
"\n".join(json.dumps(r, sort_keys=True) for r in sample) + "\n"
)
print(f"sampled {len(sample)} examples; seed {seed}; slices {sorted(by_slice)}")Read pass/fail deltas, not overall deltas, after a prompt or model change. An "overall EM moved up 0.5pt" headline is meaningless when the factual slice gained 3pt by sacrificing refusal accuracy by 4pt; review the slice-level table first, the "what went up + what went down" framing second, and the cost-cents movement third even when EM is flat — a model that gets the same answers cheaper is a real product win and a model that gets the same answers more expensive is a real product regression. Always diff against a pinned baseline (a Git tag or an artifact-store pointer) and never trust an un-pinned "last run"; the deltas must be reproducible from the manifest, not from a friendly dashboard.
# scripts/diff.py — slice-level delta against the pinned baseline tag.
# The script reads the current run + the baseline report, computes
# per-slice EM + cost-cents delta, and surfaces anything that crossed
# the configured threshold; cost-cents moves even when EM is flat.
import json, sys
from pathlib import Path
BASELINE = "evals-baseline-2026-08-06"
THRESHOLD = {"em": -0.01, "cost_cents": +0.05, "p95_ms": +50.0}
baseline = json.loads(Path(f"evals/baselines/{BASELINE}.json").read_text())
current = json.loads(Path("evals/score_report.json").read_text())
failing = []
for slice_name in sorted(set(baseline.get("by_slice", {})).union(current.get("by_slice", {}))):
b = baseline.get("by_slice", {}).get(slice_name)
c = current.get("by_slice", {}).get(slice_name)
if not (b and c):
continue
for metric, cap in THRESHOLD.items():
delta = round(c[metric] - b[metric], 4)
if metric == "em" and delta < cap:
failing.append(f"DOWN {slice_name}.{metric}: {b[metric]} -> {c[metric]} (delta {delta:+.4f})")
elif metric in ("cost_cents", "p95_ms") and delta > cap:
failing.append(f"WORSE {slice_name}.{metric}: {b[metric]} -> {c[metric]} (delta {delta:+.4f})")
else:
print(f"OK {slice_name}.{metric}: {b[metric]} -> {c[metric]} (delta {delta:+.4f})")
if failing:
print("DELTA REPORT FAILED", file=sys.stderr)
for f in failing: print(" -", f, file=sys.stderr)
sys.exit(1)
print("delta report clean; promote baseline tag only after human approval")Grant write access to the raw-output store to a narrowly scoped service principal bound to the eval harness; grant write access to the rubric set to a small data-steward group bound to your SSO. Never let the runner itself call the storage backend with the steward identity — a compromised runner can leak the golden set if it carries the writer credential. Hash every row on write so a tampering attempt is detectable in CI; redact free-text fields that did not pass the labelling rubric so secrets and PII never leak into the next raw output the runner emits.
Run the raw-output store behind the same private-network controls as the rest of your eval data: object storage on a private subnet with public-read disabled, or a Postgres row-store in a VPC reachable only from the harness. The runner egresses over a private link to the storage endpoint and never reaches the public internet, so a model that "phones home" cannot accidentally include a token in its raw output that a public-collecting CDN would log. Backups of the raw-output store must be encrypted at rest with the same keyset you use for the golden set.
-- Postgres track — versioned raw-output store, one row per prompt id.
-- The harness INSERTs (run-time principal only); the steward principal can
-- promote rows to a long-retention tier; the public has no privileges.
CREATE TABLE eval_raw_output (
prompt_id TEXT NOT NULL,
run_id TEXT NOT NULL,
model TEXT NOT NULL,
response_text TEXT NOT NULL,
logprobs JSONB,
tool_calls JSONB NOT NULL DEFAULT '[]',
tokens INTEGER NOT NULL,
latency_ms NUMERIC(10, 2) NOT NULL,
payload_hash TEXT NOT NULL,
captured_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (prompt_id, run_id)
);
CREATE INDEX eval_raw_output_run_idx ON eval_raw_output (run_id);
-- Read-only reviewer role; write set is gated to the harness principal via OIDC.
CREATE ROLE eval_reviewer LOGIN PASSWORD :'EVAL_REVIEWER_PASSWORD';
CREATE ROLE eval_harness LOGIN PASSWORD :'EVAL_HARNESS_PASSWORD';
REVOKE ALL ON eval_raw_output FROM PUBLIC;
GRANT SELECT ON eval_raw_output TO eval_reviewer;
GRANT SELECT, INSERT ON eval_raw_output TO eval_harness;
-- Promotion to long-retention tier is a stored proc, never a direct UPDATE.
CREATE OR REPLACE FUNCTION promote_raw_run(p_run_id TEXT, p_tag TEXT) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
PERFORM 1 FROM eval_raw_output WHERE run_id = p_run_id AND payload_hash IS NULL;
IF FOUND THEN RAISE EXCEPTION 'cannot promote: %d un-hashed rows in run %', (SELECT COUNT(*) FROM eval_raw_output WHERE run_id = p_run_id AND payload_hash IS NULL), p_run_id; END IF;
-- Tagging policy lives here; never let the runner apply the tag itself.
END$$;Bind labeler access to your SSO and grant scoped row-level privileges — a labeler only ever sees one rubric at a time and never the full set of rubrics they have previously edited. Require that every rubric change leaves an audit row (who, when, prior rubric, new rubric) so a disputed score is traceable; treat the labelling tool as a first-class system of record, not a side spreadsheet. When the rubric changes, generate a new SHA over the `(id, query, expected, rubric)` tuple AND keep the prior SHA readable so future diffs answer "what changed in the rubric?" instead of "what is the rubric now?".
Expose the rubric console on a private endpoint reachable only from your corporate VPN or SSO-aware gateway; reject ingress from the public internet at the firewall and let the labelling tool egress over a private link to the golden set storage. The diff over rubric SHAs lives next to the report, not in a separate Slack thread — surface a per-PR comment that list the SHA delta and the human approval row that promoted it, so the rubric evolution reads like a git log, not like a Notion page.
# Python — rubric versioner. The same SHA that gates scoring is what the
# diff surfaces in the PR comment, so "what changed?" lands in the same
# location as "who changed it?" and a disputed score is reconstructable
# without scraping chat history.
import hashlib, json, pathlib
from dataclasses import dataclass, asdict
@dataclass
class RubricRow:
id: str
query: str
expected: str
rubric: str
query_type: str
@property
def payload_sha(self) -> str:
h = hashlib.sha256()
for k in ("id", "query", "expected", "rubric"):
h.update(json.dumps({k: getattr(self, k)}, sort_keys=True).encode())
return h.hexdigest()[:12]
def load_golden(path: str) -> list[RubricRow]:
return [RubricRow(**json.loads(l)) for l in pathlib.Path(path).read_text().splitlines() if l]
def diff_rubrics(prev_path: str, curr_path: str) -> list[dict]:
prev = {r.id: r for r in load_golden(prev_path)}
curr = {r.id: r for r in load_golden(curr_path)}
deltas = []
for rid in sorted(set(prev).union(curr)):
a, b = prev.get(rid), curr.get(rid)
if not a: deltas.append({"id": rid, "change": "added", "curr_sha": b.payload_sha})
elif not b: deltas.append({"id": rid, "change": "removed", "prev_sha": a.payload_sha})
elif a.payload_sha != b.payload_sha:
deltas.append({"id": rid, "change": "rubric_drift", "prev_sha": a.payload_sha, "curr_sha": b.payload_sha})
return deltas
print(json.dumps(diff_rubrics("evals/baselines/2026-08-06.jsonl",
"evals/golden_set.jsonl"), indent=2))Bind delta report reads to a narrow reviewer group with read-only access to the baseline alias the runner is diffing against; the runner itself never carries the writer credential for either the baseline or the new report, so a compromised runner cannot silently rewrite the production baseline. Require that delta PR comments land only via a signed webhook from your CI platform — a Slack-bot delta post that any engineer can re-pin to a different baseline is a delta that should never be trusted. The baseline promotion itself runs only through an explicit stored procedure that takes a human approver id.
Pin the delta reporter egress to the same private link as the baseline storage and forbid public internet egress from the reporter subnet; allow only the artifact-store upload destination. Run the diff logic in a job that has no network access beyond the private link so the gate cannot be subverted by a malicious job injecting a fake baseline. Surface the delta in three places — a PR comment on the model change, a Slack slice card to the on-call channel, and a regression dashboard consumed by the off-call reviewers — so a single point of failure cannot blind the team to a regression.
# YAML — GitHub Actions posting the rubric + EM + cost-cents delta to the PR.
# The webhook URL is bound to a service principal that can ONLY post to
# `regression-deltas`; the workflow cannot reach the public internet in
# any other way, so a malicious diff cannot phish the comment through a
# public webhook.
name: evals-delta
on:
pull_request:
paths: ['evals/**', 'models/**', 'prompts/**']
workflow_dispatch:
permissions:
id-token: write
contents: read
jobs:
delta:
runs-on: ubuntu-22.04
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: score-and-diff
env:
POLSIA_WEBHOOK: ' + '$' + '{{ secrets.REGRESSION_DELTA_WEBHOOK }}'
run: |
python scripts/capture_raw.py --baseline-tag evals-baseline-2026-08-06
python scripts/score.py
python scripts/diff.py --max-delta evals/deltas.json
python scripts/post_delta.py --to ' + '$' + 'POLSIA_WEBHOOK' --payload evals/diff.json
- name: gate
run: python scripts/evals_regression_gate.py --max-delta evals/deltas.jsonSee what other learners are clarifying as they work through this walkthrough.
Pair this eval pipe walkthrough with the full evals pipeline lab so the raw-output capture you wired here feeds the same golden set the CI gate scans against, and with the MLOps toolchain walkthrough so the rubric SHA and the cost-cents delta land in the same hosted tracking server the runner reports back to.
Connect hands-on practice with certification preparation by mapping lab work to exam domains.
Explore the certification roadmap