Sub topic 5
Isolating the Model Call Behind One Function
This chapter assumes you can write Python functions, work with lists and dictionaries, and handle exceptions. You should also know the basic idea of a chat API: you send messages and get a reply back.
Why one function
A chat program touches the model in exactly one place: the moment it sends the history and receives text. If you put that call inside the input loop, provider details spread through your code. These include the SDK import, the API key, the model name, and the response format. Changing providers or writing a test then means editing the loop.
The fix is a single function with a narrow contract:
- Input: a list of message dictionaries, each with a
roleand acontentkey. - Output: the reply as a plain string.
- Failure: it raises an exception.
Everything else in the program depends only on that contract.
The function in the loop
The chat loop from the earlier chapter already uses this shape:
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 NotImplementedErrorThe loop calls reply = complete(history) and never looks inside it. The body is the only part you rewrite for a specific provider. Most SDKs follow the same pattern. You create a client, pass the messages and a model name, and read the text out of the response object. Reading the text out is part of complete()'s job. The loop should receive a string, not a provider-specific object.
What belongs inside
Put these inside complete(), or in helpers that it calls:
- Client creation and the API key, read from an environment variable and never hard-coded.
- The model name and settings such as maximum reply length.
- Converting your message format if the provider needs a different one. Some providers take the system prompt as a separate argument instead of a message.
- Extracting the reply text from the response.
Keep these outside it:
- Changes to the history. The caller appends the user message and the reply.
- Printing. The function returns text, and the loop decides what to do with it.
- Trimming and saving.
A function that only maps messages to text is easy to replace and easy to test.
Passing the function in
The loop can call a module-level complete() directly. A more flexible design passes the function in as an argument:
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 replyHere complete is a parameter, so run_turn works with any function that follows the contract. In production you pass the real one. In a test you pass a fake. If the call fails, the user message is removed, so the history never ends with an unanswered user turn. Later chapters cover that failure handling and the tests in detail.
Common mistakes
- Returning the raw response object. The loop then needs provider knowledge, which defeats the isolation. Return a string.
- Catching every exception inside
complete()and returning an error message as text. The error would then be saved in the history as if the assistant had said it. Let exceptions propagate so the caller can decide. - Mutating the list that was passed in. If you need to modify messages for a provider, build a new list.
- Hard-coding the key. Read it from the environment.
Exercise
Why should complete() return a plain string and raise an exception on failure, instead of returning an error message as text?
Show answer
A string keeps the loop independent of any provider's response format. If errors were returned as text, the loop would append them to the history as assistant replies, and they would be sent to the model on later turns. Raising an exception lets run_turn remove the pending user message and leave the history valid.
Exercise
Write a fake complete function for testing that always returns the text of the last user message in uppercase.
Show answer
lambda messages: messages[-1]["content"].upper()