Sub topic 1
What an LLM API Call Is: HTTP, JSON and Endpoints
Prerequisites
This chapter assumes you can do the following:
- Write basic Python or a similar language.
- Read JSON.
- Recognize HTTP status codes such as 200 and 404.
- Set environment variables and use a terminal.
The working model
Calling a hosted large language model (LLM) is an ordinary web request. Your program sends an HTTP request to a URL. A server runs the model and sends back an HTTP response. No special protocol is involved. Anything that can send HTTP can call an LLM.
Four parts make up the exchange:
- Endpoint: the URL that accepts the request. This tutorial uses
https://api.openai.com/v1/chat/completions. - Method: the HTTP verb. Chat requests use
POST, because you send a body. - Headers: metadata such as
Content-Type: application/jsonand credentials. - Body: a JSON document that holds the model name, the messages and any settings.
The response has a status code, headers and a JSON body that holds the generated text.
A first request with curl
The request below sends one question. The model name comes from the LLM_MODEL environment variable, so it is not hard-coded. Credentials are covered in the next chapter. For now, note that the key is also read from the environment.
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"model": "$LLM_MODEL",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API key is in one sentence."}
]
}
EOFThe -d @- option tells curl to read the body from standard input. The here-document (<<EOF) supplies that input and lets the shell insert $LLM_MODEL.
The same call in Python
Python's requests library does the same work. Its json= argument converts a dictionary to JSON and sets the content type for you.
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in one sentence."},
],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
choice = data["choices"][0]
print(choice["message"]["content"])
print("finish_reason:", choice["finish_reason"])
print("usage:", data["usage"])Three habits in this code matter from the start:
timeout=30stops the program from waiting forever if the server never answers.raise_for_status()turns a 4xx or 5xx response into an exception. Without it, your code would try to parse an error body as if it were a result.resp.json()parses the body into dictionaries and lists, so you can index into it.
Common errors
| Symptom | Likely cause |
|---|---|
| `KeyError: 'OPENAI_API_KEY'` | The environment variable is not set in this shell. |
| 401 status | The key is missing, wrong or revoked. |
| 404 status | The URL path is wrong, or the model name does not exist for your account. |
| 400 status | The JSON body is malformed or a field has the wrong type. |
| `KeyError: 'choices'` | You parsed an error response without checking the status first. |
Exercise
Your script prints KeyError: 'choices' when you index the parsed response. Name the likely mistake and the one-line fix.
Show answer
The script parsed an error response as if it were a success, because it never checked the HTTP status. Call resp.raise_for_status() before resp.json(), so a 4xx or 5xx response raises an exception that shows the real error.