Sub topic 5
Isolating the Model Call Behind One Function
This chapter assumes you can write Python functions, lists, dictionaries, and try/except blocks, and that you know a chat API takes a list of messages and returns a reply. You should also have the terminal loop and message history from earlier chapters.
By the end you will have a single function, complete(messages), that is the only place your program talks to a model. Everything else in the chatbot calls this function and never touches a provider SDK.
Why one function
A chat model API is stateless. Every request must carry the whole conversation, and every response is a new piece of text. That makes the contract between your program and the model small:
- Input: a list of messages, each a dictionary with
roleandcontent. - Output: the reply text, as a string.
If you keep that contract narrow, the rest of your program does not need to know which provider you use, how you authenticate, or what the response object looks like. Hiding those details behind one function gives you four benefits:
- Swapping providers means editing one function body.
- Testing is easy, because you can pass in a fake function that returns canned text.
- Error handling has one place to translate provider-specific exceptions into your own.
- Later features such as streaming, retries, and logging have one obvious home.
The contract
Define the function's contract before writing its body.
| Part | Rule |
|---|---|
| Parameter | `messages`, a list of dictionaries with `role` and `content` string keys |
| Return value | The assistant's reply as a plain `str` |
| Side effects | None on `messages`. The function must not modify the list. |
| Failure | Raises an exception. It never returns an error message disguised as a reply. |
The last two rules matter most. If complete() appended the reply to the history itself, the caller and the function would both own the history, and bugs would follow. If it returned the string "Error: timeout" on failure, the chat loop would store that string as if the assistant had said it, and the model would read its own error text on the next turn.
A skeleton you can run
This is the placeholder from the chat loop. It has the right signature and fails loudly until you fill it in.
def complete(messages):
"""Send the full message list to a model and return the reply text.
Replace this body with a call to your chosen provider's SDK."""
raise NotImplementedErrorRaising NotImplementedError is deliberate. A function that quietly returns an empty string would let the loop run and hide the fact that no model is connected.
Filling in the body
Every provider SDK differs in names, but the shape of the work is the same. Your function does three things:
- Convert your messages into the format the provider expects.
- Make the request.
- Extract the reply text from the response object.
Here is a sketch of that shape. The client and its method names below are placeholders for your provider's real ones, so check its documentation for the exact calls.
import os
class ModelError(Exception):
"""Raised when the model call fails for any reason."""
def make_complete(client, model_name):
"""Build a complete() function bound to a client and model name."""
def complete(messages):
payload = [
{"role": m["role"], "content": m["content"]} for m in messages
]
try:
response = client.send(model=model_name, messages=payload)
except Exception as exc:
raise ModelError(f"model call failed: {exc}") from exc
text = response.text
if not isinstance(text, str) or not text.strip():
raise ModelError("model returned an empty reply")
return text
return complete
class _DemoClient:
"""Stand-in client so this example runs without a provider."""
class _Response:
def __init__(self, text):
self.text = text
def send(self, model, messages):
last = messages[-1]["content"]
return self._Response(f"[{model}] you said: {last}")
if __name__ == "__main__":
complete = make_complete(_DemoClient(), os.environ.get("MODEL_NAME", "demo"))
print(complete([{"role": "user", "content": "hello"}]))Run it and you should see [demo] you said: hello. To use a real provider, replace _DemoClient with the provider's client and adjust the two lines that send the request and read the text.
Three design choices in this sketch are worth explaining.
A factory instead of a global
make_complete returns a function that remembers client and model_name. The chat loop still sees the simple complete(messages) signature. You avoid module-level globals, and tests can build a complete around any client they like.
Copying the messages
The list comprehension builds a new list of new dictionaries. This does two things. It strips any extra keys you may add later to your own history entries, such as timestamps, which many providers reject. It also guarantees that nothing in the SDK can mutate your stored history.
One exception type
The function wraps every failure in ModelError. The chat loop can then write except ModelError and does not need to know about the provider's timeout, rate-limit, or authentication exception classes. The from exc keeps the original error attached, so tracebacks still show the real cause.
Keeping secrets out of the function
Most providers need an API key. Read it from an environment variable when you build the client, not inside complete() and never as a string literal in your source file.
import os
def read_api_key(name="MODEL_API_KEY"):
key = os.environ.get(name)
if not key:
raise SystemExit(f"Set the {name} environment variable first.")
return keyFailing at startup with a clear message is better than failing on the first user message with an authentication error.
Wiring it into the loop
The chat loop from earlier chapters calls complete(history) directly. That still works. The better form passes complete in as a parameter, so the loop never imports a provider at all:
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except Exception:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return replyThis function does not know whether complete is a real model or a fake. The next chapters use that fact for error handling and tests.
Common mistakes
- Returning the raw response object. The caller then needs provider knowledge to read it. Return a string.
- Mutating the history inside
complete(). Keep appends in the loop, where the history is owned. - Catching exceptions and returning text. Errors become fake assistant messages and pollute later turns.
- Putting
input()orprint()in the function. It then cannot be tested or reused. Keep it free of terminal code. - Hard-coding the model name. Pass it in, or read it from configuration, so you can change it without editing logic.
- Forgetting timeouts. Many SDKs wait a long time by default. Set a timeout on the client so a stalled network does not freeze the terminal.
Looking ahead
Because the contract is only "messages in, string out," later features slot in without changing the loop. Streaming will need a variant that yields pieces of text, which you can add beside complete() as a second function. Retries can wrap complete() in a small decorator. Summarization will call complete() itself with a different message list. None of these require the chat loop to learn anything about the provider.
Exercise
A teammate writes complete() so that, on a network timeout, it returns the string "Sorry, something went wrong." instead of raising. The chat loop appends whatever complete() returns as the assistant message. Give two problems this causes and say how to fix the function.
Show answer
First, the apology is stored in the history as if the assistant said it, so the model sees it on every later turn and the saved JSON file contains it permanently. Second, the loop cannot tell failure from success, so it cannot remove the user's message, retry, or show a distinct error to the user. The fix is to raise an exception (for example ModelError) on failure, return only genuine reply text on success, and let the chat loop catch the exception, remove the pending user message, and print the error to the terminal without touching the history.
Exercise
Write a fake complete() for use in a test that returns the text "echo: " followed by the content of the last message, and explain why it satisfies the same contract as the real function.
Show answer
def fakecomplete(messages): return "echo: " + messages[-1]["content"] It takes a list of role/content dictionaries, returns a plain string, does not modify the list, and raises only on real failure. Because runturn depends only on that contract, it cannot tell the fake from the real function.