跳到正文

第 9 课 · Structured Outputs

Validating Structured Results

Check the meaning of structured model output with business rules, evidence quotes, safe retries and human review before your program acts on the data.

In the last lesson, Structured Outputs gave you objects with the right shape. Shape is only the first check. An invoice object can have a valid total that does not match its lines. A support ticket can carry an order number that does not exist. A meeting date can be in the past. Your program needs a second layer of checks that knows what the data means.

This lesson builds that layer: business rules, evidence checks, careful retries and a path to human review.

Layers of validation

Layer Question Who checks
Transport Did the call succeed? Exception handling
Completeness Finished and not refused? Status and content types
Shape Right fields and types? Schema or Pydantic
Business rules Do values make sense? Your code
Grounding Does the source support them? Your code and people

Each layer catches a different kind of failure. Do not skip a lower layer because a higher one exists.

Write business rules as plain code

Rules that you can state exactly belong in code, not in a prompt. Code gives the same answer every time and you can test it. Examples:

  • Totals equal the sum of the lines.
  • Dates are in a sensible range.
  • IDs exist in your database.
  • A discount is within the limit this user may grant.
  • Text fields are not empty and not too long.

Return all problems, not only the first, with messages that a person or a model can understand.

Ground extracted facts in the source

For extraction tasks, you can ask the model to return a short quote that supports each important value. Your code then checks that the quote really appears in the source. This catches many invented details. It is not proof: a real quote can still be read wrongly. But a quote that does not exist is a clear warning.

The following stand-in uses a hand-written "model result" with two planted errors. No model produced it.

Python Stand-in: check rules and evidence

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For real money, use Python's Decimal type or whole cents instead of floating-point numbers. See decimals and fractions. The float here keeps the example short.

Retry with feedback, but only a few times

When a check fails, you can send the problems back and ask for a corrected object. Set a small limit, often one or two retries. If the source itself is wrong or unclear, more attempts will not fix it. They may only push the model to produce values that pass your checks without being true. That is the main danger of retry loops.

A safe pattern does three things:

  1. Sends the specific problems, without suggesting the "right" numbers.
  2. Allows an honest answer such as null or "unclear".
  3. Stops after the limit and routes the item to a person.
Python Stand-in: a bounded repair loop

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The final status is needs_review. That is a success for the system: it did not invent a quantity.

Decide what needs a human

Not every item needs the same care. A simple policy might be:

  • Accept automatically when all checks pass and a mistake is cheap to undo.
  • Review when checks fail, values are unknown or the amount is large.
  • Always review when a mistake could hurt someone or cannot be undone.

Do not rely on a model's own "confidence" field as a probability. A model can write 0.99 next to a wrong value. If you use such a field, measure on real labeled examples whether it predicts errors before it changes your process.

Log what you need to improve

For each item, record the model ID, the prompt version, the schema version, the check results and the final decision. Store the minimum personal data you can, and protect it. When reviewers correct a value, keep the correction as a new test example. Over time your test set reflects the problems that really happen.

Version your schema

Your database and other services may depend on field names. When you change a schema, add a version number, and make readers handle old records. Treat the schema like any other interface.

Treat string values from a model as untrusted input. Never paste them into SQL, shell commands or HTML without the usual protections, such as parameterized queries and output escaping. A schema does not make a string safe.

Measure your checks

Your checks can be wrong too. A rule that is too strict sends good results to people and wastes their time. A rule that is too loose lets errors through. Review a sample of both accepted and rejected items regularly. Count how often each check fires, and how often a reviewer agrees with it. If one check fires on almost every item, the prompt, schema or rule probably needs work. If a reviewer finds an error that no check caught, add a rule or a test case for it where that is possible.

Make the review screen useful. Show the source next to the extracted values, highlight the failed checks and let the reviewer correct fields directly.

Common mistakes

  • Telling the model the expected total in the retry message. It can then copy your number instead of reading the source.
  • Silently replacing a failed value with a default, so nobody learns that extraction failed.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. A result matches the schema, but the total does not equal the lines. What caught it?

    A schema checks types and fields. Relations between values need your own rules.
  2. 2. What does checking an evidence quote against the source show?

    It detects invented quotes, but a real quote can still be misread.
  3. 3. Why limit repair retries?

    After a small limit, send the item to a person instead.
  4. 4. How should you treat a model's self-reported confidence?

    A stated number is just more output unless testing shows that it predicts errors.

Summary

  • Check success, completeness, shape, business rules and grounding.
  • Put exact rules in testable code and report every problem.
  • Evidence quotes help expose invented facts.
  • Bound retries, allow "unknown" and send hard cases to people.
  • Treat output strings as untrusted and version your schemas.

Next: Function Calling

你的学习进度保存在此浏览器中,无需账号。