Structured output and validation for AI features

A model that returns a nice paragraph is a demo. A model that returns a checked object your code can trust is a feature.

An assistant screen showing a WhatsApp order turned into checked fields, with one quantity flagged for review

A roofing supplier in Ruiru gets most of its orders on WhatsApp, typed fast, in a mix of Swahili and English: "Nataka bati 12 za gauge 30, rangi maroon, delivery Ruiru kesho." A person reads that and knows exactly what to do. Code cannot do anything with it until it becomes something like item, quantity, delivery_place and delivery_date.

Language models are good at that translation. They are also capable of returning "twelve", a product that does not exist, or a date of 31 November. The work of building an AI feature that writes to a business's records is mostly the work around the model: defining what a correct answer looks like and refusing anything that is not.

Define the shape before you write the prompt#

Start with the object your code needs, written as a schema. For the roofing order it might be:

from pydantic import BaseModel, Field
from datetime import date
 
class OrderLine(BaseModel):
    item_code: str
    quantity: int = Field(gt=0, le=500)
    colour: str | None = None
 
class DraftOrder(BaseModel):
    lines: list[OrderLine] = Field(min_length=1)
    delivery_place: str | None
    delivery_date: date | None
    unclear: list[str] = []

Two choices there matter more than they look.

unclear is a field. The model needs a legitimate place to say "I could not tell whether 'gauge 30' meant the 2m or 3m sheet." Without it, the model guesses, because the schema gave it no other option.

Limits are business limits. A quantity of 0 or 5,000 is not a parsing mistake the model should fix creatively. It is a value your code rejects.

Most model APIs now offer a structured output or tool-calling mode that keeps the reply in valid JSON matching a schema. Use it. It removes a whole class of "the reply had a sentence before the JSON" failures. But it only guarantees the shape. It does not guarantee that item ITS-G30-MRN exists, or that the date is in the future.

Validate in three layers#

We check every reply in order, and stop at the first failure:

  1. Shape. Does it parse into the schema? Types, required fields, ranges.
  2. Reference. Do the values point at real things? The item code exists in the item list, the customer exists, the branch delivers to Ruiru.
  3. Business rules. Is it sensible? The delivery date is not a Sunday when the yard is closed, the quantity is within what this customer normally orders, the price is not below cost.

Layer 2 is where most real errors are caught. A model asked to pick an item code from a description will sometimes produce a plausible code that is not in the list. The fix is to give it a short list of candidates found by your own search, and then check its answer is one of those candidates.

Decide what failure does#

A validation failure is not an exception to log and forget. Each one needs a designed path:

FailureWhat happens
Reply does not parseRetry once with the error message, then hand to a person
Item not foundShow staff the original message and the two closest items
Something in unclearDraft a clarifying question for the customer, staff approves
Business rule brokenKeep the draft, flag the rule, never save automatically

Notice that nothing on that list writes to the records. Even a reply that passes every check becomes a draft order that a person approves; we covered that in designing approval steps for AI that writes to your records. Validation decides whether a draft is worth showing. Approval decides whether it becomes real.

Retry carefully. Sending the same prompt again hoping for a different answer costs money and hides the problem. One retry that includes the specific error ("item_code ITS-G30-MRX is not in the candidate list") is reasonable. A loop of five is not.

Measure it like any other parser#

Keep every input, every raw reply, every validation result and every human correction. After a few weeks you have a test set made from real messages. Run it whenever you change the prompt, the model or the schema, and count:

  • how many replies passed all three layers,
  • how many passed but a person still corrected them,
  • which fields get corrected most.

That second number is the honest one. A reply can be valid and still wrong: twelve sheets when the customer meant twelve metres. Our post on measuring extraction accuracy on receipts goes through scoring field by field; the same method works for orders.

What to do this week#

Pick one AI feature that currently returns free text which your code then picks apart with string matching. Write the schema it should have returned. Add an unclear field. Add the reference check against your own records. Then look at last week's replies and count how many would have failed. That count tells you how much silent guessing has already been going on.

All posts

Want this working in your business?

We build the AI systems we write about - for retail, clinics, workshops and property businesses across Africa. Tell us what you run and we will be honest about where it helps.