Skip to chapter content
navan✳THE BUILD LABAI ENGINEERING / GUIDE
0/21 read
CHAPTER 04 / 21 · FIRST PRINCIPLES

Sampling, uncertainty, and structured output.

See why generations vary, what decoding controls do, and how to treat JSON as data that still needs validation.

BY NAVAN SAMILONG READTHEORY FIRST
01 / FROM THE BEGINNING

Start with the meaning.

At each step a language model assigns different likelihoods to possible next tokens. A decoding strategy chooses one token and repeats the process. If the strategy always chooses the highest-scoring option, outputs may be more repeatable but can still be wrong. If it samples among likely options, outputs can vary. Temperature changes how spread out the choice is; it does not make an answer truthful or creative by itself.

Applications often want a structured result, such as a category, score, and explanation. Text that looks like JSON can be parsed into fields. A provider may also support constrained output formats. Either way, structure only controls form. A perfectly formed object can contain an invented category or a confidence number with no calibrated meaning.

02 / THE SYSTEM

How the idea works.

Separate three checks: can the output be parsed, does it match the expected schema, and does it satisfy the task. For example, a support routing object might require category to be one of billing, access, or other. A parser accepts {"category":"banana"}; a schema check rejects it. Even {"category":"billing"} may be wrong for the user's issue, which requires task evaluation.

Keep output limits aligned with the job. A short classification answer should not need a long generation budget. A long report needs room to include its evidence and caveats. Truncated output may leave an invalid object or omit a crucial qualification. A robust application detects that state rather than presenting an incomplete result as final.

Repeated calls are useful when comparing options or estimating variability, but they also cost time and money. Do not treat several similar generations as independent proof. All calls can share the same missing evidence or flawed instruction. The right uncertainty signal is often a measured failure rate on representative cases, plus a clear fallback when evidence is absent.

A temperature setting changes the distribution from which a token is chosen. Lower values often make outputs less varied; higher values can make unusual continuations more likely. Neither setting tells the model which facts are true. A low-temperature answer can repeat the same hallucination consistently, while a high-temperature answer can still be correct. Choose decoding settings for the task's desired variability, then judge quality on representative examples.

Structured output is particularly useful when the result feeds another program. Suppose the object says a payment is approved. JSON validation can establish that approved is a boolean, but it cannot establish that the customer actually consented or had funds available. Domain checks and authority checks must happen in the application. For a consequential action, the model's structured object should be a proposal that software and, where appropriate, a person review.

01GenerationCandidate text02ParseReadable JSON?03SchemaAllowed fields?04TaskCorrect meaning?
Valid syntax and a valid schema do not guarantee a correct answer.
03 / PYTHON, EXPLAINED

Follow the code.

sampling-and-structure.py
import json

def parse_route(raw):
    try:
        value = json.loads(raw)
    except json.JSONDecodeError:
        return None
    if not isinstance(value, dict):
        return None
    if value.get("category") not in {"billing", "access", "other"}:
        return None
    if not isinstance(value.get("reason"), str):
        return None
    return {"category": value["category"], "reason": value["reason"]}

json.loads converts text into a Python value. That value might be a list, number, or dictionary, so the next check matters. The allowed-category set closes the output space to three values. The reason must be text. The function returns only validated fields, which prevents unexpected keys from flowing into another part of the application.

This parser cannot prove the chosen route is correct. That requires labelled support requests or human review. It also does not enforce length or reject harmful content in reason. Those are separate product rules.

04 / THE BOUNDARY

What the result does not say.

Determinism can help repeatability, but model services, versions, and infrastructure can still introduce differences. Save inputs, settings, and model versions for controlled evaluations.

When a structured response fails validation, a narrow retry may help. Limit retries and record the failure; otherwise an application can spend a surprising amount of time trying to repair an impossible request.

05 / KEEP THIS

One clear idea.

Control output shape explicitly, then evaluate whether the content is correct.

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.