Explain Missed Cards with a Language Model
A language model is a program on another computer that reads text and writes an answer. Calling one from Python takes only a few lines with a package made for the job. What makes those lines useful is what you put into the request, and what the program does when no answer comes back: a call over the network can fail, and one missing answer should never stop the whole program.
A client that sends the request for you
Sending a request by hand means writing the URL, the headers, the JSON body and then digging the answer out of the JSON that comes back. A client package does that work for you: it is a third-party package whose functions build the request, send it and turn the response into a Python object.
For language models, the most widely used one is the openai package. It sends requests in the Chat Completions format, and that format is accepted by many model providers and local model servers, not only by OpenAI. So the same code talks to any server that understands the format, which is why it is called an OpenAI-compatible client.
You add it to a project like any other package (uv add openai), and in the program you import one class from it, OpenAI. Calling that class makes a client, an object that remembers two things for every request it will send:
- the base URL, the address of the server, ending at its version folder, such as
http://localhost:8000/v1. The client adds the rest of the path (/chat/completions) itself; - the API key, the secret that says who is calling, which the client puts into a request header for you.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ["LLM_API_KEY"],
)The two values come from environment variables, so the secret key stays out of the code. The names of those variables are your choice. Left to itself, the client looks only at variables called OPENAI_API_KEY and OPENAI_BASE_URL. With names of your own, you read the values yourself and pass them in by name, as above.
Because the server's address is just a setting, changing the base URL is all it takes to point the same program at another provider or at a model running on your own computer. One thing does not change: even a server that ignores keys still needs some key that is not empty. With no key at all, making the client raises openai.OpenAIError ("Missing credentials") before anything is sent.
Making the client only stores these settings. The request goes out when you call client.chat.completions.create with two arguments: model, the name of the model on that server, and messages, the text you send. The diagram follows one such call.
- Your program
- openai client
- Model server
- Your program to openai client: create(model, messages)
- openai client to Model server: POST base URL + /chat/completions
- Model server to openai client: status 200, JSON body
- openai client to Your program: a completion object
What comes back is not a dictionary but an object, so its parts are read with dots, the same way you read the attributes of any object. The answer sits a few steps down: choices is a list of possible answers, [0] picks the first, its message is the model's reply, and content is the text of that reply, a string.
- completion the object returned
- .choices a list
- [0] the first item
- .message role: assistant
- .content the answer text
- completion to .choices
- .choices to [0]
- [0] to .message
- .message to .content
completion = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": "Say hello in French."}],
)
answer = completion.choices[0].message.content
print(answer)The model name is read from a setting too, so a new server or a new model needs no change to the code. The printed answer depends on the model: a real model writes new words on each run, so two runs rarely print exactly the same text.
True or false?
Making the client with a wrong API key raises an error at once.
False. Making the client sends nothing, so a wrong key is noticed only when create sends the request and the server rejects it. Only a missing or empty key fails when the client is made.
The answer text is read with dots and one index, as completion.choices[0].message.content.
True. The client returns an object. Brackets with names in quotes fit raw JSON read by hand, not this object.
The client reads a setting called LLM_API_KEY from the environment by itself.
False. On its own it looks only at OPENAI_API_KEY and OPENAI_BASE_URL. Settings with other names are passed in as arguments.
Messages and roles
The messages argument is a list of dictionaries, one dictionary per message. Every message has the same two keys: role, which says who is speaking, and content, the text itself. The model reads the whole list in order before it answers.
Two roles cover most requests. A system message sets the rules for the answer: how long it may be, what tone to use, what to leave out. A user message carries the request itself. Splitting them keeps the rules fixed while the request changes from call to call. The model gives the system message more weight than the user message and usually follows it, but that is not a guarantee: a user message can still lead the model away from its rules. The reply the model writes has a third role, assistant, which is why message.role in the answer is "assistant".
| role | Who writes it | What it holds |
|---|---|---|
| system | the program | the rules for every answer |
| user | the program, for the person | this one request |
| assistant | the model | the reply that comes back |
messages = [
{
"role": "system",
"content": "You explain things to beginners in two short sentences.",
},
{
"role": "user",
"content": "Why does ice float on water?",
},
]OpenAI's own newer examples sometimes use a role called developer for the rules. The Chat Completions format still documents system, and it is the role that OpenAI-compatible servers in general understand.
True or false?
Each message is a dictionary with the keys role and content.
True. The list holds one dictionary per message, and every one of them has these two keys.
A user message is the place for rules that should stay the same on every call.
False. Rules that stay the same go in the system message; the user message carries the request that changes from call to call.
Building the prompt from data
The prompt is the text you send the model. A prompt written once, as a fixed string, gets a general answer: ask "What should I wear today?" and the model knows nothing about your day, so it can only talk about weather in general. The program, though, often holds exactly the details that matter, in its variables. Putting those values into the prompt turns a general question into a question about this case.
An f-string does the job: the text of the question with the values put in at their places. The same line of code then writes a different prompt every time the values change.
prompt = "What should I wear today?"city = "Oslo"
temperature = -3
rain = True
prompt = (
f"I am in {city}. It is {temperature} degrees "
f"and rain is expected: {rain}. "
"What should I wear today?"
)The built prompt reads "I am in Oslo. It is -3 degrees and rain is expected: True. What should I wear today?", and the model can now answer about a cold, wet day in one city. The rules stay in the system message; only the user message is built from the data. Wrapping both in a function with parameters makes the pattern reusable: each call passes the values of one case and gets back the text of an answer about that case.
def clothing_advice(city: str, temperature: int) -> str:
messages = [
{"role": "system", "content": "Answer in one short sentence."},
{
"role": "user",
"content": f"I am in {city} and it is {temperature} degrees. "
"What should I wear?",
},
]
completion = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=messages,
)
return completion.choices[0].message.contentThe model sees only what the messages hold. A detail the program knows but leaves out of the prompt does not exist for the model, so the useful question when building a prompt is which values the answer depends on.
True or false?
The model can read the variables of the program that calls it.
False. Only the text in the messages travels to the server. A value reaches the model only when the program puts it into a message.
One f-string in a function can produce a different prompt for every call.
True. The f-string is filled in each time the line runs, with the values the parameters hold in that call.
When the call fails
A call to a model travels over a network to another computer, and many things there are outside your control. The server may be switched off, the address may be wrong, the key may be rejected. In each case the client raises an exception during the call to create, and an exception that nothing handles stops the program, with everything after that line left undone.
The client names two kinds of failure with two exception types, both found in the openai module:
openai.APIConnectionError: no answer arrived at all. The server could not be reached, or it took too long (a timeout,APITimeoutError, is one kind of connection error).openai.APIStatusError: the server answered, but with a status code that is not success (400 or higher). The exception keeps that code in itsstatus_codeattribute.
Each common status code also has its own, more specific type: a rejected key (401) raises openai.AuthenticationError, a missing address (404) raises NotFoundError, and too many requests (429) raise RateLimitError.
Together these types form a family tree, drawn below with two of the specific types (NotFoundError sits beside them). A type drawn under another is a special case of it: an AuthenticationError is also an APIStatusError. That is why an except for a type also catches every type under it.
- APIError any failed call
- APIConnectionError no answer
- APITimeoutError too slow
- APIStatusError 400 or higher
- AuthenticationError 401
- RateLimitError 429
- APIError to APIConnectionError
- APIConnectionError to APITimeoutError
- APIError to APIStatusError
- APIStatusError to AuthenticationError
- APIStatusError to RateLimitError
Handling them follows the same try and except pattern as any other expected error: the call goes inside try, and each except names one type and says what to do instead. Writing as error after a type gives the caught exception a name, so its attributes can be read.
The order of the except lines matters. Python checks them from the top and runs the first one that matches, so a specific type must come before the more general type above it in the tree. Put APIStatusError first and it would also catch every rejected key, and the line for AuthenticationError would never run.
import openai
def clothing_advice(city: str, temperature: int) -> str:
messages = [
{"role": "system", "content": "Answer in one short sentence."},
{"role": "user", "content": f"I am in {city} and it is {temperature} degrees."},
]
try:
completion = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=messages,
)
except openai.APIConnectionError:
return "No advice: the model server could not be reached."
except openai.AuthenticationError:
return "No advice: the server rejected the API key."
except openai.APIStatusError as error:
return f"No advice: the server answered with status {error.status_code}."
return completion.choices[0].message.contentWhatever happens, the function returns a string, and the code that called it carries on: it prints the advice or the short explanation, and the rest of the program still runs to its end. The program has lost one answer, not its whole run. The except lines name only the client's own exception types, so a real bug in your code, such as a misspelt variable name, still stops the program with its traceback instead of hiding behind a friendly message.
Two details explain what you see while testing this. The first is that some failures are tried again before you hear about them. By default the client retries connection errors, timeouts, 429 and server errors (500 and above) twice, waiting a little longer each time. So an unreachable server takes a moment before APIConnectionError arrives. A rejected key (401) is not retried and fails at once. The number of retries is set when the client is made, as in OpenAI(max_retries=0).
The second detail is the missing-key error raised while making the client. Its type is openai.OpenAIError, the type above APIError, and it happens before any call, so the except lines around the call do not catch it.
True or false?
except openai.APIConnectionError also catches a request that timed out.
True. APITimeoutError sits under APIConnectionError in the tree, so the more general type catches it too.
The order of the except lines does not matter, since Python picks the best match.
False. Python runs the first except that matches, from the top. A general type placed first catches the specific cases below it.
A server switched off makes the client try again before the program sees an error.
True. Connection errors are retried twice by default, with a short wait between tries, before APIConnectionError reaches the program.
Catching every exception with a bare except is the safest way to keep the program running.
False. It also hides real bugs in your own code. Naming the client's exception types handles the expected failures and lets the rest show.