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

Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values

Seven support tickets, seven endings: a clean tool_use block, JSON in a code fence, a cut-off reply, a refusal, a casing slip, an out-of-range priority and an unreadable reply. Three gates handle all of them.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Ask for structure with a tool and an input_schema, and know the structured outputs and strict tool use options
  • Check stop_reason for refusal and max_tokens before parsing anything
  • Read a tool_use block, or salvage JSON from text without crashing
  • Validate values a schema can't judge: enums, ranges and empty fields

Before you start

  • Claude tool use: tool_use and tool_result
  • Structured LLM output with Pydantic

A support team has a pile of tickets, and your system has to sort them. You ask Claude, using one tool, triage_ticket, with a category, a priority and a summary. Claude answers. But what comes back isn't always what you hoped for.

Most replies are clean. The rest are the ones that break the pipeline. This article puts three gates between Claude and your data so every reply ends somewhere sensible.

Five shapes a reply can take

  • A clean tool_use block.
  • The JSON as text, inside a code fence.
  • A reply cut off at max_tokens.
  • A refusal.
  • A friendly sentence with no JSON in it at all.

Your code gets all five, so plan for each one. Think of a clerk receiving parcels. One clerk signs for the box and shelves it without looking, and finds out a week later it was empty. The other clerk checks first: is the box whole, is the parcel inside, is it the right item?

Three gates

Ask, read, check 1. ask for structure tool + input_schema gives the shape 2. read defensively stop_reason first block, or JSON in text 3. check the meaning enum, range, not empty fix harmless, reject wrong refused, truncated, unreadable: stop
A schema is one gate of three. Your code holds the other two.

Gate 1: ask for structure

The pattern to learn first is a tool with an input schema. You read block.input, and the arguments are your data.

TRIAGE_TOOL = {
    "name": "triage_ticket",
    "description": "Record the category, priority and summary.",
    "input_schema": {
        "type": "object",
        "properties": {
            "category": {"type": "string"},
            "priority": {"type": "integer"},
            "summary": {"type": "string"}},
        "required": ["category", "priority", "summary"]}}


def triage(client, text):
    reply = client.messages.create(
        model="claude-haiku-5-5", max_tokens=1024,
        tools=[TRIAGE_TOOL], tool_choice={"type": "auto"},
        messages=[{"role": "user", "content": text}])
    how, data = read_reply(reply)
    ...

tool_choice is auto, which means Claude may answer in text instead of calling the tool. That's realistic, and it's why gate 2 exists.

The API offers two more ways to ask for structure. Structured outputs: set output_config.format with a JSON schema and the reply is JSON shaped by it. Strict tool use: set strict: true on a tool and its inputs match the schema. Even with these, a refusal or a max_tokens cut-off can return output that doesn't match the schema. So the next two gates apply to all three options.

Gate 2: read defensively

"""Read one reply defensively: never assume it is clean JSON."""
import json


def read_reply(reply):
    """Return (how, data). data is None when nothing is usable."""
    if reply.stop_reason == "refusal":
        return "refused", None
    if reply.stop_reason == "max_tokens":
        return "truncated", None
    for block in reply.content:
        if block.type == "tool_use":
            return "tool_use block", block.input
    parts = [b.text for b in reply.content if b.type == "text"]
    text = "".join(parts)
    start, end = text.find("{"), text.rfind("}")
    if start == -1 or end < start:
        return "unreadable", None
    try:
        data = json.loads(text[start:end + 1])
    except json.JSONDecodeError:
        return "unreadable", None
    return "text, salvaged", data

The order matters:

  1. Refusal. The model declined. It comes back with a normal 200 status, not an error. There's nothing to parse, so a person should see it.
  2. max_tokens. The reply was cut off and the JSON is incomplete. Don't parse it; retry with a higher max_tokens.
  3. A tool_use block. The clean case: read block.input.
  4. Only text. Find the first { and the last }, cut out what's between, and run json.loads inside a try. Bad JSON becomes "unreadable" instead of a crash.

Gate 3: check the meaning

"""Check the meaning of the values. A schema only checks the shape."""
CATEGORIES = ("billing", "shipping", "account")


def check(data):
    """Return (clean_data, problems). Fixes casing only."""
    data = dict(data)
    cat = str(data.get("category", "")).strip().lower()
    data["category"] = cat
    priority = data.get("priority", 0)
    problems = []
    if cat not in CATEGORIES:
        problems.append(f"category {cat!r} is not allowed")
    if not 1 <= priority <= 5:
        problems.append(f"priority {priority} is outside 1-5")
    if not str(data.get("summary", "")).strip():
        problems.append("summary is empty")
    return data, problems

Plain Python, no model. The rule is: fix what's harmless, reject what's wrong. Billing with a capital B is harmless, because enum casing isn't guaranteed, so compare case-insensitively and fix it. Priority 9 has a valid shape (it's an integer) but it's outside 1 to 5, so it's rejected. A schema can't judge that; your code can.

Seven tickets, seven endings

The run uses a stand-in model that imitates Claude on a mock transport, so no key is needed:

T-101  tool_use block -> ok
  billing | priority 2 | Card charged twice
T-102  text, salvaged -> ok
  shipping | priority 3 | Parcel is late
T-103  TRUNCATED: retry with a higher max_tokens
T-104  REFUSED: send it to a person
T-105  tool_use block -> ok (category 'Billing' -> 'billing')
  billing | priority 1 | Refund not received
T-106  tool_use block -> REJECTED: priority 9 is outside 1-5
T-107  UNREADABLE: log it and send it to a person
  • T-102 came back as text with the JSON inside a code fence. We cut it out and it parsed.
  • T-103 and T-104 stopped before parsing: one cut off, one refused. Each gets its own next step.
  • T-105 said Billing; we fixed the casing and accepted it.
  • T-106 had a perfect shape and a priority of 9. Rejected.
  • T-107 had no usable JSON at all. It's logged and sent to a person, and the program keeps running.

If your next step is a retry that sends the validation error back to the model, structured LLM output with Pydantic shows that loop.

Common mistakes

  • Parsing before reading stop_reason. A truncated reply can look almost like JSON.
  • Treating a refusal as an HTTP error. It arrives as a normal 200 response.
  • Calling json.loads on the whole text. A code fence or one friendly sentence breaks it.
  • Trusting a valid shape. A schema checks types, not whether priority 9 makes sense.

Recap

GateQuestionIf it fails
stop_reasonIs the reply complete?Refusal: a person. max_tokens: retry higher.
ReadBlock, or JSON in text?Unreadable: log it, a person.
ValidateAre the values right?Fix casing; reject out-of-range or empty.

A confident reply is not a checked one.

Keep going in Claude · 45 of 66

Previous
Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
Next post
Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
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

  • Five shapes a reply can take
  • Three gates
  • Gate 1: ask for structure
  • Gate 2: read defensively
  • Gate 3: check the meaning
  • Seven tickets, seven endings
  • Common mistakes
  • 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.