Sub topic 3
Building a chat request: model, messages and roles
This chapter covers the body of a chat request: the model field, the messages array, and the roles that give each message meaning. It assumes you can write basic Python, read JSON, set environment variables, and know what an HTTP POST and a status code are. The examples use the chat-completions request shape. Other providers use different field names, so check your provider's documentation.
The shape of a request
A chat request is a single HTTP POST to an endpoint such as /v1/chat/completions. The JSON body has two required fields.
model: a string that names which model should answer.messages: an ordered list of message objects that make up the conversation so far.
Everything else, such as temperature or max_tokens, is optional and is covered in later chapters.
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 key and the model name come from environment variables. The model name is not hard-coded because providers retire and rename models, and you will likely want different models in development and production.
The model field
The model string selects the model that processes your request. It affects four things:
- Capability: larger models usually follow complicated instructions better.
- Context window: the maximum number of tokens the request and reply can share.
- Price per token: usually higher for more capable models.
- Latency: smaller models usually respond faster.
Some providers publish aliases that point to the latest version of a model, and others publish dated snapshots that never change. An alias is convenient but can change behavior without any change in your code. A dated snapshot gives you repeatable behavior until it is retired. For production work, prefer a pinned name and keep it in configuration.
An unknown or unavailable model name normally produces a 4xx error, often 400 or 404, with a message naming the model. This is one of the most common first-request failures.
The messages array
messages is a list of objects. Each object has a role and content. The order matters, because the model reads the list from first to last as a transcript and writes the next turn.
[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "What is a token?"}
]The model has no memory between requests. Whatever is not in this array is not visible to the model. The chapter on multi-turn conversations returns to this point.
Roles
Each message carries one of a small set of roles.
| Role | Who writes it | Purpose |
|---|---|---|
| `system` | You, the developer | Sets behavior, tone, rules and format for the whole conversation |
| `user` | The end user, or your program acting for them | The request or question to answer |
| `assistant` | The model, or you when replaying history | A previous model reply |
| `tool` | Your program | The result of a tool call the model asked for |
Some newer models and providers rename or supplement system with a developer role that has the same purpose. Some providers, such as Anthropic's Messages API, take the system prompt as a separate top-level field instead of a message. When you move between providers, check where the instructions belong.
The system message
Use the system message for instructions that apply to every turn: persona, response length, output format, topics to avoid, and the language to answer in. Put it first. Keep it specific. "Answer in at most two sentences and do not use bullet points" works better than "Be brief."
The system message is guidance, not a security boundary. A user can often persuade a model to ignore or reveal it. Do not put secrets in it, and do not rely on it alone to enforce permissions.
The user message
The user message holds the actual task. You can build it from a template that combines instructions with data, for example "Summarize the following text:" followed by the text. Treat any text that came from outside your program, such as web pages or uploaded documents, as untrusted. If it contains instructions, the model may follow them. This is called prompt injection, and keeping untrusted data clearly separated in your template reduces the risk but does not remove it.
The assistant message
An assistant message is a model reply. You include earlier replies in later requests so the model sees what it already said. You can also write an assistant message yourself, for example to show one or two example answers in the format you want. This technique is called few-shot prompting.
messages = [
{"role": "system", "content": "Classify the sentiment as positive, negative or neutral. Reply with one word."},
{"role": "user", "content": "The delivery was fast."},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "The box arrived damaged."},
{"role": "assistant", "content": "negative"},
{"role": "user", "content": "The package is on the porch."},
]The final message is a user message, so the model produces the next assistant turn. Most chat APIs expect the list to end with a user message, or with a tool message when you are returning tool results.
Sending the request from Python
The same request in Python uses requests with a timeout and checks the status code before parsing.
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"])Passing json=payload makes requests serialize the dictionary and set the body correctly. The explicit Content-Type header is still set here so the request matches the curl example. raise_for_status() turns 4xx and 5xx responses into exceptions, so a failed call does not reach resp.json() and fail with a confusing error. The next chapter explains the response fields printed at the end.
Content that is not a plain string
For most text work, content is a string. Models that accept images or other inputs usually take content as a list of parts instead, each with a type.
{
"role": "user",
"content": [
{"type": "text", "text": "What is in this picture?"},
{"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}
]
}Only use this form with a model that supports the input type. Sending an image to a text-only model returns an error. The exact part types and limits vary by provider.
Common errors
- Missing or misspelled
model: you get a 400 error that names the field. - Wrong role name, such as
"human"or"bot": the API rejects it with a 400 error. Use the documented roles. contentset tonullor a number: most APIs require a string or a list of parts, except for assistant messages that contain only tool calls.- Sending a
messageslist that is empty: this is rejected. - Putting the system message in the middle of a conversation: some providers allow it, but others reject it, and models may weight it less. Put it first.
- Request body too large: if the messages exceed the context window, you get an error that mentions the maximum context length. The tokens chapter covers this limit.
- Building the JSON by string concatenation in a shell: quotes and newlines in user text break the JSON. Use a JSON library, or
json=inrequests.
Design habits for the request
- Keep the system message in one place in your code, so you can version and review it like any other configuration.
- Read the model name from configuration, not from a string literal in the call.
- Build messages as a list of dictionaries, and append to it rather than formatting one large string.
- Log the role sequence and the size of each message while developing. Avoid logging full content once real user data is involved.
- Validate that the last message has the role you expect before you send.
Exercise
A developer sends the messages [{"role": "user", "content": "My name is Sam."}] in one request. In a second, separate request, they send [{"role": "user", "content": "What is my name?"}]. The model cannot answer. Why, and what should they change?
Show answer
The API is stateless, so the second request contains no record of the first. The model only sees the messages in the current request. The developer should keep the message list in their program and send the earlier user message and the assistant reply together with the new question, in order, in every request.
Exercise
Which role should hold the rule "Always answer in French", and where in the list should that message go? Name one reason not to rely on it for security.
Show answer
The rule belongs in a system message placed first in the list. It is not a security boundary because a user can often convince the model to ignore or reveal it, so it should not hold secrets or be the only control over permissions.