Sub topic 3
Building a chat request: model, messages and roles
This chapter assumes you can write basic Python, read JSON, and set environment variables in a terminal. You should also know what an HTTP POST request and a status code are. It covers the request body only. Authentication was covered in the previous chapter, and the response is covered in the next.
The three parts of a request
A chat-completions request is an HTTP POST to one endpoint. The body is JSON. Two fields are required:
model: the name of the model that should generate the reply.messages: an ordered list of message objects that make up the conversation so far.
Every other field, such as temperature or max_tokens, is optional and comes in later chapters. Field names and defaults differ between providers, so check your provider's documentation.
Roles
Each message has a role and a content string. The role tells the model who is speaking.
| Role | Purpose |
|---|---|
| `system` | Sets behavior, tone and rules for the whole conversation. |
| `user` | The input from the person or program asking. |
| `assistant` | A previous reply from the model. |
Order matters. The model reads the list from top to bottom, so the system message normally comes first and the final message is normally from the user. Some newer models accept a developer role in place of system. The idea is the same.
A first request with curl
This request sets a system message and one user message. The key and model name come from environment variables, so no secret is written into the command.
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 Content-Type: application/json header tells the server how to parse the body. Without it, many servers reject the request.
The same request in Python
In Python, you build the body as a dictionary and let the json= argument serialize it and set 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"])The last three lines read the reply. They are explained in the next chapter. Here, focus on how payload is built.
Common errors
- Wrong model name. A misspelled or unavailable model usually returns a 4xx error, often 404 or 400. Reading the name from
LLM_MODELkeeps it in one place. - Missing
messagesor empty list. The server returns a 400 error. At least one message is required. - A role that is not allowed. Typos such as
"users"are rejected. Use the exact role strings. - Non-string
content. For plain text,contentmust be a string. Passing a dictionary orNonefails validation. - Sending a body that is not JSON. With
requests, usejson=payload. Usingdata=payloadsends form encoding instead.
Exercise
Exercise
A request returns a 400 error. The body contains {"model": "your-model", "messages": [{"role": "user", "content": {"text": "Hi"}}]}. What is the most likely problem, and how do you fix it?
Show answer
The content field is a dictionary, but for plain text it must be a string. Change it to "content": "Hi". Also confirm the model name is valid, since a bad model name can produce a similar 4xx error.
Exercise
Why should the system message come first in the messages list?
Show answer
The model reads messages in order, and the system message sets the rules for the whole conversation. Placing it first makes those rules apply to everything that follows.