How to grade Claude's answers with code checks

Day 3, 25 minutes · advanced

Goal of this lessonRun the email sorter over your test set and grade each answer with code checks: valid JSON, a known label and an exact match.

Why it matters

You have criteria and a test set. Now you need someone, or something, to check every answer. Reading twelve answers by hand is fine once. Reading them after every prompt change, every week, is not, and you will start to skim.

Today you let code do the checking. For a task with a fixed right answer, such as a category, a few lines of Python grade an answer in a split second, the same way every time. At the end you have run your first real eval: a score, a list of what failed and why, and a results file you will compare against later.

The words you need today

  • Grader: the logic that scores an answer. It can be code, a model or a person.
  • Exact match: the answer must equal the ground truth, often after removing spaces and making both lower case.
  • String match: the answer must contain a key word or phrase.
  • Score: here, the share of test cases that pass all checks.

Three kinds of graders, in order of preference

The Claude docs say to choose the fastest, most reliable, most scalable method that works:

  1. Code-based grading: fastest and most reliable, and it scales well. It lacks nuance for judgments that do not fit a rule. Examples: exact match and string match.
  2. Human grading: the most flexible and highest quality, but slow and expensive. The page says to avoid it if possible.
  3. LLM-based grading: fast and flexible, scales well and suits complex judgment. Test that it is reliable first. Lesson 4 is about this one.

Anthropic's engineering post lists the strengths of code graders as fast, cheap, objective, reproducible and easy to debug. Their weakness: they are brittle when an answer is valid but does not match the expected pattern exactly.

Tjalling's four checks

graders.py checks every answer four ways:

  • valid_json: can Python read the answer as JSON at all? If not, the program that should use the answer cannot either.
  • known_label: is the category one of the five? An answer like "repair" is not.
  • category: exact match with the ground truth, after removing spaces and making it lower case.
  • urgent: does true or false match the ground truth?

A test case passes only if all four checks pass. The script prints which checks failed, because "FAIL" alone does not tell you what to fix.

The format check is not a formality. If Claude wraps its JSON in a markdown code fence (three backticks before and after), a person sees the right answer, but json.loads cannot read it and the check fails. The docs page on output consistency points to structured outputs when you need JSON that always follows a schema. This course keeps the prompt simple and lets the check show what happens.

Read the failures, not just the score

A score on its own says little. The useful part is the list of failures. For each one, ask three questions:

  1. Is the answer wrong? Then the prompt or the model needs work.
  2. Is my ground truth wrong or unclear? Then fix the test case, and write down the rule you used.
  3. Is my check too strict? For example, it rejects a valid answer because of a detail that does not matter. Then fix the grader.

Anthropic's engineering team says they do not take eval scores at face value until someone reads the details of what failed. Do the same. And a rule of this course: never change the test set just to get a higher score.

Your results will differ from anyone else's, and they can differ between two runs of your own: Claude does not always give the same answer twice. Lesson 5 shows how to deal with that.

The steps

  1. Create the graders: one function that returns the four checks for one answer.
  2. Create the eval script: it sends each test email to Claude, grades the answer, prints one line per case and saves all results in results.json.
  3. Run the eval and read every failed case.
  4. Write the score next to your criteria, with the date and the model.

Follow the steps below.

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. Open a terminal in your spokeworth-evals folder and turn on the virtual environment: source .venv/bin/activate on macOS or Linux, .venv\Scripts\Activate.ps1 on Windows.
  2. Create graders.py with this code. grade() returns four checks for one answer: valid JSON, a known category, the right category and the right urgent value.
    import json
    
    from classifier import CATEGORIES
    
    
    def parse_json(output):
        try:
            data = json.loads(output)
        except json.JSONDecodeError:
            return None
        return data if isinstance(data, dict) else None
    
    
    def grade(output, case):
        data = parse_json(output)
        if data is None:
            return {"valid_json": False, "known_label": False, "category": False, "urgent": False}
        label = str(data.get("category", "")).strip().lower()
        return {
            "valid_json": True,
            "known_label": label in CATEGORIES,
            "category": label == case["category"],
            "urgent": data.get("urgent") == case["urgent"],
        }
  3. Create run_eval.py with this code. It sends every email in the test set to Claude, grades each answer, prints PASS or FAIL with the failed checks and saves everything in results.json.
    import json
    import sys
    
    from classifier import classify
    from graders import grade
    
    model = sys.argv[1] if len(sys.argv) > 1 else "claude-haiku-5-5"
    cases = [json.loads(line) for line in open("test_set.jsonl", encoding="utf-8") if line.strip()]
    
    results = []
    for case in cases:
        output, usage, seconds = classify(case["email"], model=model)
        checks = grade(output, case)
        passed = all(checks.values())
        results.append({"id": case["id"], "passed": passed, "checks": checks, "output": output})
        failed = [name for name, ok in checks.items() if not ok]
        print(case["id"], "PASS" if passed else "FAIL " + ", ".join(failed), "|", output)
    
    with open("results.json", "w", encoding="utf-8") as f:
        json.dump(results, f, indent=2)
    
    passed = sum(r["passed"] for r in results)
    print(f"Model {model}: {passed} of {len(results)} passed ({passed / len(results):.0%})")
  4. Run python run_eval.py. Each line shows the case id, PASS or FAIL with the names of the failed checks, and the answer. The last line shows the score.
  5. Read each FAIL line. Ask: is the answer really wrong, or is my right answer or my check wrong? Fix the test set or the check only when they are wrong, not to make the score look better.
  6. Open criteria.txt and add a line with today's date, the model and the score, for example <date>: claude-haiku-5-5, <passed> of <total>.

Note: To run the same eval on another model, pass its id: python run_eval.py claude-sonnet-5-5. That model costs more per token. A score can change a little from one run to the next even when nothing changed; lesson 5 deals with that.

Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.

Checked on 4 December 2026 · Source: Claude API docs: Define success criteria and build evaluations (opens in a new tab)

Create a free account to save your progress. Sign in or sign up