Sub topic 6
System, user, and assistant messages
This chapter covers the messages array in a chat completion request. It explains what each role does and how conversation history works. It also covers the mistakes that most often cause confusing output from local models.
It assumes you can already send a basic chat completion to your local server, as in the previous chapter. It also assumes you have the OpenAI Python client installed and a model such as llama3.2 downloaded.
Why the API takes a list of messages
A language model has no memory between requests. Each call to /v1/chat/completions is independent. Whatever the model should "know" about the conversation must be sent again in that request.
The messages field is how you send it. It is an ordered list of objects, and each object has two main keys:
rolesays who is speaking.contentholds the text.
The server turns this list into one long prompt using the model's chat template, a set of formatting rules specific to each model family. The model then continues the text as the assistant. The template is why the same list of messages can work on one model and behave strangely on another.
The three core roles
| Role | Who writes it | Purpose |
|---|---|---|
| `system` | You, the developer | Sets behavior, tone, and rules for the whole conversation |
| `user` | The end user, or your code on their behalf | The question or task |
| `assistant` | The model, or you when you supply earlier replies | A previous model reply |
The system message
The system message sets standing instructions: the persona, the output format, the language, or limits on scope. By convention it comes first and appears once.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[
{"role": "system", "content": "You are a concise assistant. Answer in one sentence."},
{"role": "user", "content": "Explain what a context window is."},
],
)
print(response.choices[0].message.content)Small local models follow system messages less reliably than large hosted ones. Keep the instructions short, concrete, and positive. "Answer in one sentence" works better than a long list of things not to do.
The user message
The user message carries the request. In a single-turn call, it is the last item in the list. In a multi-turn call, each new question is appended as a new user message.
The assistant message
An assistant message is a reply from the model. You see one in the response, at response.choices[0].message. You also write assistant messages yourself when you replay history, or when you want to show the model an example of the answer style you expect.
Reading the response message
The reply is an object, not a plain string. Its role is always "assistant", and its content holds the text.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Name a prime number."}],
)
message = response.choices[0].message
print(message.role)
print(message.content)
print(response.choices[0].finish_reason)finish_reason tells you why generation stopped. stop means the model finished naturally. length means it hit the max_tokens cap or the context limit, so the text may be cut off.
Building a multi-turn conversation
To continue a conversation, append the assistant's reply to your list, then append the next user message, and send the whole list again. The server stores nothing between calls.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
messages = [
{"role": "system", "content": "You are a concise assistant."},
]
def ask(question: str) -> str:
messages.append({"role": "user", "content": question})
response = client.chat.completions.create(
model="llama3.2",
messages=messages,
temperature=0.2,
)
reply = response.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
return reply
print(ask("My favorite color is green. Remember that."))
print(ask("What is my favorite color?"))The second call works because the first exchange is inside messages. If you forget the append calls, the model answers the second question with no knowledge of the first.
Roles must make sense to the template
Hosted OpenAI models accept many message orders. Local models are stricter, because their chat templates were written for a particular pattern. Some templates raise an error if two user messages appear in a row, or if the first non-system message is an assistant message. Others accept the list but produce worse output.
A safe pattern is: one optional system message, then strictly alternating user and assistant messages, ending on a user message.
If you get a 400 error mentioning roles or alternation, check the order first.
Few-shot examples with assistant messages
You can steer the output format by inserting made-up exchanges before the real question. This is few-shot prompting. The model sees the earlier assistant messages as its own past behavior and tends to continue the pattern.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[
{"role": "system", "content": "Classify the sentiment as positive, negative, or neutral. Reply with one word."},
{"role": "user", "content": "The battery lasts all day."},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "The screen cracked in a week."},
{"role": "assistant", "content": "negative"},
{"role": "user", "content": "The box contains a charger and a cable."},
],
temperature=0,
max_tokens=5,
)
print(response.choices[0].message.content)This often gives a stronger format guarantee on small models than a long instruction in the system message.
Managing history length
The history grows with every turn, and the whole list must fit in the model's context window. The context window is the maximum number of tokens the model can read and write in one request. Local servers often use a default that is smaller than the model's trained limit. Ollama, for example, has historically defaulted to a small window unless you raise it.
What happens when you exceed it depends on the server. Some return an error. Others silently drop the oldest tokens, which can remove your system message and change the model's behavior without any warning.
Two simple strategies help:
- Keep the system message and only the last N exchanges.
- Summarize older turns into a single message and replace them.
Here is the first strategy.
def trim_history(messages: list[dict], keep_last: int = 6) -> list[dict]:
"""Keep the leading system message and the most recent messages."""
system = [m for m in messages[:1] if m["role"] == "system"]
rest = messages[len(system):]
return system + rest[-keep_last:]With keep_last set to an even number, the trimmed list keeps whole user and assistant pairs after the system message. Call trim_history(messages) just before each request and pass the result as messages. Trimming only the copy you send keeps your full log intact.
Note that this counts messages, not tokens. A few very long messages can still overflow the window. For a stricter limit, count tokens with a tokenizer that matches your model, or read response.usage.prompt_tokens after each call to see how much space the history uses.
Other roles you may meet
The API defines roles beyond the three core ones.
toolcarries the result of a function call back to the model. It belongs to tool calling, which a later chapter covers.developeris a newer OpenAI role that replacessystemfor some hosted models. Many local servers do not recognize it. Usesystemunless the server's documentation says otherwise.
An unrecognized role usually produces a 400 error or is silently treated as a user message, depending on the server.
Common errors
- Forgetting history. The model "forgets" earlier turns because you sent only the newest user message.
- Not storing the reply. You print the answer but never append it as an
assistantmessage, so the next turn has a gap. - Several system messages. Some templates merge them, some keep only the first, and some fail. Combine them into one.
- System message not first. A system message placed mid-list may be ignored or rejected.
- Empty
content. Some servers reject empty strings. Check forNonebefore appending a reply. - Ending on an assistant message. Some servers treat this as a request to continue that message. Others return an error. End on
userunless you intend to prefill.
Summary of the key points
- Each request is stateless. You own the history.
- Use one
systemmessage first, then alternatinguserandassistantmessages ending onuser. - Append every reply to the history, and trim the history before it outgrows the context window.
- Local chat templates are stricter than the hosted API, so unusual message orders can fail or degrade output.
Exercise
A user sends "My name is Priya." and your code gets a reply. On the next request, your code sends only [{"role": "user", "content": "What is my name?"}] and the model cannot answer. What is wrong, and what two messages must be in the list for the model to answer correctly?
Show answer
The server keeps no state between requests, so the earlier turn was never sent. The list must include the first user message ("My name is Priya.") and the model's earlier reply as an assistant message, followed by the new user question. A system message, if used, goes first.
Exercise
Your multi-turn chat works for ten turns, then the model stops following the system message's instruction to answer in one sentence. The server returns no error. Give a likely cause and one fix.
Show answer
The history probably exceeded the context window, and the server silently dropped the oldest tokens, including the system message. Fixes include trimming the history while always keeping the system message, summarizing older turns, or raising the server's context size setting.
Exercise
You get a 400 error from a local server after sending a list with a system message, a user message, and then a second user message. What change is the safest first attempt?
Show answer
Merge the two user messages into one, or insert the assistant reply that belongs between them, so that roles alternate user, assistant, user. Strict chat templates often reject consecutive messages with the same role.