Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin 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: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data

The refund app ships as a template with a typed-in model id, a key in code and evals that only work for one shop. A five-check audit finds all of it; template.json, config.py, data-built evals, exact pins and a README fix it, and the same evals then pass for two customers.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Audit a template for a hard-coded model id, a key in code, customer data, loose pins and missing docs
  • Move every per-customer value into template.json with an optional customer override file
  • Build eval cases from a customer's own orders and limit
  • Pin package versions exactly and document parameters and a changelog

Before you start

  • Ship a Claude app (part 3)
  • Pinning model versions and upgrade evals

A maintainer is handed our refund app as a template for new customers. Before they accept it, it has to work for any shop, whoever opens it, with nobody editing code first. Right now it doesn't. This last lab of the build-along repairs three defects, pins what must be pinned, and writes it up. (In the course this lecture is an extra prep bonus, not a separate exam objective.)

Think of a shop manual copied to a new branch. If the supplier's name is written on every page, changing it means editing every page; written once on the front, the pages just point to it. The safe code copied into the manual can be read by every branch that gets a copy. And a staff test that names the first shop's regulars fails anywhere else.

Three defects, three fixes model id typed into the call key typed into the code evals that name Acme Shop one pinned id in template.json key from env, .env in .gitignore evals built from each customer's data
A maintainer can accept it when all three are fixed, pinned and written up.

The template as it shipped

"""The model call, as the template shipped it."""
from anthropic import Anthropic

client = Anthropic(api_key="sk-ant-...")  # a key string typed into the code (shortened here)


def ask(question, tools):
    return client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=300,
        tools=tools,
        messages=[{"role": "user", "content": question}])

Two defects in one file. The key string travels with every copy of the template, and the model id is typed into the call, so changing it means editing code. The eval file has the third defect: its docstring names Acme Shop, its cases use order ids like A-102 from one shop's data, and the hook case only works because of Acme's limit and prices. Another shop doesn't have A-102, so the case can't even start.

An audit with five checks

MODEL = re.compile(r"[\"']claude-[a-z0-9.-]+[\"']")
KEY = re.compile(r"sk-[A-Za-z0-9_-]{10,}")
CUSTOMER = re.compile(r"Acme Shop|\bA-\d{3}\b")


def model_id(root):
    hit = scan(root, MODEL, ["*.py"])
    if hit:
        return False, f"model id typed in {hit}"
    if not (root / "template.json").exists():
        return False, "no template.json"
    note = "no model id in code, one in template.json"
    return True, note


def pins(root):
    req = root / "requirements.txt"
    if not req.exists():
        return False, "no requirements.txt"
    rows = [r for r in req.read_text().split() if r]
    loose = [r for r in rows if "==" not in r]
    if loose:
        return False, f"not pinned: {loose[0]}"
    return True, f"{len(rows)} packages pinned with =="


CHECKS = [("model id", model_id), ("secret", secret),
          ("customer", customer), ("pins", pins),
          ("docs", docs)]

check_template.py has one function per check: a quoted claude model id in code, key-shaped text (sk- and a long tail), a shop name or an order id, exact version pins, and a README with parameters and a changelog. scan() returns the first file and line that matches. On the template as it shipped:

$ python check_template.py defects
audit defects
  FAIL model id: model id typed in app.py line 9
  FAIL secret: key-shaped text in app.py line 4
  FAIL customer: one customer's data in evals.py line 1
  FAIL pins: no requirements.txt
  FAIL docs: no README.md
5 checks fail

Repair 1: template.json and config.py

{
  "template_version": "1.1.0",
  "model": "claude-sonnet-5-5",
  "customer": "Acme Shop",
  "refund_limit": 500,
  "orders_file": "orders.json"
}

Everything that changes between customers lives here, and nothing in it is secret. The template version tells a maintainer which one they reviewed. The model is named once: one exact id, the one the evals run on. The limit and the orders file are parameters now.

"""Everything a new customer changes lives here."""
import json
import os
import pathlib

HERE = pathlib.Path(__file__).parent
PARAMS = json.loads((HERE / "template.json").read_text())

# A customer file overrides the defaults.
OVERRIDE = os.getenv("TEMPLATE_CUSTOMER")
if OVERRIDE:
    extra = pathlib.Path(OVERRIDE).read_text()
    PARAMS.update(json.loads(extra))

MODEL = PARAMS["model"]
CUSTOMER = PARAMS["customer"]
LIMIT = PARAMS["refund_limit"]
ORDERS = HERE / PARAMS["orders_file"]
API_KEY = os.getenv("ANTHROPIC_API_KEY", "")

Every other file reads the model and the limit from here, so nothing else types a model id. If TEMPLATE_CUSTOMER points to a customer file, it overrides the defaults; that's how a second shop gets its own limit with no code edit. The key comes from the environment. The real key lives in a .env file that .gitignore keeps out of git, and .env.example is a blank copy to start from. A second customer file looks like this:

{
  "customer": "Birch Books",
  "refund_limit": 200,
  "orders_file": "customers/birch_orders.json"
}

For the key side in more depth, see API keys, proxies, rotation and scope.

Repair 2: evals built from the data

def build_cases(orders, limit):
    price = {i: o["total"] for i, o in orders.items()}
    ids = sorted(price, key=price.get)
    under = [i for i in ids if price[i] <= limit]
    over = [i for i in ids if price[i] > limit]
    small, big = under[-1], over[0]
    return [
        ("refund within the limit",
         f"Please refund order {small}.",
         f"issue_refund {small} -> refund sent"),
        ("refund over the limit",
         f"Please refund order {big}.",
         f"issue_refund {big} -> hook denies"),
        ("unknown order",
         "Where is order Z-000?",
         "get_order Z-000 -> mcp: Error"),
    ]

The function needs only two facts: the customer's orders and their limit. It picks the biggest order under the limit and the smallest order over it, so no order id is typed in. Each case runs through the real loop, and we look for the expected step in the trace.

Repair 3: pin and document

anthropic==2.10.0
mcp==2.3.0
claude-agent-sdk==0.2.185

Each package is pinned with == to the exact version the lab ran, not a range. The model id in template.json is pinned in the same spirit (more in model pinning and upgrade evals). The README opens with the version, lists what template.json holds and what a customer file overrides, gives three steps for a new customer (copy a customer file, set the key, run the checks), and ends with a changelog of the fixes and pins.

One template, two customers

As in the rest of the build-along, model replies come from the scripted stand-in, so no key is needed.

$ python check_template.py .
audit .
  ok   model id: no model id in code, one in template.json
  ok   secret: no key in files, .env ignored
  ok   customer: no customer name or order id in code
  ok   pins: 3 packages pinned with ==
  ok   docs: README.md has parameters and changelog
all 5 checks pass
$ python evals.py
evals for Acme Shop, limit $500
  pass refund within the limit
  pass refund over the limit
  pass unknown order
3 of 3 pass
$ $env:TEMPLATE_CUSTOMER="customers/birch.json"; python evals.py
evals for Birch Books, limit $200
  pass refund within the limit
  pass refund over the limit
  pass unknown order
3 of 3 pass

Between the two eval runs only the customer file changed. No code did. That's the test of a template.

Recap

DefectFixAudit check
Model id typed in the callOne id in template.json, read through config.pymodel id
Key in the codeANTHROPIC_API_KEY from the environment, .env ignoredsecret
Evals for one shopbuild_cases(orders, limit)customer
No pins, no docsrequirements.txt with ==, README with parameters and changelogpins, docs

Fix it, pin it, write it up. That closes the build-along: from one business need in part 1 to an app a maintainer can hand to the next customer.

Previous: lab: judge, retry and hook matcher.

Keep going in Claude · 63 of 66

Previous
Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
Next post
Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
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

  • The template as it shipped
  • An audit with five checks
  • Repair 1: template.json and config.py
  • Repair 2: evals built from the data
  • Repair 3: pin and document
  • One template, two customers
  • 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.