Sub topic 6
How Messages Are Ordered and Which Sequences Are Valid
This chapter assumes you know that a chat message is a dictionary with a role and content, and that you have seen the system, user, and assistant roles. It covers the rules about order. Order matters because the model reads the list from top to bottom, and because providers reject some sequences.
Why order matters
A chat request is a list, not a set. The model reads the messages in the order you send them, and it treats the last message as the thing it must respond to. Two rules follow from this:
- Position carries meaning. An instruction near the top frames everything after it. A user message at the end is the request being answered.
- Providers validate the list. If the sequence breaks their rules, the API returns an error before the model runs.
The exact rules differ by provider and change over time, so check your provider's current documentation. The patterns below are the common ones.
The usual shape of a valid conversation
Most valid conversations follow this pattern:
- An optional system message first.
- A user message.
- An assistant message (a previous reply).
- Alternating user and assistant messages after that.
- A final user message, which the model answers.
messages = [
{"role": "system", "content": "You answer in one short sentence."},
{"role": "user", "content": "What is a tuple in Python?"},
{"role": "assistant", "content": "A tuple is an ordered, immutable collection of values."},
{"role": "user", "content": "How do I make one?"},
]The model's new reply is not part of this list yet. You append it after the response arrives. That is why the list normally ends on a user message when you send it.
Mermaid diagrams must use the fence format required here, so the diagram follows below.
Where the system message goes
In OpenAI-style APIs, the system message is a normal entry in the messages list. By convention it is the first entry. Putting it first means every later message is read in light of it.
Some APIs allow system messages later in the list. This is allowed in some places, but it is a risky habit. Behavior can vary, and a late instruction may compete with earlier ones. If you need to change behavior mid-conversation, prefer one of these:
- Rebuild the list with an updated system message at the top.
- Add the new instruction to the latest user message.
In Anthropic-style APIs, the system prompt is not in the list at all. It is a separate system parameter, so the messages list holds only user and assistant turns. The next chapters compare providers in more detail. For ordering, the point is that "system first" is automatic there.
Alternation: user, assistant, user, assistant
The most common rule is that user and assistant messages take turns. Some providers enforce this strictly. Others accept two user messages in a row and merge them or treat them as separate turns.
Consider this list:
messages = [
{"role": "user", "content": "Summarize this article."},
{"role": "user", "content": "Keep it under 50 words."},
]Depending on the provider, this may:
- work as written, with the two messages handled together,
- be merged into one user turn, or
- fail with a validation error.
The portable choice is to avoid consecutive same-role messages. Combine them yourself:
messages = [
{
"role": "user",
"content": "Summarize this article. Keep it under 50 words.",
},
]If you must keep parts separate, for example an article and an instruction, put both in a single message with clear labels:
article = "Large language models predict the next token in a sequence."
messages = [
{
"role": "user",
"content": f"Article:\n{article}\n\nTask: Summarize in under 50 words.",
},
]Which turn comes first
Most chat APIs expect the first non-system message to come from the user. A conversation that starts with an assistant message may be rejected. Some providers allow it, so it is not universal.
You might want to start with an assistant greeting, such as "Hi, how can I help?", in a chat interface. You do not need to send that greeting to the model as history. Show it in your user interface and leave it out of the request, or place the greeting text in the system message as context.
Ending on the right role
The model generates the next assistant turn. So the list should end where an assistant reply makes sense, normally after a user message.
What happens if the list ends on an assistant message? It depends on the provider:
- Some APIs return an error.
- Some treat the final assistant message as a prefill, which is the start of the reply, and the model continues from it.
- Some simply generate another reply as if you had asked it to continue.
Prefill is a real feature in some APIs. It lets you start the reply with text like { to push the model toward JSON. Because behavior varies, do not rely on it unless the provider documents it for your model.
messages = [
{"role": "user", "content": "Return the colors of a rainbow as JSON."},
{"role": "assistant", "content": "{"},
]This example is only valid where the provider supports prefill. Elsewhere it may raise an error.
Empty and malformed messages
Order is not the only thing validated. Common failures include:
- An empty
contentstring, which some providers reject. - A role name the API does not know, such as
"bot"or"User"with a capital letter. Role names are case sensitive and must match exactly. - A missing
roleorcontentkey. - A
contentvalue of the wrong type, such asNonewhere text is required.
A small checker catches many of these before you spend a request on them:
VALID_ROLES = {"system", "user", "assistant"}
def check_messages(messages):
if not messages:
raise ValueError("messages is empty")
for i, m in enumerate(messages):
if m.get("role") not in VALID_ROLES:
raise ValueError(f"message {i}: unknown role {m.get('role')!r}")
if not isinstance(m.get("content"), str) or not m["content"].strip():
raise ValueError(f"message {i}: content must be a non-empty string")
non_system = [m for m in messages if m["role"] != "system"]
if not non_system:
raise ValueError("need at least one user or assistant message")
if non_system[0]["role"] != "user":
raise ValueError("first non-system message should be from the user")
for prev, cur in zip(non_system, non_system[1:]):
if prev["role"] == cur["role"]:
raise ValueError(
f"two consecutive {cur['role']} messages; merge them"
)
if non_system[-1]["role"] != "user":
raise ValueError("conversation should end with a user message")
check_messages([
{"role": "system", "content": "Be brief."},
{"role": "user", "content": "Hello"},
])
print("valid")This checker is stricter than some providers. That is deliberate. It enforces the portable subset, so code that passes it should work across providers. Note that it only handles text content. Later chapters cover tool messages and other content types, which need their own checks.
What the order does to the model
Beyond validity, order shapes quality.
- Recent messages tend to have more influence than distant ones. A constraint stated 40 messages ago may be followed less reliably than one repeated near the end.
- The last user message sets the task. If it is vague, earlier context only partly rescues it.
- Few-shot examples work through order. Earlier user and assistant pairs show a format, and the final user message gets the same treatment.
This is a tendency, not a guarantee. Test with your own prompts and model.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Two user messages in a row | Error, or merged text | Combine into one message |
| System message placed last | Instructions ignored or error | Put it first, or use the `system` parameter |
| Dropping the assistant reply from history | Model forgets what it said | Append every reply after each call |
| Appending the reply as `user` | Model confuses its own words with yours | Use the `assistant` role |
| Trimming history so it starts with an assistant message | Validation error | Trim in whole user and assistant pairs |
| Empty content | Validation error | Skip empty messages |
The trimming mistake deserves a closer look. If you cut a history by keeping the last N messages, an odd N can leave an assistant message at the front. Trim in pairs, or after trimming, drop any leading assistant message:
def trim_pairs(messages, keep_pairs=3):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
rest = rest[-keep_pairs * 2:]
while rest and rest[0]["role"] != "user":
rest = rest[1:]
return system + rest
history = [
{"role": "system", "content": "Be brief."},
{"role": "user", "content": "One"},
{"role": "assistant", "content": "A"},
{"role": "user", "content": "Two"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "Three"},
]
print(trim_pairs(history, keep_pairs=1))With keep_pairs=1, the slice takes the last two non-system messages, which are the assistant "B" and the user "Three". The loop then removes "B", so the result is the system message and "Three". The list starts with a user message and ends with one.
Summary of the rules
- Put the system message first, or in the
systemparameter where the API provides one. - Start with a user message.
- Alternate user and assistant turns.
- End on a user message so the model has something to answer.
- Use exact, lowercase role names and non-empty text content.
- Treat any other pattern, such as prefill, as provider-specific.
Exercise
A history list is [system, user, assistant, user, assistant]. You send it as is. Why might the call fail or behave oddly, and how do you fix it?
Show answer
It ends on an assistant message, so there is no pending user request. Depending on the provider, the call may be rejected, treated as a prefill that the model continues, or answered with an unwanted extra reply. Fix it by appending the new user message before sending, so the list ends on a user turn.
Exercise
You keep only the last 5 non-system messages of a long history, and the API now complains. What is the likely cause, and what is one way to avoid it?
Show answer
Five messages from a user/assistant alternation can start with an assistant message, which many providers reject as the first non-system message. Keep an even number of messages (whole user and assistant pairs), or drop any leading assistant message after trimming.
Exercise
Your app has two pieces of input for one request: a document and a short instruction. Why is sending them as two consecutive user messages risky, and what is a portable alternative?
Show answer
Providers differ. Some merge consecutive same-role messages and others raise an error. A portable alternative is one user message that contains both parts, labeled clearly, such as "Document:" followed by the text and "Task:" followed by the instruction.