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

Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives

Three receipts, three wrong totals, and everyone blames the model. A probe taps the request, the raw reply and the saved record, then asks three questions in order. Verdicts: one cut request, one parser that turned 18.50 into 185 cents, and only one real model mistake.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Separate your integration layer (before and after the call) from the model output in the middle
  • Tap the boundary: keep the request, the raw reply and its request id, and the saved record
  • Ask three questions in order and let the first failure name the side
  • Pick the fix that belongs to that side: your code, the prompt and evals, or the parser

Before you start

  • The Claude Messages API: your first call
  • Debugging a Claude app: error types and traces

A small app reads receipts and saves the total. One day a total comes out wrong, and somebody says: the model got it wrong again.

Maybe. But a wrong answer always has a home, and the model is only one of three places it can live. In this article we find which side the fault is on before fixing anything.

Where the fault can live

Three taps on the boundary Our codebuilds the request Modelmodel output Our codeparses the record 123 request raw reply record integration layer integration layer
Our code sits on both sides of the model. Tap the request, the raw reply and the record.

Think of a restaurant where you get the wrong dish. Maybe the waiter wrote half your order on the slip (the request). Maybe the kitchen made the wrong dish, and you can see it at the pass (the raw reply). Or the dish was right but went to the wrong seat (the record). You look at the slip, then the pass, then the table. You don't blame the kitchen before you read the slip.

Three reports, one blame

  • Receipt R-202: the total is empty.
  • Receipt R-203: the total shows 185 cents.
  • Receipt R-204: the total says 40, the receipt says 44.

Same symptom, a wrong total. Three different places it can start.

Ask in order

  1. Did the whole receipt go out? If not, the fault is in the integration layer, request side.
  2. Is the answer in the raw reply right? If not, it's the model output.
  3. Did the record match the raw reply? If not, it's the integration layer again, response side.

The order matters, and the first failure names the side. A wrong request makes a wrong answer, and that answer isn't the model's fault.

receipt_app.py: our code on both sides

"""The integration layer: our code on both sides of the model call."""
import json
from stand_in import MODEL

MAX_CHARS = 60
PREFIX = "test model reply: "
ASK = "Read the receipt. Reply with JSON: merchant and total."


def build_request(case):
    text = case["text"][:MAX_CHARS]
    return {"model": MODEL, "max_tokens": 200, "system": ASK,
            "messages": [{"role": "user", "content": text}]}


def parse_reply(message):
    text = message.content[0].text.removeprefix(PREFIX)
    fields = json.loads(text)
    cents = None
    if fields["total"] is not None:
        tidy = fields["total"].rstrip("0")
        cents = int(tidy.replace(".", ""))
    return {"merchant": fields["merchant"],
            "total_cents": cents}

Two bugs are already hiding here. Can you spot them before the probe does?

probe.py: tap, then ask

class Tap:
    def send(self, client, request):
        self.request = request
        message = client.messages.create(**request)
        self.raw = message.model_dump()
        self.request_id = message._request_id
        return message


def diagnose(case, client):
    tap = Tap()
    message = tap.send(client, build_request(case))
    record = parse_reply(message)
    sent = tap.request["messages"][-1]["content"]
    reply = tap.raw["content"][0]["text"]
    fields = json.loads(reply.removeprefix(PREFIX))
    total = fields["total"]
    want = None if total is None else round(float(total) * 100)
    ok1 = sent == case["text"]
    ok2 = fields == case["expect"]
    ok3 = record["total_cents"] == want
    ...
    verdict = "no fault"
    if not ok1:
        verdict = "integration layer, request side"
    elif not ok2:
        verdict = "model output"
    elif not ok3:
        verdict = "integration layer, response side"
    return steps, verdict, tap.request_id

The tap keeps a copy of the request, the raw reply and its request id. Every API response carries a request id, and the Python SDK exposes it as _request_id. Keep it with every tap so a support ticket or a log search can find the exact call.

One verdict per receipt

The lecture runs the probe against a stand-in for Claude (the real SDK over a mock transport, scripted replies, test request ids), so the outputs below show the method, not a live model.

R-201  req_test_R201
  1 request ok    sent 52 of 52 chars
  2 raw     ok    total 8.64 (expected 8.64)
  3 record  ok    864 cents, raw says 864
  -> no fault
R-202  req_test_R202
  1 request FAIL  sent 60 of 77 chars
  2 raw     skip  not judged
  3 record  skip  not judged
  -> integration layer, request side
R-203  req_test_R203
  1 request ok    sent 43 of 43 chars
  2 raw     ok    total 18.50 (expected 18.50)
  3 record  FAIL  185 cents, raw says 1850
  -> integration layer, response side
R-204  req_test_R204
  1 request ok    sent 53 of 53 chars
  2 raw     FAIL  total 40.00 (expected 44.00)
  3 record  skip  not judged
  -> model output
verdicts: 1 no fault | 1 request side | 1 response side | 1 model output

R-202: the request was cut

MAX_CHARS = 60 keeps the first 60 characters of a 77-character receipt. The last 17 never leave, and that's where the total was. The other checks are skipped: a model can't read what was never sent. Fix our code.

R-203: the record drifted

The whole receipt went out, and the raw reply says 18.50, exactly right. But rstrip("0") strips the trailing zero, so 18.50 becomes 18.5, then the dot goes and we save 185 cents. The model was right; our parser changed the number. Because we saved the raw reply, we can run it through the parser again and get the same wrong number: a perfect reproduction.

R-204: the model output

The request was whole, and the raw reply says 40.00 where the receipt says 44.00. This one really is the model's. The fix is in the prompt: say what "total" means, add an example, and add this receipt to your evals. Patching the parser would not help.

Common mistakes

  • Rewriting the prompt first. That may "fix" the wrong side, and R-202 and R-203 stay broken.
  • Retrying until it looks right. That hides a cut request or a bad parser.
  • Switching to a bigger model. No model reads text that was never sent.
  • Logging only the parsed record. Without the raw reply you can't tell the model's mistake from the parser's.
  • Judging the model on a broken request. Once question one fails, stop and fix the request.

Quick recap

First failing questionSideFix
1. Whole input sent?Integration layer, request sideOur request-building code
2. Raw reply right?Model outputThe prompt, plus an eval case
3. Record matches raw?Integration layer, response sideOur parser

Once you know the side, choose a fix that holds on a new input too: see fix the cause, not the symptom.

Try it yourself

Add a tap to one model call in your own app: save the exact request, the raw reply with its request id, and the record you store. Next time someone says "the model got it wrong", answer the three questions before anyone touches the prompt.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 51 of 66

Previous
Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
Next post
Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App

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

  • Where the fault can live
  • Three reports, one blame
  • Ask in order
  • receipt_app.py: our code on both sides
  • probe.py: tap, then ask
  • One verdict per receipt
  • R-202: the request was cut
  • R-203: the record drifted
  • R-204: the model output
  • Common mistakes
  • Quick recap
  • Try it yourself
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.