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.
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_useblock. - 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
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:
- 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.
- max_tokens. The reply was cut off and the JSON is incomplete. Don't parse it; retry with a higher
max_tokens. - A tool_use block. The clean case: read
block.input. - Only text. Find the first
{and the last}, cut out what's between, and runjson.loadsinside atry. 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.loadson 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
| Gate | Question | If it fails |
|---|---|---|
| stop_reason | Is the reply complete? | Refusal: a person. max_tokens: retry higher. |
| Read | Block, or JSON in text? | Unreadable: log it, a person. |
| Validate | Are the values right? | Fix casing; reject out-of-range or empty. |
A confident reply is not a checked one.
StudyEasy AI Community
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
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.