# 25.9 Validate before downstream code uses it (/building-ai-workers/prompts-and-structured-output/validate-before-use)

---
type: Document
title: "25.9 Validate before downstream code uses it"
description: "The value checks code runs after the schema, when sending the error back helps, and where an answer goes when a retry cannot help."
status: stable
order: 325.09
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.9" ]
last_verified: '2026-11-29'
sources:
  - id: anthropic-structured-outputs
    title: Structured outputs (verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/structured-outputs
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 hand a bank teller a deposit slip. Every box is filled in, and every number is in the right box. She still counts the cash herself, and she checks that the account number belongs to a real account. If her count differs from your slip, she passes it back and says which number is wrong, and you count again. If the account does not exist, counting again will not help, so she calls her manager. A slip can be filled in perfectly and still be wrong. In this concept, the filled-in slip is the answer's shape, the teller's count is the value check, and the manager is Ana.

**What you will learn.** You practice this in Lab 25, Tasks 3 and 4.

- What does the schema leave unchecked?
- Which values does the code check?
- Is an invoice over its purchase order a failed extraction?
- When does sending the error back help?
- Where does an answer go when a retry cannot help?

**Why it matters.** A person who read the answer knew a wrong value when they saw one, and asked someone when they were unsure. The schema does neither. If your code does not do both on purpose, a wrong number reaches the code that pays.

**At work.** The extraction step now runs under a schema the API holds, and INV-8340 passes (25.7). The builder has run all 42 cases, and all 42 pass. But the schema would have passed the red case of 25.6 too, and a live invoice has no label from Ana to compare with. Downstream code means the code that uses the answer next. Here that is the due-date function and the triage after it.

<!-- OPEN: the red case's invoice number and its three amounts (subtotal, tax, total) are not in the spec or in specs/labs/part-2-facts.md. Add them here as one worked line once they are decided and the run is recorded. -->

### What does the schema leave unchecked?

**It leaves every value unchecked.** The schema holds the shape: the fields, their types and the allowed words. It never holds the truth, which is the rule of [21.2](../agent-loop-by-hand/a-tool-is-a-name-a-description-and-a-schema.md): "Strict means the shape, never the truth." For INV-8301, 482500 cents and 48250 cents are both whole numbers, so both pass (14.5).

The schema the API holds is also weaker than the one in your code. Claude's API rejects a schema that carries a number range or a text length (`minimum`, `maximum`, `multipleOf`, `minLength`, `maxLength`) with a 400 error.[^anthropic-structured-outputs] So 14.5's rule that `amountCents` is zero or more cannot be in the schema you send. The SDK is Anthropic's code library for calling the API. It has helper functions that take such rules out of the schema, write them into the field's description, and then check the response against your original schema. One helper, `jsonSchemaOutputFormat()`, does not check the response.[^anthropic-structured-outputs] So check those rules on the answer in your own code, whichever helper you use. The same page says to compare enum values ignoring upper and lower case.[^anthropic-structured-outputs] The due-date code wants the exact spelling "Net 30". So your code matches the answer to the list ignoring case, and passes on the list's own spelling.

### Which values does the code check?

**It checks each value against something the model did not write:** the invoice's own numbers, and Brightline's record. There are five checks, in this order, and each one is plain code with no model call. All five belong to the value gate, and no other gate repeats them.

1. **Each number is in its range.** These are the ranges the API would not carry, such as an amount of zero or more. The schema gate before this one checks the shape with the ranges left out.
2. **The total adds up.** `amountCents` must equal `subtotalCents` plus `taxCents`, to the cent. This is the check that stops the red case, because a total read as the subtotal is short by exactly the tax.
3. **The vendor exists.** `vendorId` must be a row in Brightline's `vendors` table, such as V001 for Midwest Packaging Co.
4. **The purchase order exists.** When `poNumber` is not `null`, it must be a row in Brightline's `purchase_orders` table. A `null` passes: the invoice prints no purchase order, and the triage holds such an invoice, as it did before.
5. **The terms are known.** `terms` must not be "other" (25.7). It is not a value the due-date code can use.

<!-- OPEN: the field names subtotalCents, taxCents and poNumber come from the Chapter 24 spec (raised point 3) and are not yet in specs/labs/part-2-facts.md. Whether the answer carries vendorId or the vendor's name is not decided there either. -->

<!-- EDITOR: a null poNumber passes the gates, as a correct reading of an invoice with no purchase order, and the triage holds the invoice. The other option: a null poNumber goes to needs_review. -->

```ts tab="TypeScript" tab-group="language"
// the teller counts the cash herself
const sum = answer.subtotalCents + answer.taxCents;
if (answer.amountCents !== sum) {
  failures.push(
    `amountCents is ${answer.amountCents}, but subtotalCents plus taxCents is ${sum}`,
  );
}
// "other" fits the shape, and is not a term we can use
if (answer.terms === "other") {
  failures.push("terms is other: the invoice's terms are not one of the five");
}
```

```python tab="Python" tab-group="language"
# the teller counts the cash herself
total = answer.subtotal_cents + answer.tax_cents
if answer.amount_cents != total:
    failures.append(
        f"amount_cents is {answer.amount_cents}, "
        f"but subtotal_cents plus tax_cents is {total}"
    )
# "other" fits the shape, and is not a term we can use
if answer.terms == "other":
    failures.append("terms is other: the invoice's terms are not one of the five")
```

The check returns a list of failures in plain language, as the report check of [Lab 23](../hosted-agents/lab.md), Task 18, does. An empty list means the answer may go on.

### Is an invoice over its purchase order a failed extraction?

**No.** INV-8303 is for $12,900.00, and its purchase order is for $12,000.00. An answer that says so is a correct reading of a real invoice. It passes every gate, and the triage flags the $900.00 difference, as it did before this chapter. The value checks ask one question only: did the model read this invoice correctly? Whether Brightline should pay the invoice is the triage's question, and Ana's.

### When does sending the error back help?

**It helps when the error names something the model can fix from the invoice.** Then your code adds the failure to the same conversation, in the check's own words, and calls the model again. It does this at most twice, the round limit of Lab 23, Task 18.

| The failure | Send it back? | Why |
| --- | --- | --- |
| The total is not the subtotal plus tax | Yes | All three numbers are printed on the invoice, so the model can read them again |
| The purchase order or vendor is not in the tables | Yes. If the same value comes back, stop | It may be a misread. If it is not, the invoice itself names something Brightline does not have |
| A field is null because the invoice does not print it | No | Asking again invites the model to invent a value. A `null` the schema allows is an answer, and it passes |
| The terms are "other" | No | The model has already said the invoice's terms are outside the five |
| The model declines | No | 25.10 handles it |

### Where does an answer go when a retry cannot help?

**It goes to Ana, as `needs_review`, with the gate that stopped it and the reason in plain language.** It is never passed on as done, and it never reaches `dueDate` ([13.6](../programming-fundamentals/functions.md)). `dueDate` raises an error on unknown terms, so it would have refused "Net 30 days" with a clear error. Nothing downstream would have refused the wrong total. That is why this gate stands in front.

**The price.** Each value check is code you write and test, and each retry is a second paid call. A check that is too strict sends good answers to Ana, and her time is limited. When a person reads every answer anyway, as the builder did on Friday, you can run with fewer checks. Once nobody reads, you cannot.

**The operating rule:** check each value against something the model did not write. Send the error back only when the invoice can settle it, and send everything else to a person.

<!-- FIGURE 25.9: The gates in order. Read left to right. On the far left, a box labeled "The model's answer". Three gates follow in a row, each drawn as a doorway with its name above it. Gate 1: "The stop reason". Gate 2: "The schema". Gate 3: "The values". An arrow runs from the answer into gate 1, from gate 1 to gate 2, from gate 2 to gate 3, and from gate 3 to a box on the far right labeled "The due-date code: dueDate(invoiceDate, terms)". No other arrow reaches the due-date code. From each gate, one arrow points down to a single long box along the bottom labeled "needs_review: Ana Morales reads it, with the gate and the reason". The arrow down from gate 1 is labeled "a decline, an answer cut short, an answer with no get_invoice call, or, only when fallback is on, an answer from a model the suite never ran". The arrow down from gate 2 is labeled "the wrong shape, such as Net 30 days from a prompt-only step, or text with no JSON in it". The arrow down from gate 3 is labeled "the right shape with a wrong value, such as a total that is the subtotal, or terms that are other". A small curved arrow leaves gate 3 and returns to "The model's answer", labeled "send the error back, at most twice, only if the invoice can settle it". Below the figure: only an answer that passes all three gates reaches the due-date code. -->

*Figure 25.9. The gates in order: the stop reason, then the schema, then the values. Every gate has its own way out to Ana, and only an answer that passes all three reaches the due-date code.*

**Do this now.** Open the invoice schema in your project and pick one number field. Copy this line:

> List every rule on this field that the schema checks, and every rule about its value that the schema cannot check. For each rule in the second list, name the record or the other field my code could check it against. Change nothing.

Keep the second list. It is the start of your value checks.

[^anthropic-structured-outputs]: Structured outputs, Anthropic.
