Roles & System Prompts
Chat models do not receive one big string from you. They receive a list of messages, each with a role:
| Role | Who writes it | Typical content |
|---|---|---|
system |
the application developer | persona, rules, background, output style — applies to the whole conversation |
user |
the person (or your code) | questions, tasks, documents |
assistant |
the model | previous replies (your app sends them back so the model sees the history) |
The system prompt is the developer's place for standing instructions. Users normally never see it, and models are trained to give it more weight than user messages.
Messages in code
In the Anthropic Messages API the system prompt is a separate system parameter and messages alternates between user and assistant. Other providers have very similar chat APIs (some put the system prompt into the message list instead).
import anthropic
client = anthropic.Anthropic() # reads the ANTHROPIC_API_KEY environment variable
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=300,
system="You are a friendly tutor for 10-year-olds. Use short sentences and one example.",
messages=[{"role": "user", "content": "What is photosynthesis?"}],
)
print(response.content[0].text)This is reference code — it needs an API key and network access, so it does not run here. With this system prompt a model typically answers in a few simple sentences with a child-friendly example (plants using sunlight to make food from water and air), rather than the textbook definition it might give an adult.
Validating a conversation
Your app is responsible for sending a well-formed history. A small validator catches common bugs before they become API errors:
def validate(messages):
problems = []
if not messages:
problems.append("conversation is empty")
elif messages[0]["role"] != "user":
problems.append("first message must come from the user")
for prev, cur in zip(messages, messages[1:]):
if prev["role"] == cur["role"]:
problems.append(f"two '{cur['role']}' messages in a row")
for m in messages:
if m["role"] not in ("user", "assistant"):
problems.append(f"unexpected role '{m['role']}' (system goes in its own parameter)")
return problems or ["ok"]
good = [{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello! How can I help?"},
{"role": "user", "content": "Explain tokens."}]
bad = [{"role": "system", "content": "Be brief."},
{"role": "user", "content": "Hi"},
{"role": "user", "content": "Anyone there?"}]
print("good:", validate(good))
print("bad: ", validate(bad))good: ['ok']
bad: ['first message must come from the user', "two 'user' messages in a row", "unexpected role 'system' (system goes in its own parameter)"]
Under the hood: chat templates
The model itself still only sees a sequence of tokens. A chat template turns the message list into one text with special marker tokens around each turn, ending with an open assistant turn for the model to continue. The exact markers differ between model families and are handled for you by the API; this toy version shows the idea:
def render_chat(system, messages):
out = [f"<|system|>\n{system}\n<|end|>"]
for m in messages:
out.append(f"<|{m['role']}|>\n{m['content']}\n<|end|>")
out.append("<|assistant|>") # the model continues from here
return "\n".join(out)
print(render_chat(
"You are a concise assistant.",
[{"role": "user", "content": "Name a prime number."},
{"role": "assistant", "content": "7"},
{"role": "user", "content": "Another one?"}],
))<|system|>
You are a concise assistant.
<|end|>
<|user|>
Name a prime number.
<|end|>
<|assistant|>
7
<|end|>
<|user|>
Another one?
<|end|>
<|assistant|>
The model was trained on many texts in this format, so after <|assistant|> it produces a reply and then the end marker. This also explains why the role structure matters: it is literally part of the text the model reads.
Writing a good system prompt
A useful system prompt usually covers:
- Role and audience — "You are the help assistant of an online plant shop; customers are beginners."
- Goals and priorities — what a good answer achieves, what matters most.
- Boundaries — topics to decline, when to hand over to a human.
- Style — tone, length, formatting (e.g. "no markdown, the widget shows plain text").
- Background facts — opening hours, product facts, today's date.
SHOP = {"name": "Leafy Lane", "hours": "Mon-Sat 9:00-18:00", "returns": "30 days with receipt"}
system_prompt = f"""You are the assistant for {SHOP['name']}, an online plant shop.
Customers are mostly beginners, so avoid botanical jargon.
Facts you may use:
- Opening hours: {SHOP['hours']}
- Returns: {SHOP['returns']}
Rules:
- Answer in at most 4 sentences, plain text, no markdown.
- If a question is about an order's status, ask for the order number.
- For anything about plant poisoning or pets' health, recommend a vet or doctor."""
print(system_prompt)
print(f"\n({len(system_prompt.split())} words)")You are the assistant for Leafy Lane, an online plant shop.
Customers are mostly beginners, so avoid botanical jargon.
Facts you may use:
- Opening hours: Mon-Sat 9:00-18:00
- Returns: 30 days with receipt
Rules:
- Answer in at most 4 sentences, plain text, no markdown.
- If a question is about an order's status, ask for the order number.
- For anything about plant poisoning or pets' health, recommend a vet or doctor.
(74 words)
Note: A system prompt is guidance, not a security boundary. Determined users can sometimes talk a model out of its instructions (see Privacy & Security), and you should assume the system prompt may be revealed. Never put secrets such as API keys or passwords in it.
Test yourself
Who normally writes the system prompt?
- The end user
- The application developer
- The model
- The tokenizer
Why does an app send previous assistant messages back to the API?
- To train the model
- Because the model has no memory between requests; it only sees what is in the request
- To save tokens
- The API requires exactly three messages
Which should never go into a system prompt?
- The assistant's tone
- Opening hours
- An API key or password
- Today's date