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

Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency

Six support tickets, six status 200s, six wrong answers. A catalogue of six failure modes, each with its signature, a small Python check that catches it, the place its cause lives, and the fix that edits that place: six checks fail before the fixes and all six pass after.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Name six failure modes of an LLM app from their signature in the reply or the trace
  • Write one small check per mode: grounded, answered, acted, remembered, schema_ok and agreement
  • Find where each mode's cause lives: the request, a rule, a tool description, the trim, the format or the labels
  • Fix the cause instead of hiding the symptom with retries or try-harder prompts

Before you start

  • Debugging a Claude app: error types and traces
  • Claude tool use: tool_use and tool_result

Picture a support agent whose calls all come back fine. Status 200, an answer on the screen. Still, the answer is wrong.

There is no exception to catch and no error type to read, so the tricks from sorting errors by type don't help. Instead we name the failure mode, write the test that catches it, and fix the place its cause lives. There are six modes worth knowing by name.

A waiter who gets it wrong

Think of a waiter taking your order. Six things can go wrong, and none of them is a crash.

  1. He describes a dish that is not on the menu. Hallucination.
  2. He says the kitchen can't make a dish that it can. Refusal.
  3. He says your order is in, but nothing went to the kitchen. Under-acting.
  4. He forgets you said no nuts. Context loss.
  5. He writes the slip a new way every time. Format drift.
  6. He brings a different dish for the same order. Inconsistent output.

Where the checks sit

A checking layer after the model Ticket Service Model reply + trace Checks grounded answered schema_ok acted remembered agreement
The checking layer reads the reply and its trace, and writes a verdict for every reply.

The six modes, one at a time

All traces below come from the lecture's stand-in for Claude (scripted replies, no API key), built to show each mode clearly.

1. Hallucination

A customer asks about the kettle warranty. The request carried no product sheet at all. The model still answered, and quoted a line.

trace H-01 hallucination
1 request    sheet in the request: no
2 reply      "Two years, as always."
3 quote      "Two-year warranty on all kettles."
4 grounded   FAIL the quote is not in the sheet

Signature: a reply that sounds sure but matches no source. A confident tone is not evidence. Test: look the quote up in the source. Cause and fix: there was no source. Put the sheet in the request ("K-9 kettle. Warranty: one year from purchase.") and allow "not found". Telling the model "don't invent" fixes nothing.

2. Refusal

trace R-02 refusal
1 request    rule: Never discuss account closure or personal data.
2 reply      end_turn: I can't help with that request.
3 answered   FAIL an allowed request got a no

Closing an account is allowed, but the reply is a plain no with stop_reason end_turn. Retrying can't change it, because the rule behind it says so. Fix: narrow the rule and name the allowed path: "To close an account: Settings, Account, Close."

3. Under-acting

trace U-03 under-acting
1 calls      tool calls: none
2 reply      end_turn: Done. Order 1042 is cancelled and refunded.
3 acted      FAIL never called: cancel_order, refund_order

The reply says done, with no tool call behind it. The cause was two vague tool descriptions, both just "Order helper." The fix is to say what each tool does and when to call it: "Cancel an order that has not shipped." and "Refund an order. Call it after cancel_order."

4. Context loss

trace C-04 context loss
1 request    messages sent: 3 of 7
2 request    Mac app in the request: no
3 reply      Open the web dashboard, then Export.
4 remembered FAIL the trim dropped the fact

A seven-message chat, and our code keeps only the last three. The model never saw that the customer uses the Mac app, so it gave web steps. The cause is our own trim, not the model. Pin the facts the trim must keep ("Known facts: the customer uses the Mac app."). Asking the customer again only hides the problem.

5. Format drift

trace F-05 format drift
1 reply 1    ok   {"category": "shipping"}
2 reply 2    ok   {"category": "billing"}
3 reply 3    FAIL {"Category": "Billing"}
4 reply 4    FAIL Sure! Here is the JSON: {"categ...

Valid at call one, off by call three. A check on the first reply alone would never see it, so the test runs on every reply. The cause is that the format was only asked for in words. Enforce it with a JSON schema in output_config:

CATS = ["billing", "refund", "shipping"]
FORMAT = {"format": {"type": "json_schema", "schema": {
    "type": "object", "additionalProperties": False,
    "required": ["category"],
    "properties": {"category": {"enum": CATS}}}}}

Stripping the extra words with a regex fixes nothing; the next reply drifts a new way.

6. Inconsistent output

trace I-06 inconsistent
1 runs       billing, refund, billing, refund, billing
2 agreement  60% FAIL the bar is 80%

Same ticket, five runs, two labels. Nothing is broken in any single reply. The cause is two labels that overlap. Define them so they can't: "A double charge is billing. Refunds follow returns." Running three times and taking the majority only hides the problem.

The checks in code

Checks that need only the reply live in output_checks.py:

"""Checks that need only the reply."""
import json

REFUSALS = ("I can't help", "I cannot help", "I'm not able to")
CATEGORIES = {"billing", "refund", "shipping"}


def grounded(reply, source):
    """Hallucination: the quote must appear in the source."""
    return reply["quote"] in source


def answered(text):
    """Refusal: a plain no to an allowed request fails."""
    return not text.startswith(REFUSALS)


def schema_ok(text):
    """Format drift: exact JSON, exact key, a known value."""
    try:
        data = json.loads(text)
    except ValueError:
        return False
    return (list(data) == ["category"]
            and data["category"] in CATEGORIES)

Checks that need the trace or several runs live in trace_checks.py:

"""Checks that need the trace or several runs."""
from collections import Counter


def acted(calls, required):
    """Under-acting: every needed tool must be called."""
    return [t for t in required if t not in calls]


def remembered(request, fact):
    """Context loss: the fact must still be in the request."""
    sent = " ".join(m["content"] for m in request["messages"])
    return fact in sent or fact in request.get("system", "")


def agreement(labels):
    """Inconsistent output: how often the runs agree."""
    top = Counter(labels).most_common(1)[0][1]
    return top / len(labels)

Each fix edits the cause

Run all six cases twice, once broken and once with the fix. Nothing else changes.

fixes
H-01 hallucination before FAIL grounded   after pass
R-02 refusal       before FAIL answered   after pass
U-03 under-acting  before FAIL acted      after pass
C-04 context loss  before FAIL remembered after pass
F-05 format drift  before FAIL schema_ok  after pass
I-06 inconsistent  before FAIL agreement  after pass

Common mistakes

  • Treating a 200 as success. Every mode here returns 200.
  • Fixing with words aimed at the model. "Don't invent", "try harder" and "always use JSON" don't touch the cause.
  • Retrying until it passes. That hides refusals and inconsistency; it doesn't remove them.
  • Checking only the first reply. Format drift and inconsistency only show up across replies.
  • Blaming the model for your own trim. Context loss is often in the code that builds the request.

Quick recap

ModeSignatureCheckWhere the cause lives
HallucinationSure, but matches no sourcegroundedNo source in the request
RefusalPlain no to an allowed requestansweredAn over-broad rule
Under-acting"Done" with no tool callactedVague tool descriptions
Context lossIgnores something said earlyrememberedOur history trim
Format driftValid at first, off laterschema_okFormat asked in words only
InconsistentSame input, different labelagreementOverlapping labels

Once you can name the mode, the next step is a repeatable drill for choosing the fix: see fix the cause, not the symptom.

Try it yourself

Pick five bad answers from your own app's logs. For each one, write the mode, its signature, and the place the cause lives. If you wrote "the model" as the cause more than once, look again at the request your code built.

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

Previous
Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
Next post
Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input

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 waiter who gets it wrong
  • Where the checks sit
  • The six modes, one at a time
  • 1. Hallucination
  • 2. Refusal
  • 3. Under-acting
  • 4. Context loss
  • 5. Format drift
  • 6. Inconsistent output
  • The checks in code
  • Each fix edits the cause
  • 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.