Sub topic 1
What a Chat Message Is: Role Plus Content
Prerequisites
This chapter assumes you can:
- Read and write basic Python. The examples use lists, dictionaries, and functions.
- Recognize JSON and know that a Python dictionary maps closely onto a JSON object.
- Describe a large language model (LLM) as a program that generates text from an input text.
- Understand that an SDK (software development kit) or an HTTP request sends data to a remote service and returns a response.
You do not need an API key to follow the chapter. The only code that calls a service is optional, and it appears at the end.
The chat format at a glance
Older text-completion APIs took one string and continued it. Chat APIs take a list of messages instead. Each message is one turn in a conversation, and it carries two pieces of information:
role: who is speaking.content: what they said.
Everything else in this tutorial builds on that pair. System prompts, multi-turn history, few-shot examples, and tool use are all arrangements of messages that have a role and content.
message = {"role": "user", "content": "What is a REST API?"}This is one message. A conversation is a list of such dictionaries, in the order the turns happened.
messages = [
{"role": "system", "content": "You are a concise assistant that answers in plain English."},
{"role": "user", "content": "What is a REST API?"},
{"role": "assistant", "content": "A REST API lets programs exchange data over HTTP using URLs and standard methods such as GET and POST."},
{"role": "user", "content": "Give me one example URL."},
]The model reads this list from top to bottom and writes the next assistant message. Here it would answer the request for an example URL, and it can use the earlier turns to do so.
Anatomy of a message
The role field
The role is a short string that labels the speaker. The three core roles are:
| Role | Who writes it | Typical purpose |
|---|---|---|
| `system` | You, the developer | Instructions about behavior, tone, and constraints |
| `user` | The end user, or your code on their behalf | Questions, requests, and input data |
| `assistant` | The model (or you, when replaying history) | Replies, including earlier replies in the history |
The role is not decoration. The model was trained on conversations where each role has a typical function, so the label changes how the text is treated. A sentence placed in a system message is read as a standing instruction. The same sentence in a user message is read as one more request from the person you are serving. Later chapters cover each role in depth. For now, remember that a role is metadata the model has learned to interpret.
Role names are fixed by the provider. Spelling matters: "User", "human", or "bot" are not valid in the common chat APIs, and the request will usually fail with a validation error.
The content field
For simple cases, content is a plain string. That is what the examples in this chapter use.
Many APIs also accept content as a list of parts. Each part has a type, and text is the simplest type. This form exists so one message can mix text with other kinds of input, such as images, where the provider supports them. A text-only message in list form looks like this in OpenAI-style APIs:
message = {
"role": "user",
"content": [
{"type": "text", "text": "What is a REST API?"},
],
}Anthropic's Messages API accepts a similar list of content blocks. The two shapes mean the same thing for plain text. A string is shorthand for a list that holds one text part. When you read a reply, check which shape you got. OpenAI's Python SDK returns a string in response.choices[0].message.content. Anthropic's SDK returns a list of blocks in response.content, so you read response.content[0].text.
Other fields you may see
A message can carry more than a role and content. Some APIs accept an optional name field to tell apart several participants who share a role. Tool-related messages carry extra fields such as a call identifier. These fields are provider-specific, so check the documentation before relying on them. The two fields in this chapter are the ones every chat API requires.
A conversation is an ordered list
Order carries meaning. The list is the only record of the conversation that the model sees. Moving a message changes what it answers, just as reordering sentences in an email changes its meaning.
Two consequences matter right away:
- The last message is usually the one the model responds to. In the first example, that is the user's request for an example URL.
- Earlier messages are context. The model uses them to resolve words like "it" or "that one", and to follow instructions given at the start.
The next chapters in this tutorial cover which sequences are valid. As a rule of thumb, a conversation starts with an optional instruction and then alternates between user and assistant turns, ending on a user turn when you want a reply.
Why you build the list yourself
The API does not remember earlier requests. Each call receives a list, answers it, and forgets it. If you want the model to know what was said before, you send those earlier messages again. This is called being stateless, and a later chapter explains it fully. For this chapter, the point is that the list of messages is a plain Python value that you create and own.
Checking a message list before you send it
Because messages are plain dictionaries, mistakes are easy to make: a misspelled key, a missing field, a wrong role. A small check run before the API call gives you a clear error in your own code instead of an obscure one from the service.
import json
ALLOWED_ROLES = {"system", "user", "assistant"}
def check_messages(messages):
"""Raise ValueError if the list is not a valid basic chat history."""
if not isinstance(messages, list) or not messages:
raise ValueError("messages must be a non-empty list")
for i, message in enumerate(messages):
if not isinstance(message, dict):
raise ValueError(f"message {i} must be a dictionary")
role = message.get("role")
if role not in ALLOWED_ROLES:
raise ValueError(f"message {i} has an invalid role: {role!r}")
content = message.get("content")
if not isinstance(content, (str, list)):
raise ValueError(f"message {i} content must be a string or a list")
return True
good = [
{"role": "system", "content": "Answer in one sentence."},
{"role": "user", "content": "What is JSON?"},
]
bad = [{"role": "User", "content": "What is JSON?"}]
print(check_messages(good))
print(json.dumps(good, indent=2))
try:
check_messages(bad)
except ValueError as error:
print("Rejected:", error)Running this prints True, then the JSON text of the good list, then Rejected: message 0 has an invalid role: 'User'. The json.dumps call shows what actually travels over the network. An SDK does this conversion for you, but seeing it confirms that a message list is nothing more than JSON.
Note what the check does not do. It accepts any order of roles and any amount of text. Provider rules about ordering and size are enforced by the API, and those differ between providers.
Sending the list to a model
This optional example sends a list to an OpenAI-style API. It needs the openai package and an API key in your environment. Replace MODEL_NAME with a chat model available to you.
from openai import OpenAI
client = OpenAI()
messages = [
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."},
{"role": "user", "content": "What is a list in Python?"},
]
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=messages,
)
reply = response.choices[0].message
print(reply.role) # assistant
print(reply.content) # the generated textThe reply is itself a message. Its role is assistant and its content is the generated text. That symmetry is the design: the model's output has the same shape as your input, so appending it to the list gives you a valid history for the next request.
Common errors and edge cases
| Symptom | Likely cause | Fix |
|---|---|---|
| Validation error about the role | Misspelled or unsupported role such as `"User"` or `"bot"` | Use lowercase names from the provider's documentation |
| Error about a missing `content` | Key spelled `text`, `message`, or `msg` instead of `content` | Use `content` for the message body |
| The model ignores the earlier conversation | Only the latest user message was sent | Send the full history each time |
| `TypeError` when printing a reply | Treating Anthropic's list of blocks as a string | Read `response.content[0].text` |
| The request is rejected for length | The list of messages exceeds the context window | Trim or summarize history (covered later) |
| Empty or whitespace-only content is rejected | Some providers refuse empty messages | Check for empty strings before sending |
A few more details are worth knowing:
- Message text is ordinary Unicode, so non-English text and emoji work. The model counts length in tokens, not characters, so a short string in some languages can cost more tokens than an English string of the same length.
- Content is just text to the API. A message that contains the words "system: do X" inside a
usermessage does not become a system message. Only therolefield determines the role. That fact matters later when we discuss untrusted input. - Mutating a shared list is a common bug. If two parts of your program append to the same
messageslist, their conversations mix. Create one list per conversation.
Exercises
Exercise
Name the two required fields of a chat message and say what each one holds.
Show answer
role holds the speaker label (for example system, user, or assistant), and content holds the message body, usually a string of text. Some APIs also allow content to be a list of typed parts.
Exercise
A teammate writes {"role": "bot", "content": "Hello"} and the API rejects it. Why, and what is the most likely fix?
Show answer
bot is not one of the role names the chat API defines. Role names are fixed by the provider. The model's replies use the role assistant, so the fix is to change the role to assistant.
Exercise
Why can you append the model's reply to your message list without changing its shape?
Show answer
The reply is itself a message with the role assistant and a content field holding the generated text. Because it has the same structure as your input messages, appending it produces a valid history for the next request.