Sub topic 6
How messages are ordered and which sequences are valid
This chapter assumes you know what a message with a role and content looks like, and that you have seen the system, user, and assistant roles. It covers the order in which messages must appear and what happens when the order is wrong.
Order is the conversation
A chat API reads the messages list from top to bottom. The position of each message tells the model what was said first and what it should answer now. The model produces the next assistant message, so the list is written as if the conversation has reached the point where it is the assistant's turn.
A typical valid list looks like this:
- An optional system message at the start.
- A user message.
- An assistant message (a past reply).
- Another user message, and so on.
- A final user message that the model will answer.
Common rules
The exact rules vary by provider, but these hold in most chat APIs.
- System first. The system message belongs at the start. Putting it later is either rejected or treated unpredictably.
- Start with a user turn. After any system message, the first turn should be from the user. Some APIs reject a list that begins with an assistant message.
- Alternate user and assistant. Strict APIs require the roles to take turns. Others accept two user messages in a row and merge them.
- End with a user message. The model replies to the last message. If the list ends with an assistant message, some APIs return an error. Others treat the assistant text as a prefix and continue it.
- Content must not be empty. Empty strings in
contentare rejected by some providers.
A valid and an invalid example
valid = [
{"role": "system", "content": "Answer in one sentence."},
{"role": "user", "content": "What is HTTP?"},
{"role": "assistant", "content": "HTTP is the protocol browsers use to request web pages."},
{"role": "user", "content": "And HTTPS?"},
]
invalid = [
{"role": "assistant", "content": "Hello! How can I help?"},
{"role": "user", "content": "What is HTTP?"},
{"role": "system", "content": "Answer in one sentence."},
]The second list has two problems. It begins with an assistant message that the model never wrote in this request. It also places the system message last, after the question it was meant to shape.
Checking order before you send
Errors from the API can be vague, so it helps to check the list yourself. This function enforces the strict rules above and raises a clear error.
def check_messages(messages):
if not messages:
raise ValueError("messages is empty")
turns = messages
if messages[0]["role"] == "system":
turns = messages[1:]
if any(m["role"] == "system" for m in turns):
raise ValueError("system message must be first, and only once")
if not turns:
raise ValueError("no user or assistant messages")
if turns[0]["role"] != "user":
raise ValueError("first turn must be a user message")
if turns[-1]["role"] != "user":
raise ValueError("last message must be a user message")
for previous, current in zip(turns, turns[1:]):
if previous["role"] == current["role"]:
raise ValueError(
f"two {current['role']} messages in a row"
)
return True
print(check_messages(valid))
try:
check_messages(invalid)
except ValueError as error:
print("Error:", error)The valid list prints True. The invalid list prints Error: system message must be first, and only once, because the check finds the stray system message before it reaches the other problems.
Common errors
| Mistake | Typical result | Fix |
|---|---|---|
| Two user messages in a row | Error, or the messages are merged | Combine them into one message |
| List ends with an assistant message | Error, or the model continues that text | End with the user message to answer |
| System message in the middle | Error, or the instruction is weakened | Move it to the start |
| Assistant reply left out of history | Model loses track of what it said | Append every reply after each call |
The last row connects to the next chapter. The model keeps no memory between calls, so the order you build is the only history it has.
Exercise
A developer sends [system, user, assistant, assistant, user] and gets an error from a strict API. What is wrong, and how can they fix it?
Show answer
Two assistant messages appear in a row, which breaks the alternating user and assistant pattern. They can merge the two assistant messages into one message, or remove the extra one if it is a duplicate. The list then reads system, user, assistant, user.
Exercise
Why should the final message in the list usually be a user message?
Show answer
The model writes the next assistant message in reply to the last message. Ending on a user message gives it something to answer, and avoids errors or prefix-continuation behavior that some APIs trigger when the list ends on an assistant message.