A model call with an honest boundary.
Wrap a fallible generator in a small response contract and distinguish transport success from task success.
Why this workflow exists.
A hosted model SDK can make generation look like a normal function call. This example reveals what the rest of the application should actually receive: an explicit status and a candidate text value. That shape lets the interface tell a user when the service is unavailable or when the response cannot be interpreted.
The model stand-in returns a small dictionary. In a real application, only that adapter would know the provider's response format. The rest of the product would depend on the stable result contract shown here.
Code context. Python 3 standard library only. The local model function is a stand-in, so the workflow runs without an account or API key.
The whole example.
def local_model(messages):
if not messages:
return {"text": ""}
return {"text": "I found a draft answer for: " + messages[-1]["content"]}
def generate_candidate(model_call, messages):
try:
response = model_call(messages)
except TimeoutError:
return {"status": "unavailable", "text": None}
if not isinstance(response, dict):
return {"status": "invalid", "text": None}
text = response.get("text")
if not isinstance(text, str) or not text.strip():
return {"status": "invalid", "text": None}
return {"status": "candidate", "text": text.strip()}
request = [{"role": "user", "content": "Where is the access guide?"}]
print(generate_candidate(local_model, request))What each stage does.
The request is a list of messages, each with a role and content. local_model simulates a provider response. generate_candidate catches one transport failure, checks the response type, then checks for nonempty text. Every exit path returns the same keys, so the caller can render the state reliably.
The word candidate is deliberate. A text response might be fluent and still fail to answer the user's question. Another component must check that the answer uses permitted evidence and fits the task. A real adapter would handle the provider's timeout, authentication, and rate-limit errors explicitly.
What the output means.
The printed dictionary has status candidate and a draft text value. It shows that the application successfully obtained text. It makes no claim that the draft is true or supported.
Where the example stops.
The stand-in does not perform inference. It isolates the application contract so the lesson remains runnable and stable across model vendors. Replace only local_model with a provider adapter after choosing a service and reviewing its current API and data terms.