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

Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input

Four saved meeting notes that failed: format drift, a cut reply, context loss and an invented due date. The tempting fixes (retry, raise the limit, type a reminder, warn the model) hold on 0 of 4 when a new note arrives. Changing what the request asks holds on 4 of 4.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Run a four-step recovery drill: reproduce, try the tempting fix, test a new input, fix the cause
  • Explain why a retry, a bigger max_tokens or a one-off reminder only quiets a symptom
  • Move the fix into the request: a JSON schema, a smaller ask, a rule in the system prompt, an optional field
  • Prove a fix by passing both the saved reproduction and a fresh input

Before you start

  • Six ways a 200 can still be wrong: the failure-mode catalogue
  • Structured output with a JSON schema

A small app reads meeting notes and lists the action items: owner, task and due date. One day a reply comes back wrong. Good news: we saved the note that failed, so we can run it again and watch it fail.

Then someone says: run it again. Or raise the limit. Or add a reminder. Each quick fix makes today's report go away. None of them touches the cause. This article is a drill for choosing the fix that closes it.

A drip in the ceiling

You see water on the floor: the failing reply. A bucket catches the drip today: a retry, a bigger limit, a reminder. The roof is the real repair. A bucket works until the next rain. The roof works every time.

Where the fix goes

A note comes in, our code builds a request, the model sends a raw reply, our code reads it into an action item. What we ask, and how we ask it, is our code's job. In all four drills here, the cause lives in the request. The model answers what it was asked.

A retry sends the very same request again, so expect the same kind of answer. A cause fix changes the request.

The same drill every time

The four-step recovery drill 1. Reproduce run the savednote, watch it fail 2. Tempting fix it may pass,but only once 3. New note a symptom fixfails again 4. Cause fix change the request;both notes pass
A fix that only passes step two has not touched the cause. Step three is the honest test.

Telling which side broke, your code or the model, is its own skill: see integration layer or model output. Here we start from a reproduction and choose the recovery.

minutes_app.py: the integration layer

"""The integration layer: build the request, read the reply."""
import json
from stand_in import MODEL

PREFIX = "test model reply: "
SYSTEM = "Read the meeting note and reply with the action item: owner, task and due."
KEEP = 2


class BadReply(Exception):
    pass


def build_request(note, system=SYSTEM, max_tokens=12,
                  schema=None, earlier=()):
    request = {"model": MODEL, "max_tokens": max_tokens,
               "system": system,
               "messages": [*earlier[-KEEP:],
                            {"role": "user", "content": note}]}
    if schema:
        request["output_config"] = {
            "format": {"type": "json_schema", "schema": schema}}
    return request


def read_item(message):
    if message.stop_reason == "max_tokens":
        raise BadReply("stop_reason max_tokens, reply cut")
    text = message.content[0].text.removeprefix(PREFIX)
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        raise BadReply("reply is not JSON") from None

Three details matter later: only the last two earlier messages go out (KEEP = 2), a schema becomes output_config, and a reply that stops at max_tokens is treated as a failure and never parsed. The runs below use the lecture's stand-in for Claude, where one word counts as one token and every reply is scripted.

fixes.py: base, tempting fix, cause fix

STRING = {"type": "string"}
SHAPE = {"type": "object", "required": ["owner", "task", "due"], "additionalProperties": False,
         "properties": {"owner": STRING, "task": STRING, "due": STRING}}
OPTIONAL_DUE = {**SHAPE, "properties": {
    **SHAPE["properties"],
    "due": {"anyOf": [STRING, {"type": "null"}]}}}

# what the app sends today in each drill
BASE = {
    "D1": {},
    "D2": {"system": SYSTEM + " Add why it matters."},
    "D3": {"earlier": HISTORY},
    "D4": {"schema": SHAPE},
}
# the tempting fix: "keep" stays in the app,
# "once" is typed into one reply
SYMPTOM = {
    "D1": {"tries": 3},
    "D2": {"keep": {"max_tokens": 18}},
    "D3": {"once": " Write the owner as Name (team)."},
    "D4": {"tries": 2, "once": " Only use facts from the note."},
}
# the fix for the cause: change what the request asks for
CAUSE = {
    "D1": {"schema": SHAPE},
    "D2": {"system": SYSTEM},
    "D3": {"system":
           SYSTEM + " Write every owner as Name (team)."},
    "D4": {"schema": OPTIONAL_DUE},
}

The four drills

D1 format drift: a retry sends the same request

The reply isn't JSON, so we retry three times. Three calls, the same reply every time. A retry is right for a busy server, but here the request never says what shape to return. The fix is a JSON schema in the request.

D2 cut reply: a bigger limit hides what fills the reply

The system prompt also asks "why it matters". With that extra field, the first note runs to 15 tokens and the second to 22. Both pass the limit of 12, so both are cut. Raising the limit to 18 fits the first note; the second is cut again. We never use that extra field. Drop it, and both replies fit the original limit. A bigger limit is right when you need the longer reply; here we don't.

D3 context loss: a reminder fixes one reply

The team rule (write owners as Name (team)) came first in the chat. Our code keeps only the last two earlier messages, so the rule is trimmed away and the owner comes back as Ana instead of Ana (legal). Typing a reminder into that one note passes. The next note has no reminder, and the owner is Ben. Move the rule into the system prompt: it goes out on every call.

D4 invented value: a required field makes the model invent

The note never gave a due date, yet the reply says Friday. A retry with a warning only changes it to TBD. Still wrong. The cause is that due is a required string: the model must fill it, so it invents. Let due be empty (anyOf string or null) and both notes pass.

Four drills, one tally

D1  format drift  M-301
  1 reproduce       FAIL  1 call, reply is not JSON
  2 retry x3        FAIL  3 calls, reply is not JSON
  3 new note        skip  not judged
  4 cause fix       ok    2 of 2 notes pass
  -> cause: the request never asked for a shape
D2  cut reply  M-302
  1 reproduce       FAIL  1 call, stop_reason max_tokens, reply cut
  2 bigger limit    ok    1 call, item matches the note
  3 new note        FAIL  1 call, stop_reason max_tokens, reply cut
  4 cause fix       ok    2 of 2 notes pass
  -> cause: we ask for a field we never use
D3  context loss  M-303
  1 reproduce       FAIL  1 call, owner is Ana, expected Ana (legal)
  2 reminder        ok    1 call, item matches the note
  3 new note        FAIL  1 call, owner is Ben, expected Ben (ops)
  4 cause fix       ok    2 of 2 notes pass
  -> cause: the rule sits in history we trim
D4  invented value  M-304
  1 reproduce       FAIL  1 call, due is Friday, expected empty
  2 retry + warning FAIL  2 calls, due is TBD, expected empty
  3 new note        skip  not judged
  4 cause fix       ok    2 of 2 notes pass
  -> cause: the schema makes due required
held after the tempting fix: 0 of 4 | after the cause fix: 4 of 4

None of the tempting fixes held. All four cause fixes did.

Common mistakes

  • Stopping at step two. The saved note passes, so the ticket is closed. Always try a new input.
  • Retrying a deterministic failure. Same request, same kind of reply.
  • Raising max_tokens by reflex. First ask what fills the reply, and whether you use it.
  • Typing reminders into one turn. Rules that must always hold belong where they are always sent.
  • Forcing a value the input doesn't have. A required field with no source is an invitation to invent.

Quick recap

DrillTempting fixCause fix
Format driftRetry x3JSON schema in output_config
Cut replyBigger max_tokensStop asking for the unused field
Context lossReminder in one noteRule in the system prompt
Invented valueRetry with a warningLet the field be empty

Fix the cause, then test a new note.

Try it yourself

Take the last LLM bug you "fixed". Run the fix on a fresh input the original report never saw. If it fails, find where the cause lives in the request and change that instead.

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 · 50 of 66

Previous
Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
Next post
Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives

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

  • A drip in the ceiling
  • Where the fix goes
  • The same drill every time
  • minutes_app.py: the integration layer
  • fixes.py: base, tempting fix, cause fix
  • The four drills
  • D1 format drift: a retry sends the same request
  • D2 cut reply: a bigger limit hides what fills the reply
  • D3 context loss: a reminder fixes one reply
  • D4 invented value: a required field makes the model invent
  • Four drills, one tally
  • 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.