Skip to content
The AI Agent Factory

25.10 Defensive parsing: refusals, truncation and free text

Approved by
Panaversity ·
18 min read

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.1 Only one of them lets an answer through to the schema.

Stop reasonWhat the code does
end_turnCheck 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_useRun the tool the model asked for, here get_invoice (25.5), return its result and call again. This is not an answer yet
refusalThe model declines. Mark the invoice needs_review. Never send the same request again unchanged
max_tokensThe answer was cut. Treat it as failed, and ask once more with a higher limit
model_context_window_exceededTreat it as cut too.1 A higher output limit does not make the window larger, so it goes to needs_review
Any otherMark 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.1 Its content can be empty (25.7).2 Anthropic's advice is to choose what to do by the stop reason, never by what the content looks like.3 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.3

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.4 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.3 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.5

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.4

  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.6
  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.

The parser never repairs broken JSON by guessing, and it never fills a gap with a default value (14.6). 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.3 When it is on, the response's model field names the model that answered, and a fallback block in the content marks the handover.3 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.

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.3 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.2

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.

Check yourself

Question 1 / 7

0 answered

A response arrives from the Messages API. What does the extraction code read before anything else?

  1. Stop reasons and fallback, Anthropic.↑↑2↑3
  2. Structured outputs, Anthropic.↑↑2
  3. Refusals and fallback, Anthropic.↑↑2↑3↑4↑5↑6
Owner
Panaversity