Evals for Engineers: Template Pack

From the Evals From Zero series on falkster.com: https://falkster.com/blog/evals-for-engineers

Download

evals-for-engineers-pack.md8 KB1,044 wordsFree to use, no signup

From the Evals From Zero series on falkster.com: https://falkster.com/blog/evals-for-engineers

How to use this pack: Trace schema, dataset format, code graders, judge prompt, judge calibration script, pass^k helpers, CI workflow, and gate file. The code is a starting point: adapt names, paths, and thresholds, and measure thresholds from repeated runs on an unchanged branch.

Method credits: Hamel Husain and Shreya Shankar (error analysis, binary grading, judge validation), Anthropic Engineering (vocabulary, pass^k, capability and regression sets), Teresa Torres (the experiment loop). Templates and gates by Falk Gottlob.

1. Step 1: Log everything before you need it

Copy and adapt
{
  "trace_id": "tr_2026_11_25_8812",
  "timestamp": "2026-11-25T14:03:11Z",
  "app_version": "support-agent@4.12.0",
  "prompt_version": "refund-policy-v7",
  "model": "provider/model-name@2026-10",
  "user_segment": "enterprise",
  "input": {"message": "My mug arrived cracked, I want my money back", "account_id": "acct_hash_93f1"},
  "steps": [
    {"type": "retrieval", "query": "refund policy damaged item", "doc_ids": ["kb_412", "kb_077"]},
    {"type": "tool_call", "name": "lookup_order", "args": {"account_id": "acct_hash_93f1"}, "result_summary": "1 order, delivered 11-21"},
    {"type": "model_call", "tokens_in": 2140, "tokens_out": 162, "latency_ms": 1830}
  ],
  "output": "I'm sorry about the mug. Under our policy, damaged items get store credit...",
  "final_state": {"credit_issued": false, "ticket_status": "awaiting_customer"},
  "feedback": {"thumb": "down", "reason": "didnt_answer_question"},
  "pii_redacted": true
}

2. Step 2: Treat the dataset as code

Copy and adapt
{"id": "refund-001", "slice": "refund", "input": {"message": "My mug arrived cracked, I want my money back"}, "context": {"policy_doc": "kb_412"}, "checks": ["no_unsupported_promise", "order_ids_exist", "under_120_words"], "expected": {"credit_issued": false}, "label_source": "human:ana", "label_confirmed_by": "human:lee", "added": "2026-11-20", "origin": "trace:tr_2026_11_18_0412", "split": "regression"}
{"id": "refund-002", "slice": "refund", "input": {"message": "refund pls order 4471"}, "checks": ["order_ids_exist"], "expected": {"mentions_order": "4471"}, "label_source": "human:ana", "label_confirmed_by": null, "added": "2026-11-21", "origin": "complaint", "split": "capability"}

3. Step 3: Code graders first

Copy and adapt
import json
import re

def check_schema(output: str) -> tuple[bool, str]:
    """The reply must be valid JSON with the fields the front end needs."""
    try:
        data = json.loads(output)
    except json.JSONDecodeError as e:
        return False, f"not JSON: {e}"
    missing = {"answer", "sources"} - data.keys()
    return (not missing, f"missing fields: {sorted(missing)}" if missing else "ok")

def check_order_ids_exist(output: str, account_orders: set[str]) -> tuple[bool, str]:
    """Every order number in the reply must exist on the customer's account."""
    mentioned = set(re.findall(r"\b\d{4,6}\b", output))
    invented = mentioned - account_orders
    return (not invented, f"invented order ids: {sorted(invented)}" if invented else "ok")

def check_citations_resolve(sources: list[str], retrieved_ids: set[str]) -> tuple[bool, str]:
    """Every cited source must be one the system actually retrieved."""
    bad = [s for s in sources if s not in retrieved_ids]
    return (not bad, f"cites unretrieved docs: {bad}" if bad else "ok")

def check_tool_calls(steps: list[dict]) -> tuple[bool, str]:
    """The agent must look up the order before issuing any credit."""
    names = [s["name"] for s in steps if s["type"] == "tool_call"]
    if "issue_credit" in names and "lookup_order" not in names[: names.index("issue_credit")]:
        return False, "issued credit before looking up the order"
    return True, "ok"

def check_final_state(final_state: dict, expected: dict) -> tuple[bool, str]:
    """Grade the outcome: did the environment end up where it should?"""
    diffs = {k: (final_state.get(k), v) for k, v in expected.items() if final_state.get(k) != v}
    return (not diffs, f"state mismatch: {diffs}" if diffs else "ok")

4. Build it narrow

Copy and adapt
You are grading one property of an AI support reply. Grade only this property.

PROPERTY: Every factual claim in the reply is supported by the provided documents.
A claim is supported if a document states it or directly implies it.
Greetings, apologies, and offers to help are not factual claims.

DOCUMENTS:
<documents>
{retrieved_documents}
</documents>

REPLY:
<reply>
{reply}
</reply>

EXAMPLES OF THE BOUNDARY:
<examples>
{two_pass_and_two_fail_examples_from_the_train_split}
</examples>

Steps:
1. List each factual claim in the reply, one per line.
2. For each claim, quote the supporting sentence from the documents, or write NONE.
3. On the final line, write exactly one of:
VERDICT: PASS
VERDICT: FAIL

5. Calibrate it against people

Copy and adapt
import json

def calibrate(judge, labeled_path: str, split: str = "test") -> dict:
    """Compare judge verdicts with human labels on one split. Run once on 'test'."""
    tp = fn = tn = fp = 0
    misses, false_alarms = [], []
    for line in open(labeled_path):
        case = json.loads(line)
        if case["split"] != split:
            continue
        human_fail = case["human_label"] == "FAIL"
        judge_fail = judge(case) == "FAIL"
        if human_fail and judge_fail:
            tp += 1
        elif human_fail:
            fn += 1
            misses.append(case["id"])
        elif judge_fail:
            fp += 1
            false_alarms.append(case["id"])
        else:
            tn += 1
    return {
        "true_positive_rate": tp / max(tp + fn, 1),   # failures caught
        "true_negative_rate": tn / max(tn + fp, 1),   # good outputs passed
        "n_fail": tp + fn,
        "n_pass": tn + fp,
        "missed_failures": misses,
        "false_alarms": false_alarms,
    }

6. Step 5: Agents need their own rules

Copy and adapt
from math import comb

def pass_at_k(n: int, c: int, k: int) -> float:
    """Chance at least one of k samples passes, given c passes out of n trials."""
    if n - c < k:
        return 1.0
    return 1.0 - comb(n - c, k) / comb(n, k)

def pass_hat_k(n: int, c: int, k: int) -> float:
    """Chance all k samples pass, given c passes out of n trials (k <= n)."""
    return comb(c, k) / comb(n, k)

# Example: 10 trials, 8 passed
# pass_at_k(10, 8, 3)  -> 1.0
# pass_hat_k(10, 8, 3) -> about 0.47

7. Handle the randomness

Copy and adapt
# .github/workflows/evals.yml
name: evals
on:
  pull_request:
    paths: ["prompts/**", "src/agent/**", "evals/**", "config/models.yaml"]
  schedule:
    - cron: "17 6 * * *"   # nightly full suite

jobs:
  pr-gate:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - run: pip install -r evals/requirements.txt
      - name: Regression set, 3 samples per case, majority vote
        run: python evals/run.py --set evals/regression.jsonl --samples 3 --gate evals/gates.yaml --cache .evalcache
        env:
          MODEL_API_KEY: ${{ secrets.MODEL_API_KEY }}
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: eval-report
          path: evals/out/report.md

  nightly-full:
    if: github.event_name == 'schedule'
    runs-on: ubuntu-latest
    timeout-minutes: 90
    steps:
      - uses: actions/checkout@v4
      - run: pip install -r evals/requirements.txt
      - name: Regression + capability sets, 5 samples, pass^3, per-slice report
        run: python evals/run.py --set evals/regression.jsonl --set evals/capability.jsonl --samples 5 --pass-hat-k 3 --by-slice --report evals/out/nightly.md
        env:
          MODEL_API_KEY: ${{ secrets.MODEL_API_KEY }}

8. Handle the randomness

Copy and adapt
# evals/gates.yaml: thresholds measured from 10 runs on unchanged main, 2026-11-20
regression:
  no_unsupported_promise: {min_pass_rate: 0.97, hard: false}
  order_ids_exist:        {min_pass_rate: 1.00, hard: true}
  schema_valid:           {min_pass_rate: 1.00, hard: true}
  grounded:               {min_pass_rate: 0.93, hard: false, judge: grounded-v3, judge_calibrated: 2026-11-18}
latency:
  p95_ms: {max: 5000}
cost:
  per_case_usd: {max: 0.004}

License: free to copy and adapt for your own team. Please credit falkster.com when you share it.

More from the toolkit

All templates →