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

The contract of a model call.

Understand input messages, output text, errors, timeouts, and why an API response is only a candidate answer.

BY NAVAN SAMILONG READTHEORY FIRST
01 / FROM THE BEGINNING

Start with the meaning.

Most applications meet a foundation model through an interface: send input, receive output. The input may contain instructions, conversation messages, retrieved passages, images, or tool results. The output may contain text, a structured object, a request to call a tool, or an error. A library can make this look like one function call, but the application still needs to understand the contract.

A contract states what the caller supplies and what it may safely assume in return. A normal Python function might promise an integer. A model call usually promises something weaker: a response in a particular transport format, whose meaning must still be checked. It can return a fluent sentence that fails the user's task. Network failures and rate limits can also happen before any answer is generated.

02 / THE SYSTEM

How the idea works.

Keep transport success separate from task success. An HTTP success means a service processed the request; it does not mean the answer is accurate, complete, or suitable. Validate the response shape first, then validate the task-specific content. A JSON parser checks syntax, while a business rule checks whether a cited document exists or whether a requested field is permitted. Both checks are needed.

Model calls have settings such as output limits and sampling controls. These affect behavior and cost, but they are not substitutes for a clear task. Record the model identifier and settings used for important outputs so a later evaluation can be reproduced. Treat model versions as dependencies: when they change, examples that once passed may behave differently.

A timeout is a user experience decision as much as a technical one. If a response takes too long, the application may show progress, retry a safe request, or return a useful fallback. Retrying an action that changes external state is different from retrying a read-only generation. A request identifier can help prevent repeated actions when a response is lost.

Suppose a user clicks Generate and the network times out. The model service might never have received the request, or it might have produced an answer that the application never saw. If the call only generates text, a retry may be reasonable. If the call triggers an external action, a blind retry can duplicate that action. This is the reason idempotency exists: the application gives one intended operation a stable identifier, and the action layer ensures it is applied at most once.

An adapter should also distinguish failures that users can correct from failures they cannot. An oversized input can prompt the user to shorten a document. Invalid credentials require an operator. A rate limit may merit a delayed retry. A malformed response may be a provider change or a schema mismatch. Returning one generic “AI failed” state loses the information needed to choose a useful recovery path.

01User taskA bounded request02ApplicationRules and evidence03ModelCandidate output04ValidationCheck and present
A model is one stage. Application code controls evidence, permissions, and presentation.
03 / PYTHON, EXPLAINED

Follow the code.

model-call-contract.py
def safe_generate(model_call, messages):
    try:
        response = model_call(messages, timeout_seconds=20)
    except TimeoutError:
        return {"status": "unavailable", "text": None}
    text = response.get("text") if isinstance(response, dict) else None
    if not isinstance(text, str) or not text.strip():
        return {"status": "invalid", "text": None}
    return {"status": "candidate", "text": text.strip()}

The wrapper names three states. “Unavailable” means no usable transport response arrived. “Invalid” means the response did not match the expected shape. “Candidate” means there is text to inspect, not that the text has been proven correct. The isinstance checks prevent a missing or numeric field from becoming a fake answer. A real adapter would also distinguish authentication errors, rate limits, and provider-specific response formats.

The model_call argument is deliberately abstract. Different services expose different SDKs and fields, and those details change. The stable engineering principle is to contain vendor-specific code in one adapter, then give the rest of the application a small, explicit contract.

04 / THE BOUNDARY

What the result does not say.

Never put a secret key in browser code or a public repository. If an application uses a hosted model, its server should manage credentials and decide which user requests are allowed. This is about protecting both private data and the cost of an account.

“Candidate” is a useful word in system design. It reminds the team that generation is one stage; validation, grounding, presentation, and user control follow it.

05 / KEEP THIS

One clear idea.

A successful API call produces a candidate response, not a verified answer.

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.