Skip to chapter content
navan✳THE BUILD LABAI ENGINEERING / GUIDE
0/21 read
CHAPTER 10 / 21 · SHAPING MODEL BEHAVIOR

Make outputs useful to software.

Design schemas, validation, retries, and fallback paths for model output that another program will consume.

BY NAVAN SAMILONG READTHEORY FIRST
01 / FROM THE BEGINNING

Start with the meaning.

When a person reads a paragraph, they can notice a strange sentence. When software consumes model output, it needs a predictable shape. A structured output contract names fields, types, allowed values, and what missing information means. For example, a request classifier might return intent, urgency, and a short reason. The application should reject values outside that contract.

A schema describes syntax and some semantics. It can say urgency must be low, medium, or high. It cannot prove that high is correct for a particular request. That second question needs task evaluation or a rule grounded in the source data. Keeping these checks separate makes failures easier to diagnose.

02 / THE SYSTEM

How the idea works.

Validation should happen before the output causes an action. Parse the object, reject unexpected or missing fields, check ranges and lengths, then check permission and domain rules. If the output selects a customer account, verify the user is allowed to access that account. A model-supplied identifier is untrusted input, even when it arrives in valid JSON.

Retries can repair occasional formatting failures, but they should be bounded. Repeating a prompt with a concise validation error may help. After a small number of attempts, return a fallback or route to review. Endless retries increase cost and latency and can hide a bad schema design. Record which failure occurred and how often it was repaired.

Prefer small schemas aligned with one decision. Asking a model for a large nested object with many independent requirements increases the chance of missing or inconsistent fields. Split the workflow when different fields need different evidence or authority.

Schema design begins with the next consumer. If the next step only needs a route, ask for a route and perhaps a reason for review. A large object with speculative fields creates more opportunities for contradiction. For example, an object might say urgency is low while its explanation says the issue is an emergency. Cross-field rules can detect some contradictions, but reducing unnecessary fields is usually simpler.

Validation errors should have a defined path. A malformed object might be retried once with a concise error. A forbidden category might be sent to review. An unauthorized account identifier should be rejected without trying to persuade the model to choose another one. Every retry needs a bound because a persistent schema mismatch can otherwise cause a loop of costly calls. Count repairs as failures in monitoring, even when the final response succeeds.

01RulesTrusted task02QuestionUser request03ContextLabelled evidence04ContractExpected output
Keep instructions, user input, and retrieved evidence clearly separated.
03 / PYTHON, EXPLAINED

Follow the code.

structured-workflows.py
def validate_ticket(value):
    if not isinstance(value, dict):
        raise ValueError("ticket must be an object")
    if set(value) != {"intent", "urgency", "reason"}:
        raise ValueError("unexpected or missing fields")
    if value["intent"] not in {"billing", "access", "other"}:
        raise ValueError("unknown intent")
    if value["urgency"] not in {"low", "medium", "high"}:
        raise ValueError("unknown urgency")
    if not isinstance(value["reason"], str) or len(value["reason"]) > 200:
        raise ValueError("invalid reason")
    return value

The function checks exact keys, allowed categories, and a reason length. Exact keys prevent extra model-generated fields from being silently accepted. A ValueError stops the caller before it updates a ticket. In a web service, the exception would be converted into a controlled failure response and recorded for diagnosis.

The validator cannot know whether the user's issue truly belongs to billing. That accuracy question belongs in evaluation cases and, for consequential decisions, human review.

04 / THE BOUNDARY

What the result does not say.

If a model produces code or SQL, validation must be much stronger than a JSON schema. Prefer a restricted tool interface with explicit operations instead of executing arbitrary generated text.

Use the simplest representation that serves the next step. A one-word category is easier to validate than a paragraph that software must interpret again.

05 / KEEP THIS

One clear idea.

Treat generated output as untrusted data until its shape, authority, and task meaning are checked.

THE CODE IN CONTEXT

The AI cookbook

Complete, explained local workflows sit alongside this reading course.

Browse the cookbook
Finished reading?
Built with curiosity. By Navan Sami. ↗AI engineering · From model calls to reliable systems.