Your First Call to a Language Model
A language model that a program can use usually runs on someone else's servers, and a Python script reaches it the same way it reaches any web service: it sends a request and reads the response. Knowing what goes into that request, what comes back, where the request is sent and how the key that pays for it stays private is the foundation for every application built on a model.
A model behind an HTTP endpoint
A large language model (LLM) is a program that reads text and writes text that continues it. Running one takes a lot of memory and specialised hardware, so most applications do not run the model themselves. A provider runs it on its servers and offers it through an API (application programming interface): an address on the web, called an endpoint, that accepts requests in a fixed format.
Your script sends an HTTP request to that endpoint. The body of the request is JSON that holds the text for the model. The server runs the model and sends back an HTTP response, also JSON, that holds the text the model wrote. From the script's side it is an ordinary web request: no model is installed on your machine, and the script waits while the server does the work.
- your Python script
- provider's server
- request: text + key
- response: reply + usage
Every request also carries an API key, a long secret string that tells the provider who is asking. It travels in an HTTP header, Authorization: Bearer <key>, and the provider uses it to allow the request and to bill the right account.
The bill is counted in tokens. A model does not read text letter by letter or word by word: it reads and writes small pieces of text called tokens. For English text, one token is on average about four characters, or about three quarters of a word, and that is only an estimate.
Providers count two kinds of tokens: the tokens of the text you send (the input) and the tokens the model writes (the output). They charge for both, usually at a price stated per million tokens, and output is often priced differently from input. So a longer question and a longer answer both cost more. You do not have to guess the counts: the response tells you exactly how many tokens the call used.
True or false?
To call a hosted language model from Python, the model must first be downloaded to your computer.
False. The model runs on the provider's servers. Your script only sends an HTTP request with text and reads the reply that comes back.
A call that sends a long text and gets a short answer is still billed for the long text.
True. Input tokens are counted and billed as well as output tokens, so everything you send has a cost, not only what the model writes.
One request format, many providers
Each provider could invent its own request format, and some have their own native one. But one format became a common language: Chat Completions, defined by OpenAI. A Chat Completions request is sent to a path ending in /chat/completions and holds a model name and a list of messages; the response holds the model's reply in a fixed shape. Many other providers, and local servers that run a model on your own machine, accept requests in this same format. Such a server is called OpenAI-compatible.
Because the format is shared, one client library can talk to all of them. The official openai Python package sends Chat Completions requests to whatever address it is given. Three settings decide where a request goes and what answers it:
- the base URL, the start of the endpoint's address; the client adds the path such as
/chat/completionsto it; - the API key for that provider;
- the model name, which picks one of the models that provider offers.
Change those three values and the same script talks to another provider. These are the base URLs some providers document for their OpenAI-compatible endpoints:
| Provider | Base URL | Worth knowing |
|---|---|---|
| OpenAI | https://api.openai.com/v1 | the default of the openai client |
| Google Gemini | https://generativelanguage.googleapis.com/v1beta/openai/ | compatibility is in beta |
| Anthropic | https://api.anthropic.com/v1/ | meant for testing and comparing; ignores most unsupported fields |
| Groq | https://api.groq.com/openai/v1 | rejects some unsupported fields with an error |
| Ollama (local) | http://localhost:11434/v1/ | needs a key value but ignores it |
Compatible does not mean identical. Each server supports a subset of the format, and an option one provider accepts may be rejected by another with an error, or silently ignored. A script that sticks to the core of the request (a model name and messages) works almost everywhere; anything beyond that is worth checking in the provider's own documentation.
The newer Responses API
OpenAI, which defined Chat Completions, has since added a second API called Responses. Its own documentation now calls Responses its primary API and recommends it for new projects, while Chat Completions stays supported indefinitely. The two differ in shape:
| Aspect | Chat Completions | Responses |
|---|---|---|
| What you send | a list of messages | a list of items; a message is one kind of item |
| What comes back | choices, each holding a message | an output list of items |
| Earlier turns | your code sends them again | can refer to an earlier response by its id |
| Offered by | OpenAI and most compatible servers | OpenAI and only some compatible servers |
That last row decides the choice for a program meant to run against many providers. Some compatible endpoints document only Chat Completions, and others offer Responses only in part (Ollama, for example, supports it without the stored, stateful features). Chat Completions is the format that the widest range of providers and local servers accept, which is why it is the one this page explains.
True or false?
With the openai package, you can call a model from another provider by changing the base URL, the key and the model name.
True. When that provider offers an OpenAI-compatible endpoint, these three settings are what decide where a request goes and which model answers it.
Every OpenAI-compatible server also offers the Responses API.
False. Several compatibility layers document only Chat Completions, and some offer Responses only in part. Chat Completions is the format they share.
Chat Completions has been deprecated in favour of Responses.
False. OpenAI recommends Responses for new projects but states that Chat Completions remains supported indefinitely.
Keeping the API key secret
Anyone who has your API key can send requests that are billed to your account. That makes the key a secret like a password, and the main risk is careless storage: a key typed straight into a script ends up wherever the script goes, and committing it to a code repository is one of the most common ways keys leak.
The usual practice is to keep the key out of the code entirely. The program reads it from an environment variable, a named value that the operating system hands to every program it starts. Setting environment variables by hand in every terminal is tedious, so projects keep them in a plain text file named .env next to the code, one NAME=value line each:
LLM_BASE_URL=https://api.openai.com/v1
LLM_API_KEY=paste-your-key-here
LLM_MODEL=a-model-name-from-your-providerThe .env file never goes into version control. Adding its name to .gitignore tells Git to leave it out of every commit, so the code can be shared while the key stays on your machine. A common habit is to commit a copy named .env.example with the same names and empty or dummy values, so others know which settings to fill in.
The file does nothing by itself. A program has to load it, and the python-dotenv package does that with one call: load_dotenv() looks for a .env file in the script's folder or a folder above it and adds each line to os.environ, the dictionary of environment variables in Python. A variable that is already set in the environment is kept as it is, because by default load_dotenv() does not override existing values.
import os
from dotenv import load_dotenv
load_dotenv() # copies the lines of .env into os.environ
base_url = os.environ["LLM_BASE_URL"]
api_key = os.environ["LLM_API_KEY"]
model = os.environ["LLM_MODEL"]Reading with os.environ["NAME"] raises a KeyError when a setting is missing, so a forgotten line in .env stops the program at once with the name of what is missing, instead of failing later in a less obvious way.
True or false?
The openai client finds and reads a .env file on its own.
False. The client only reads the process environment, and only under its own names, such as OPENAI_API_KEY and OPENAI_BASE_URL. A .env file must be loaded first, for example with load_dotenv(), and settings under other names must be passed to the client.
If LLM_API_KEY is already set in the terminal, load_dotenv() keeps that value even when .env holds a different one.
True. By default load_dotenv() does not override variables that already exist, so the value from the environment wins.
The request: a model and a list of messages
With the settings loaded, the script creates a client and sends a request. The client is created with the base URL and the key, so every call it makes goes to that endpoint with that key. The call itself, client.chat.completions.create, needs only two things: the model to use and the messages to send.
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ["LLM_API_KEY"],
)
completion = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[
{"role": "user", "content": "In one sentence, what is an API?"},
],
)
print(completion.choices[0].message.content)Without arguments, OpenAI() would read its key from the environment variable OPENAI_API_KEY and its address from OPENAI_BASE_URL, falling back to OpenAI's own base URL when that is not set. Passing base_url and api_key explicitly is what lets settings under any names point the client at any provider. A local server such as Ollama ignores the key, but the client still requires one, so any placeholder value works there.
The messages list is the conversation so far, and it must hold at least one message. Each message is a dictionary with two keys:
rolesays who the message is from."user"is the person asking. Other roles exist:"assistant"for the model's own earlier replies, and"system"(or"developer"on newer OpenAI models) for standing instructions from the application.contentis the text of the message.
The model reads the whole list and writes the next message in the conversation. Every other parameter of the call is optional, and since providers differ in which options they accept, a request with only a model and messages is the one most likely to work on any compatible endpoint. Under the hood, the client turns this call into an HTTP POST to the base URL plus /chat/completions, with the model and messages as the JSON body and the key in the header.
True or false?
A Chat Completions request can be sent with an empty messages list, since the model already knows what to say.
False. The messages list must contain at least one message: it is the only text the model has to respond to.
The same model name can be invalid on another provider even when both endpoints are OpenAI-compatible.
True. Each provider offers its own models under its own names. The format is shared, the list of models is not.
The response: choices, finish reason and usage
The endpoint answers with a JSON object, and the client turns it into a Python object whose fields are read as attributes. Its shape looks like this; the reply text and the token counts are different on every call:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1763690000,
"model": "the-model-that-answered",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "An API is a defined way for one program to request data or actions from another."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 18,
"total_tokens": 33
}
}The top fields identify the call: an id, the time it was created (in seconds since 1970) and the model that answered. The three parts a program actually works with are the choices, the finish reason and the usage.
Choices and the message
choices is a list because a request can ask for several alternative replies. By default there is exactly one, so the reply is at completion.choices[0]. Each choice holds a message shaped like the messages you send: its role is always "assistant", and its content is the text the model wrote. That is why the first call printed completion.choices[0].message.content. The content can also be None, when the model's turn holds something other than text (a request to run a tool, for example), so code that uses it should not assume a string is always there.
The finish reason
Each choice has a finish_reason that says why the model stopped writing. It tells you whether the text is complete before you rely on it:
| finish_reason | Why the model stopped |
|---|---|
| stop | it reached a natural end, or a stop sequence given in the request |
| length | it hit the maximum number of tokens set for the reply, so the text is cut off |
| tool_calls | it asked for a tool to be run instead of answering in text |
| content_filter | content was left out by the provider's content filter |
Usage
usage holds the token counts of the call. prompt_tokens counts the input: every message you sent, plus the small amount of formatting the provider adds around them. completion_tokens counts the output the model generated, and total_tokens is the sum of the two.
These are the numbers the provider bills. A program can read them with completion.usage.prompt_tokens and completion.usage.completion_tokens to keep track of what its calls use. Some providers add more detail in nested fields, and the whole usage field is optional in the format, so a careful program checks that it is present before reading it.
True or false?
A finish_reason of "stop" means the request contained a stop sequence.
False. It also means the model ended its reply on its own, which is the usual case. A stop sequence is only one of the two ways to get it.
If finish_reason is "length", the text in message.content may end in the middle of a sentence.
True. The model was stopped by the token limit for the reply, not because it had finished, so the text is incomplete.
prompt_tokens counts only the last message in the list.
False. It counts the whole input: every message sent in the request, since the model reads all of them.
total_tokens is prompt_tokens plus completion_tokens.
True. The total is the input and the output of the call added together.