Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App

Label 30 refund-app replies by hand, check two judge rubrics against those labels (20/30 with 7 false accepts versus 29/30 with none), then gate every pull request on each slice's pass rate.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Label a golden set by hand, split into slices, before any judge runs
  • Calibrate an LLM judge by counting agreement, false accepts and false rejects
  • Gate a release on the pass rate of every slice, not the average
  • Run the gate on every pull request with an exit code CI can read

Before you start

  • Ship a Claude app (part 3)
  • Building a golden dataset
  • LLM-as-judge: writing and validating a grader

In part 3 our eval gate graded the tool trace. That proves the app called the right tools. It says nothing about whether the reply was right. To grade replies at scale we want an LLM judge, and the support lead asks the fair question: can we trust the judge?

Think of a new kitchen scale. You weigh weights you already know. If it reads wrong, you fix the scale. Only then do you weigh the flour. A judge is the same: people set the truth, and the judge has to match it before it guards anything.

Label, calibrate, gate 1 Label 30 cases, by a person 2 Calibrate judge vs labels, count false accepts 3 Gate every slice >= 0.9, exit 0 or 1
A judge nobody checked is only a guess.

The general method is covered in building a golden dataset and LLM-as-judge. This lab applies it to our own app and adds one rule that matters most for a refund bot: count the false accepts.

As in the rest of the build-along, Claude is replaced by a scripted stand-in, and the judge verdicts are scripted too (v1 listens to the tone, v2 checks the facts). The numbers show the method, not how a real model judges.

Step 1: label 30 cases by hand

"""D4: the golden set, 30 cases labelled by a person first.
Sample replies are ours to grade, some wrong on purpose.
Rubric: facts match the order, an over-limit refund
goes to a person, and the reply answers the question.
Slice by id letter: S status, R refund, H hand-off."""
CASES = [
    # id, question, a sample reply to grade, the human label
    ("S01", "Where is order A-101?",
     "order A-101 is shipped.", "pass"),
    ("S04", "Where is order A-104?",
     "order A-104 is shipped.", "fail"),
    ("S10", "Where is order A-110?",
     "order A-110 is on its way.", "pass"),
    ("R01", "Please refund order A-102.",
     "Sorry, your refund for A-102 is on its way.", "pass"),
    ("R03", "Please refund order A-104.",
     "a person will contact you about A-104.", "fail"),
    # ... 30 cases in total
]

The rubric comes first: facts match the order, an over-limit refund goes to a person, and the reply answers the question. S04 is a fail because the order is delivered, not shipped. R01 starts with "Sorry" and is still a pass, because the refund is right. Counting the labels:

  status    9 pass  1 fail
  refund    7 pass  3 fail
  hand-off  6 pass  4 fail
30 cases labelled: 22 pass, 8 fail

Hand-off has the most fails, four of ten. A wrong reply there can mean a refund nobody approved. All 30 are labelled before any judge has run.

Step 2: two rubrics, then calibrate

The judge is a second model call with a rubric as its system prompt. Version one is short: pass if the reply is polite and answers the question. Version two checks the facts, the right order, and the hand-off of a refund over the limit. The verdict is the last word, PASS or FAIL.

"""D4: calibrate the judge. Compare its verdicts with the human labels."""
from golden import CASES
from judge import JUDGE_V1, JUDGE_V2, grade
from stand_in import make_client

AGREE_MARK = 0.9


def calibrate(claude, rubric):
    agree, false_accepts, false_rejects = 0, [], []
    for cid, ask, reply, human in CASES:
        judged = grade(claude, rubric, ask, reply)
        agree += judged == (human == "pass")
        if judged and human == "fail":
            false_accepts.append(cid)
        if human == "pass" and not judged:
            false_rejects.append(cid)
    return agree, false_accepts, false_rejects


def trusted(agree, false_accepts):
    enough = agree / len(CASES) >= AGREE_MARK
    return enough and not false_accepts

Two kinds of disagreement, and they are not equal:

  • False accept: the judge says pass, a person said fail. A wrong reply gets through. This is the dangerous one.
  • False reject: the judge says fail, a person said pass. It costs some review time and does no harm.

Our trust rule (our own choice): at least 90 percent agreement and zero false accepts.

judge v1: agree 20/30  false accepts 7  false rejects 3
  false accepts: S04 R03 R07 H02 H05 H09 H10
  false rejects: R01 H04 H08
  trusted: no
judge v2: agree 29/30  false accepts 0  false rejects 1
  false accepts: none
  false rejects: S10
  trusted: yes

Version one lets seven wrong replies through, so it guards nothing. Version two agrees on 29 of 30 with no false accepts. Its one miss, S10, is a reply that said "on its way" instead of "shipped": a false reject we can live with, and a hint for the next rubric edit.

Step 3: the CI gate, per slice

PASS_MARK = 0.9
NAMES = {"S": "status", "R": "refund", "H": "hand-off"}


async def slice_rates(claude):
    seen = {}
    async with Client(mcp) as orders:
        for cid, ask, _reply, _human in CASES:
            reply, _steps = await answer(ask, claude, orders)
            ok = grade(claude, JUDGE_V2, ask, reply)
            seen.setdefault(cid[0], []).append(ok)
    return {k: sum(v) / len(v) for k, v in seen.items()}


async def gate(limit):
    hooks.LIMIT = limit
    claude = make_client()
    agree, fa, _fr = calibrate(claude, JUDGE_V2)
    print(f"candidate: refund limit {limit}")
    calibrated = "yes" if trusted(agree, fa) else "no"
    print("judge v2 calibrated:", calibrated)
    if not trusted(agree, fa):
        return False
    rates = await slice_rates(claude)
    for key, rate in rates.items():
        note = "ok" if rate >= PASS_MARK else f"below {PASS_MARK}"
        print(f"  {NAMES[key]:<9} {rate:.2f}  {note}")
    return all(rate >= PASS_MARK for rate in rates.values())

Three details make this gate honest. It scores the live app on the golden questions, with the hook and tools taking part, not the sample replies. It refuses to run if the judge isn't trusted. And every slice must reach 0.9 on its own, so one weak slice closes the gate even when the average looks fine. The script ends with sys.exit(0 if open else 1).

candidate: refund limit 5000
judge v2 calibrated: yes
  status    1.00  ok
  refund    1.00  ok
  hand-off  0.00  below 0.9
gate: closed, exit code 1
candidate: refund limit 500
judge v2 calibrated: yes
  status    1.00  ok
  refund    1.00  ok
  hand-off  1.00  ok
gate: open, exit code 0

With the limit raised to 5000, every over-limit refund went through and hand-off fell to zero. Averaged over 30 cases that is still two thirds passing, which a single average would hide. The slice view closes the gate.

Run it on every pull request

name: golden-set
on:
  pull_request:
jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install anthropic mcp claude-agent-sdk
      - run: python ci_gate.py

The golden set lives in the repo, so a changed label shows up in the pull request too. A non-zero exit fails the check. For a pytest version of the same idea see regression testing an LLM bot in CI.

Three tempting shortcuts

ShortcutWhat breaks
Let a stronger model label the setNo human data, so nothing to calibrate against
Trust the judge at 90 percent agreementAll the misses could be false accepts
Report one average pass rateA weak slice hides inside the average

Recap

StepResult on our app
Label30 cases, 22 pass, 8 fail, three slices
Calibratev1 20/30 with 7 false accepts, not trusted; v2 29/30 with 0, trusted
GateLimit 5000: hand-off 0.00, exit 1. Limit 500: all 1.00, exit 0

Previous: part 3, ship it. Next: lab: cut the bill.

Keep going in Claude · 58 of 66

Previous
Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
Next post
Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • Step 1: label 30 cases by hand
  • Step 2: two rubrics, then calibrate
  • Step 3: the CI gate, per slice
  • Run it on every pull request
  • Three tempting shortcuts
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.