Messages & Roles
Conversations are built from system, user, and assistant messages.
Each message has a role that tells the model who is speaking.
| Role | Purpose |
|---|---|
| system | Sets the model's behaviour, persona, and rules. Comes first. |
| user | The human's input or question. |
| assistant | The model's previous replies. You include these to give context for a follow-up. |
Building a conversation
To have a multi-turn chat, keep appending messages to the list and resend it. The alternating user / assistant history is what gives the model memory of the conversation.
Example
{
"messages": [
{"role": "system", "content": "You are a helpful travel guide. Keep answers under 40 words."},
{"role": "user", "content": "What should I see in Kyoto?"},
{"role": "assistant", "content": "Visit Fushimi Inari shrine, Arashiyama bamboo grove, and Kinkaku-ji."},
{"role": "user", "content": "Which is best at sunrise?"}
]
}When to use it
- A support bot uses the system role to set its persona as 'a polite agent for AcmeCo' so every reply stays on-brand.
- A tutoring app feeds prior Q&A turns back as user/assistant pairs so the model can refer to what it already explained.
- A code-generation tool pre-populates assistant messages with partial function stubs to steer the model toward completing them.
More examples
System role sets assistant persona
Shows how the system role shapes the model's persona, tone, and vocabulary for every reply.
from openai import OpenAI
client = OpenAI()
r = client.chat.completions.create(
model='gpt-4o-mini',
messages=[
{'role': 'system', 'content': 'You are a terse pirate navigator. Reply in pirate dialect.'},
{'role': 'user', 'content': 'Where is the nearest island?'}
]
)
print(r.choices[0].message.content)Multi-turn conversation history
Passes the full conversation history so the model knows what it said in previous turns.
from openai import OpenAI
client = OpenAI()
messages = [
{'role': 'system', 'content': 'You are a helpful math tutor.'},
{'role': 'user', 'content': 'What is a prime number?'},
{'role': 'assistant', 'content': 'A prime number is only divisible by 1 and itself.'},
{'role': 'user', 'content': 'Give me three examples.'}
]
r = client.chat.completions.create(model='gpt-4o-mini', messages=messages)
print(r.choices[0].message.content)Append assistant reply to history
Maintains a running message list, appending each assistant reply so follow-up questions work correctly.
from openai import OpenAI
client = OpenAI()
messages = [{'role': 'system', 'content': 'You are a concise assistant.'}]
def chat(user_text):
messages.append({'role': 'user', 'content': user_text})
r = client.chat.completions.create(model='gpt-4o-mini', messages=messages)
reply = r.choices[0].message.content
messages.append({'role': 'assistant', 'content': reply})
return reply
print(chat('My name is Alex.'))
print(chat('What is my name?'))
Discussion