# 25.10 Defensive parsing: refusals, truncation and free text (/building-ai-workers/prompts-and-structured-output/defensive-parsing)

---
type: Document
title: "25.10 Defensive parsing: refusals, truncation and free text"
description: "Reading the stop reason first, and what the code does with a refusal, a cut answer and JSON inside free text."
status: stable
order: 325.1
ksor:
  owner: team:panaversity
  audience:
    - public
  approval:
    by: process:panaversity
    at: 2026-11-30T00:02:23Z
chapter: '25'
part: III
expert_status: co-build
concepts: [ "25.10" ]
last_verified: '2026-11-29'
sources:
  - id: anthropic-refusals-and-fallback
    title: Refusals and fallback (verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
  - id: anthropic-structured-outputs
    title: Structured outputs (verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/structured-outputs
  - id: anthropic-prompting-sonnet-5-5
    title: Prompting Claude Sonnet 5.5 (Claude Platform docs, verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5
  - id: anthropic-prompting-opus-5-5
    title: Prompting Claude Opus 5.5 (Claude Platform docs, verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5
  - id: anthropic-stop-reasons
    title: Stop reasons and fallback (Anthropic, verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons
  - id: anthropic-streaming-refusals
    title: Streaming refusals (Anthropic, verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
generated:
  at: 2026-11-30T00:02:23Z
  by: esl-rewrite/1.2.0+ksor.1
trust_tier: unverified
build_id: sha256:cc6fd9ac5f72207d4365ecbda63d87d1b64f99e05519b358a45b9f5d9bfd6f8f
dirty: true
ksor_version: 0.0.60
---

**In everyday life.** You send a shop a message asking the price of a large box. Three replies could come back. "Sorry, we do not sell those." Or "The large box costs 4", where the message stops, cut off part way. Or a long friendly message with the price somewhere in the middle. You would never write "no" or "4" into your budget as the price. You see at once which reply is an answer, which is half of one, and which needs a careful second look. In this concept, the kind of reply is the stop reason, and the careful second look is the parser.

**What you will learn.** You practice this in Lab 25, Task 4.

- What does the code read first?
- Why is a cut answer failed, even when it parses?
- What if the model declines part way through?
- How does the code find JSON in free text?
- How does the code know which model answered?
- How does anyone know each job is being done?

**Why it matters.** A person saw at once that "I can't help with that", or half an answer, was no answer. A parser does not. It reads whatever arrives as data, unless your code reads the stop reason first.

**At work.** Before each 7:10 run, the portal's code calls the Messages API for each new invoice, and nobody is looking. So before tomorrow's run the builder asks one question about three saved responses. What would each of these put in the report that Ana Morales opens at 8:40? The three are a decline, an answer cut at the output limit, and an answer in plain sentences with JSON inside.

### What does the code read first?

**It reads the stop reason, before it parses a single character.** The extraction is a Messages API call, not a hosted session, so the stop reasons are the seven of [21.3](../agent-loop-by-hand/one-turn-request-response-and-stop-reason.md).[^anthropic-stop-reasons] Only one of them lets an answer through to the schema.

| Stop reason | What the code does |
| --- | --- |
| `end_turn` | Check that a `get_invoice` call came before this answer (25.8). If none did, mark the invoice `needs_review`. If one did, go on to the schema, and then to the values (25.9) |
| `tool_use` | Run the tool the model asked for, here `get_invoice` (25.5), return its result and call again. This is not an answer yet |
| `refusal` | The model declines. Mark the invoice `needs_review`. Never send the same request again unchanged |
| `max_tokens` | The answer was cut. Treat it as failed, and ask once more with a higher limit |
| `model_context_window_exceeded` | Treat it as cut too.[^anthropic-stop-reasons] A higher output limit does not make the window larger, so it goes to `needs_review` |
| Any other | Mark it `needs_review`. This step sets no stop sequence and uses no tool that pauses |

A decline is a normal response with status 200, the web code for success, not an error.[^anthropic-stop-reasons] Its content can be empty (25.7).[^anthropic-structured-outputs] Anthropic's advice is to choose what to do by the stop reason, never by what the content looks like.[^anthropic-refusals-and-fallback] The response also carries a short category and an explanation. Show the explanation to a person, and do not parse it, because its wording is not stable.[^anthropic-refusals-and-fallback]

### Why is a cut answer failed, even when it parses?

**Because the stop reason says the model was still writing.** Anthropic's guidance is direct: treat any response whose stop reason is `max_tokens` as failed, even if its text holds valid JSON, and retry.[^anthropic-prompting-sonnet-5-5] Text that happens to parse may be missing whatever came next, and nothing in the text tells you so. The stop reason is the only thing that does.

So the code asks again once, with a higher limit. If the second answer is cut as well, the invoice goes to `needs_review`. One retry is the fair price here. A cut answer is cheap to fix when the limit was simply too low. A second cut means something else is wrong, and a person should see it.

### What if the model declines part way through?

**The code discards what it has received.** To stream a response means to receive the answer piece by piece as it is written. When your code streams, a decline can arrive after some output has already been written. Treat that partial output as incomplete and discard it.[^anthropic-refusals-and-fallback] Do not keep the half you received, and do not parse it. Before your code continues that conversation, it must also remove or reword the turn that was declined.[^anthropic-streaming-refusals]

### How does the code find JSON in free text?

**It tries to parse a value at each `{` or `[`, and keeps the last one that parses.** Free text means an answer in ordinary sentences, with no schema holding it. Your code still meets it in two places. One is Lab 24's step, which only asks for JSON in the prompt. The other is any runtime that drops the schema without saying so (25.11). Anthropic publishes one recipe, and it has four steps.[^anthropic-prompting-sonnet-5-5]

1. Read only the text blocks. A response is a list of blocks, and the first one may be the model's thinking, so read each block by its type.[^anthropic-prompting-opus-5-5]
2. Try to parse a JSON value starting at each `{` or `[` in the text.
3. Keep the last value that parses. Do not take everything from the first `{` to the last `}`, because a sentence in between breaks it.
4. Check the fields. If they are not there, ask once more.

If no value is found, the invoice goes to `needs_review` at the schema gate, with the text, so Ana can read what the model said. Brightline's step runs under a schema the API holds, so its schema gate does not ask again: it hands the invoice over.

<!-- EDITOR: Lab 25's schema gate does not ask again, as Task 4, step 2 has it, and 25.10 now says so. The other option: give Task 4's schema gate one retry, as step 4 of Anthropic's recipe has. -->

The parser never repairs broken JSON by guessing, and it never fills a gap with a default value ([14.6](../structuring-programs/errors-as-design.md)). A guessed repair can turn half an answer into a record that looks whole.

### How does the code know which model answered?

**It reads the response's `model` field.** You can ask the API to pass a declined request to another model by itself. Anthropic calls this server-side fallback, and it is in beta. Only a decline from a safety check triggers it.[^anthropic-refusals-and-fallback] When it is on, the response's `model` field names the model that answered, and a `fallback` block in the content marks the handover.[^anthropic-refusals-and-fallback] With fallback on, your code reads `model` on every response and writes it into the report. The suite's cases were run on one model. An answer from a model the suite never ran has passed no test. In this book's design, the first gate stops such an answer before any parse, and sends it to `needs_review` until the suite has run on that model too.

This check is needed only when fallback is on. Lab 25 does not turn fallback on, so its gates do not have the check.

### How does anyone know each job is being done?

**By the 7:10 report.** Every answer the code will not accept appears there with its gate and its reason, and the report counts answers by gate. Each stopped invoice is counted once, at the first gate that stopped it, so every invoice is in exactly one row.

Each line names its gate, as in Figure 25.9, and gives the reason. Monday's line, from the step as Lab 24 left it, read: INV-8340, terms "Net 30 days" is not one of the five terms.

<!-- EDITOR: the table of report lines by gate is cut, because each of its rows was a phrase on one of Figure 25.9's arrows. The figure, which the spec fixes, carries them. The other option: keep the table and shorten the figure's arrow labels. -->

<!-- EDITOR: every kind of answer the code will not accept now has one of the three gates. The first gate, which reads the response before any parse, also stops an answer with no get_invoice call and, when fallback is on, an answer from a model the suite never ran. Free text with no JSON value stops at the schema gate. The other option: a fourth gate of its own for the get_invoice check, in front of the stop reason. It was not taken, because a decline arrives with no get_invoice call and would be counted there instead of as a decline, and because the spec's Figure 25.9 has three gates. -->

<!-- OPEN: the counts for Monday, April 19, 2027 (how many new invoices, how many accepted, how many at each gate) are not in the spec. Add one real report here when the run is recorded. -->

The count matters because none of these failures is an error. A decline is not an error (above), so monitoring built on error rates never sees it.[^anthropic-refusals-and-fallback] The count by gate is the only place a week of declines that nobody noticed would show.

One limit of the API belongs here too. **Citations** are the API's marks that tie a claim in an answer to the source text behind it. A request that asks for both citations and a structured output returns a 400.[^anthropic-structured-outputs]

<!-- EDITOR: the citations line stays in 25.10, where the spec places it, with the word explained. The other option, from the review: move it to 25.7 as a fifth small cost of a schema on the response. -->

**The price.** Every path here ends at Ana more often than a looser parser would. A parser that guesses gives a fuller report and a few wrong records that nobody can find later. When a person reads each answer, the loose parser is fine. For a run nobody reads, it is not.

**The operating rule:** read the stop reason first. Parse only an answer that finished, never repair one by guessing, and count what each gate stops.

**Do this now.** Ask your coding agent to find every parse in your project. Copy this line:

> Find every place in this project where code parses a model's answer. For each one, show me whether the stop reason is read before the parse, and what happens to an answer that was declined or cut at the output limit. Change nothing.

Note any place where the parse comes first.

[^anthropic-stop-reasons]: Stop reasons and fallback, Anthropic.
[^anthropic-structured-outputs]: Structured outputs, Anthropic.
[^anthropic-refusals-and-fallback]: Refusals and fallback, Anthropic.
[^anthropic-prompting-sonnet-5-5]: Prompting Claude Sonnet 5.5, Anthropic.
[^anthropic-streaming-refusals]: Streaming refusals, Anthropic.
[^anthropic-prompting-opus-5-5]: Prompting Claude Opus 5.5, Anthropic.
