All lessons in AI Engineering: From Foundation Models to Evaluated Applications
Model Interfaces and Application Contracts
Specify validated inputs and outputs, timeout behavior, and safe credential handling. Specify bounded asynchronous calls and cancellation behavior.
90 minutes · Free lesson
What you will learn
- Specify a model adapter contract with validated inputs, outputs, errors, and credential boundaries.
- Design bounded asynchronous calls with explicit deadlines, cancellation, and overload behavior.
- Trace a failed or partial response without exposing secrets or claiming an unconfirmed action completed.
Your prototype works when one person sends one short question. It fails differently when several users arrive together: one request waits indefinitely, another returns malformed data, and a third displays half an answer as though it were complete. The model's language capability has not necessarily changed. The application has no sufficiently precise contract for requests and failures.
A model interface is more than the line that sends text to a provider. It is the boundary that translates your application's task into a provider request and translates the response into something the rest of your system can trust to a defined degree. This lesson develops that boundary. P02 is the separate implementation practice; the exercises here ask you to design and inspect contracts before writing the full adapter.
The examples use fictional limits and timing. The local reference in courses/ai-engineering/support-assistant demonstrates a text-only adapter, controlled errors, and a default deterministic mode. It is a reference for selected boundaries, not an implementation of every streaming and concurrency requirement discussed here.
Define the contract before the provider payload
Start with the application operation. For a policy explanation, the input includes a question, authorized evidence, and an application request identifier. The output includes an answer, references to supporting evidence, a completion state, and measurement metadata. The adapter should not invent an authenticated user identity or grant new permissions based on text in the question.
Separate application fields from provider-specific fields. Your application can use one internal representation of question and evidence while adapters translate it into different message formats. This reduces the number of places that need changing when you compare models. It does not make all providers behaviorally interchangeable; supported roles, modalities, limits, and output features still differ.
Messages carry both content and context about their intended role. Your adapter should preserve the distinction between application instructions and user-supplied text using the selected interface's supported structure. A document saying ignore the rules remains document content. Formatting it clearly helps, but authorization must remain enforced by the application rather than relying solely on role labels.
Write a small input contract. Require a nonempty question, set a maximum input size, require stable evidence identifiers, and reject unknown fields that could be mistaken for trusted controls. Validate before a paid call. An invalid request should fail predictably without consuming a model request just to discover that an essential field was missing.
| Field or condition | Contract | Reason |
|---|---|---|
| Request ID | Server-generated stable identifier | Correlates events without using the prompt as a log key |
| Question | Nonempty text within a specified size bound | Rejects unusable input early |
| Evidence | Authorized passages with stable IDs and versions | Makes grounding inspectable |
| Deadline | One end-to-end time budget | Prevents each layer from spending a fresh full timeout |
| Answer status | Complete, unavailable, or failed | Avoids presenting partial text as a finished result |
| Citations | IDs drawn from supplied evidence | Allows reference membership checks |
| Identity | Supplied by authenticated server context | Prevents user text from selecting another account |
An input size limit in characters is easy to validate, but it does not replace token budgeting. Use both where appropriate: a coarse limit protects the interface, and a model-specific check protects the provider request. A short image attachment can also imply a large processing workload, so extend the contract deliberately before accepting new modalities.
Define error categories that callers can act on. Invalid input, missing credentials, provider unavailable, deadline exceeded, invalid output, and insufficient evidence mean different things. Do not collapse them into an empty answer. Equally, do not expose raw provider exceptions that may include sensitive request details. Return a stable public error and keep only necessary sanitized diagnostics.
Validate structure and meaning separately
A response may be valid JSON and still violate your task. Structural validation checks required fields, types, allowed values, and size limits. Semantic validation checks whether the content is supported and consistent with the application state. Both matter, but they establish different claims.
For example, an output object could require an answer string, a list of citation IDs, and a status from a small enumeration. An empty citation list may be permitted only for unavailable answers. A valid citation ID must also belong to the evidence supplied for this request. These rules should be explicit rather than inferred from whatever the model returns.
JSON Schema supports object properties, required fields, and controls on additional properties. Defining a property does not by itself require that it be present; express required fields explicitly. See the primary JSON Schema object reference when implementing the schema. Provider structured-output support may implement a subset or impose additional constraints, so validate at your own boundary as well.
Suppose the model returns a well-formed answer stating that an order has been refunded. Your schema can verify that the answer is a string. It cannot establish that a refund occurred. The application must compare action claims with trusted execution state or avoid giving the model responsibility for reporting action completion at all.
Likewise, checking that a citation ID exists is weaker than checking that the cited passage supports the claim. A response might cite the shipping policy for a return deadline. Membership validation catches invented IDs; evidence-support evaluation catches mismatched reasoning. Plan both without pretending either is a complete proof of correctness.
Reject or explicitly repair malformed output according to a bounded policy. If one repair attempt is allowed, count it in latency, cost, and attempt records. Preserve the original failure classification. Do not repeatedly prompt until valid JSON appears while reporting only the final successful call as though the application worked first time.
A repair request should contain only the information needed to correct the format, and it must not broaden authority. If the output invents an action field that the schema forbids, do not automatically add that field to the contract. Treat the mismatch as a failure to investigate. Contracts protect callers from unexpected behavior; changing them casually removes that protection.
Budget deadlines, retries, and partial responses
Use an end-to-end deadline for the task, then allocate time within it. Authentication, queueing, retrieval, model calls, validation, and response delivery all consume time. Giving each layer a separate full thirty-second timeout can turn a thirty-second product expectation into a much longer wait.
Network clients often distinguish connection, read, write, and connection-pool timeouts. HTTPX documents these as separate controls in its timeout reference. A read timeout commonly limits waiting for a portion of data, rather than defining your entire business-operation deadline. Therefore a bounded application needs an outer deadline as well as suitable transport timeouts.
A retry policy names which failures can be retried, how many attempts are allowed, what delay applies, and how much time remains. Retrying an invalid credential usually repeats the same configuration failure. Retrying after rate limiting without respecting an applicable delay can worsen overload. Retrying a timed-out mutation can create duplicates unless the operation has suitable idempotency protection.
For a text-only generation call, a timeout can still mean the provider performed work and charged for it. Record the outcome as unknown at that boundary if you lack a final response. A second call is a new attempt with its own possible cost. Do not describe a local timeout as proof that no remote computation occurred.
Streaming changes presentation and error handling. It can let the user see text sooner, but the first text is not necessarily a complete, validated answer. Define when the interface marks the response complete, what happens if the connection ends early, and whether a partial answer can be used. Structured output may remain invalid until the entire object arrives.
A safe classroom policy is to label streaming text as provisional and enable downstream actions only after the final validated result. If the stream fails, display an interrupted state and a controlled retry option. Preserve the request ID so the user does not confuse two attempts. Do not leave a spinner indefinitely or silently treat a partial sentence as success.
Cancellation is a request to stop local work; it is not a time machine. A user closing a page may cancel waiting tasks while remote computation or a previously submitted action continues. Your interface should distinguish abandoned presentation from confirmed cancellation of an external operation. Later tool lessons develop durable action records and reconciliation for this case.
Worked example
Allocate a request deadline and decide whether a retry fits
- A fictional endpoint promises to finish or return a controlled error within 12 seconds. Reserve one second for validation and response delivery, leaving 11 seconds for queueing and external work.
- The request spends two seconds waiting for a worker and one second retrieving evidence. Eight seconds remain for the model call before the final one-second reserve.
- The first model attempt times out after five seconds. Three seconds remain in the model allocation.
- A proposed retry policy requires a one-second delay and permits a three-second model attempt. It would need four seconds and therefore does not fit. Return a controlled failure instead of violating the deadline.
- If the first attempt had failed after three seconds, five seconds would remain. A one-second delay plus a three-second second attempt would fit, leaving one second unused within the model allocation.
- This calculation establishes only timing feasibility. You must still decide whether the failure is retryable and whether another attempt could duplicate a side effect or incur unacceptable cost.
Bound asynchronous work and overload
Asynchronous I/O lets a program make progress on other tasks while one task waits for a network operation. It does not make a slow provider inherently faster, and it does not remove limits on sockets, memory, rate quotas, or cost. Starting every request concurrently can turn a small performance problem into a larger reliability problem.
Choose a concurrency limit for in-flight calls and a separate bound on waiting work. A semaphore can limit active work, but an unlimited queue of tasks waiting for it still consumes memory and increases latency. Backpressure means the system communicates or enforces that it cannot accept more work at the current rate.
For a teaching service, a bounded queue can reject excess requests with a clear busy response. Another design may defer work into a durable job system. The choice depends on the task, but silently accumulating an unbounded backlog is rarely a useful contract. Include queueing time in the user's deadline rather than starting the clock only when the model call begins.
Python's task groups and timeout facilities provide ways to manage related asynchronous work. Task groups await their tasks and propagate failures under documented rules; cancellation-aware cleanup matters. Review the version-matched Python 3.11 asyncio task documentation before implementing P02. Do not copy APIs from a newer Python version into a project that claims older-version support without checking compatibility.
Independent read operations can sometimes run concurrently. Two policy lookups may be independent; creating a ticket and then fetching the newly created ticket are dependent. Running the latter together can produce a race. Draw the dependency before deciding to parallelize. Concurrency is appropriate when operations are independent and the resource budget allows it.
Cleanup belongs in the contract. When a request is cancelled, release its queue slot, close or return network resources, and avoid retaining a task forever. If an operation must continue after the user disconnects, give it an explicit owner and durable lifecycle. A task launched without a tracked result is difficult to inspect or recover.
Suppose six independent calls each take two seconds under a deliberately simplified fixed-duration model. Sequential execution takes twelve seconds. With a concurrency limit of two, three waves take six seconds. With a limit of three, two waves take four seconds. Real systems add overhead and contention, so these are schedule calculations, not performance promises.
Now suppose requests arrive at four per second while your service completes only three per second over a sustained interval. The backlog grows by roughly one request per second under these assumptions. After sixty seconds it contains about sixty additional requests unless you reject, defer, or add effective capacity. Raising a timeout hides the backlog temporarily; it does not resolve the throughput mismatch.
Keep credentials, identity, and observability at the right boundary
A provider API key belongs in server-side configuration, not in a browser bundle, a prompt, a lesson screenshot, or a committed repository file. A sample environment file should name required variables without containing a real secret. Validate configuration at startup so users receive a clear setup error rather than an unexplained failure after submitting a question.
Application authentication and provider authentication serve different purposes. A user's token identifies which application records they may access. The provider key allows the server to call a model service. Never let a customer choose another customer's identity by adding a field to a JSON body or saying a different name in chat.
The local reference maps two fixture tokens to two synthetic users. That is a teaching mechanism for isolation tests, not a production identity system. Its loopback restriction limits where the fixture service is intended to run. Before a real deployment, replace fixture identity handling with the appropriate authentication and authorization design rather than merely exposing the same port publicly.
Useful request metadata includes the request ID, operation, model configuration identifier, duration, outcome category, retry count, and usage values actually reported by the provider. If usage is absent, record it as unavailable. Do not invent token counts or costs to fill a dashboard. Pricing-based cost estimates also need a dated rate source and clear units.
A trace should explain the workflow without becoming a second uncontrolled copy of sensitive data. For many classroom checks, event names and stable synthetic IDs are sufficient. If raw prompts or outputs are retained for evaluation, make that an explicit artifact with a purpose and retention rule. Avoid printing environment variables wholesale while debugging a missing key.
Correlate events across attempts. One user request may contain two provider attempts and one validation failure. Record them under the same parent request with distinct attempt numbers. Otherwise a dashboard can count retries as independent user demand or hide the extra latency and cost behind a final success event.
Measure the experience the user receives. Model response time alone excludes queueing, retrieval, validation, and network delivery. Report end-to-end latency alongside component durations where they help diagnosis. A fast first token may improve perceived responsiveness while a slow final validated answer still blocks task completion.
Review the boundary with a failure matrix
Before implementation, write a small matrix of normal and abnormal cases. Include empty input, oversized input, missing credentials, invalid provider JSON, schema-valid but unsupported content, timeout, interrupted stream, cancellation, and overload. For each, state the public response, retry policy, logged metadata, and whether any action could have occurred.
This matrix turns vague reliability goals into observable behavior. For example, missing credentials should fail configuration without printing the credential value. An interrupted stream should end in an interrupted status rather than complete. An overload response should occur within a bounded time and should not consume an unbounded waiting slot.
Test the adapter with controlled fake responses before paying for live calls. A fake transport can return malformed JSON, sleep beyond a deadline, or raise a connection error deterministically. These tests establish application behavior under injected conditions. They do not measure a real model's quality, provider availability, or latency. Label those claims separately.
Then perform a small live smoke test if credentials and authorization are available. Verify the documented endpoint, selected model, supported payload, and actual response fields. Keep the test narrow and bounded. A successful smoke test confirms integration for that case; it does not replace the larger task evaluation or the failure tests.
Version the contract together with the adapter. If you add a new status or change the interpretation of an absent citation, update callers and tests deliberately. A schema change can break the interface even when the model produces better prose. Compatibility is an application concern independent of language quality.
For P02, the deliverable is a working adapter plus evidence that its contract holds under selected failures. The main lesson's design work should make implementation choices easier: what is trusted, what is validated, how long you wait, what can be retried, and how the user knows whether a result is complete.
Exercise
A response contains an answer string, citation ID P9, and status complete. P9 is not among the evidence IDs supplied for this request. The JSON schema passes. Should the application accept it? Specify the failure and a bounded recovery option.
Check your answer
Reject it as an invalid citation or grounding failure under the contract. Structural validity does not establish evidence membership. A bounded recovery may allow one reformulation using only supplied IDs if enough deadline and budget remain, or return a controlled unavailable result with verified excerpts. Do not silently add P9 to the evidence list or present the original result as fully supported.
Exercise
Eight independent read calls each take exactly three seconds in a simplified schedule. Calculate completion time with concurrency limits one, two, and four. The service permits at most four active calls and four waiting calls. What should happen to a ninth simultaneous request?
Check your answer
The simplified times are 24 seconds, 12 seconds, and 6 seconds respectively. Four active plus four waiting requests fill the stated capacity. The ninth request should receive the documented busy response or enter an explicitly separate durable deferral mechanism; it must not silently expand the bounded in-memory queue. Real measurements may differ because of overhead and shared-resource contention.
Exercise
A customer closes the browser after approving a ticket. The server's tool call times out, and the interface has no final result. A developer wants to submit a fresh ticket request immediately. Explain the uncertainty and name three pieces of state required for a safer recovery.
Check your answer
The timeout and closed browser do not prove that the external ticket was not created. Preserve the approved action ID, the idempotency key used for the attempt, and the last confirmed execution status or result. Reconcile or retry using the same operation identity under the tool contract. Do not create a new operation identity merely because the first response was lost. Record the attempt as uncertain until authoritative evidence resolves it.
Test omissions as well as wrong values
The JSON Schema object reference distinguishes defining a property's shape from requiring its presence. It also allows extra properties by default unless the schema constrains them. These defaults matter when a downstream caller interprets a missing decision or an unexpected field as permission to proceed.
Create boundary fixtures from the consumer's assumptions. For each field, decide whether absence, null, an empty string, and an unknown enum value have distinct meanings. Reject contradictory states explicitly. A well-formed response with decision “approved” and an empty evidence list may still violate your product contract.
Worked example
Find an interface failure before a model call
- A synthetic application expects a decision and an evidence list. Its schema defines both properties but omits the required list.
- An empty object passes that structural schema. The application then supplies a default decision, accidentally turning missing output into an action.
- Add the required fields and a defined policy for unexpected fields, then rerun empty, null, extra-field, and wrong-type fixtures.
- Add a separate semantic check: an approval requires at least one valid evidence identifier from this request.
- Return a typed validation failure before execution. These fixtures need no paid inference and do not prove that future model responses will be correct.
Exercise
The returned evidence list contains a syntactically valid ID, but that ID was never supplied in the request. Which boundary should reject it?
Check your answer
The application's semantic validation should compare the ID with the authorized evidence packet. A string type or pattern check cannot prove that the evidence exists, was supplied, or supports the decision.
Sources and further reading
JSON Schema object contracts. Review object properties, required fields, and extra-field handling.
Summary
Define inputs, outputs, timing, and failures before connecting a provider. Validate structure and meaning separately. Use an end-to-end deadline, bounded retries, bounded concurrency, and explicit overload behavior. Keep identity and credentials server-side, mark partial results honestly, and record enough sanitized metadata to explain each attempt without leaking secrets.
Next action
Complete P02, Build a Model-Powered Application, including controlled failure fixtures. Then continue to Defining Quality and Acceptance Criteria: a reliable interface is necessary, but you still need evidence that the application completes the intended task correctly.