Lesson 7 of 11 · Generation
System, User and Assistant Messages
How chats are sent to LLM APIs: system, user and assistant roles, why the API is stateless, managing history, few-shot turns, prefilling and tool messages.
- 6 min read
- Intermediate
- Reviewed
- The roles in an API conversation and what each is for
- Why the API has no memory, and what that means for your app
- How to keep a long conversation within the context window
- Useful tricks: example turns, prefilling and tool messages
A conversation is a list
Chat APIs from all the major providers take a conversation as a list of messages, each with a role and content. The model reads the list (converted with its chat template) and writes the next assistant message.
| Role | Written by | Purpose |
|---|---|---|
| system | The developer | Standing instructions for the whole conversation |
| user | The person (or your program) | Requests, questions, documents |
| assistant | The model | Its earlier replies |
Some APIs put the system prompt in a separate field rather than in the list, and some call it a "developer" message, but the idea is the same.
The API remembers nothing
This surprises many people: the "memory" in a chat app is the app re-sending the history. It has big consequences:
- Cost grows with every turn, because the history is billed again.
- You control the history. You can edit it, summarise it, remove messages, or insert information.
- Long chats overflow the context window unless the app trims them.
Trimming history
A common approach: always keep the system prompt and the new message, then add as many recent turns as fit.
def estimate_tokens(text):
return len(text) // 4 + 1 # rough rule: about 4 characters per token
def fit_history(system, history, new_message, limit):
# Always keep the system prompt and the new message,
# then add as many recent turns as fit, newest first.
used = estimate_tokens(system) + estimate_tokens(new_message["content"])
kept = []
for message in reversed(history):
cost = estimate_tokens(message["content"])
if used + cost > limit:
break
kept.insert(0, message)
used += cost
return [{"role": "system", "content": system}] + kept + [new_message], used
system = "You are a concise travel assistant."
history = [
{"role": "user", "content": "I want to visit Japan in April for 10 days."},
{"role": "assistant", "content": "April is cherry blossom season. A good route is Tokyo, Hakone, Kyoto and Osaka, with 2 to 3 nights in each."},
{"role": "user", "content": "I prefer quiet places to big cities."},
{"role": "assistant", "content": "Then consider Kanazawa, the Kiso Valley and a temple stay on Mount Koya."},
]
new_message = {"role": "user", "content": "Which of those is easiest by train from Kyoto?"}
messages, used = fit_history(system, history, new_message, limit=60)
print(f"Sending {len(messages)} messages, about {used} tokens:")
for message in messages:
print(f" {message['role']:9} {message['content'][:45]}")It fits, but look what was dropped: the first two messages, which said Japan, April, 10 days. The model can still answer about trains from Kyoto, but if the user next asks "and what should I pack?", the model no longer knows the season. Better apps summarise dropped turns ("Context so far: 10-day trip to Japan in April, prefers quiet places") and keep that summary in the request.
Useful tricks with roles
Examples as fake turns. Few-shot examples can be written as earlier user and assistant messages. The model sees "previous" exchanges in the exact format you want and continues in the same style.
Prefilling. Some APIs let you start the assistant's reply yourself: you add a final assistant message such as an opening curly bracket, and the model continues from there. This strongly steers the format (for example, straight into JSON) without any preamble.
Tool messages. When a model can use tools, the conversation also contains tool calls (the model asking to run a function, such as a weather lookup) and tool results (what the function returned), each as messages in the list. The model then reads the result and answers. Tools are covered in the API courses.
Common mistakes
Convert a saved chat into the messages format that AI APIs expect.
turns = [("me", "Hi"), ("bot", "Hello! How can I help?"), ("me", "Tell me a joke")]
# Build a messages list for an API:
# - start with {"role": "system", "content": "You are friendly."}
# - "me" turns become role "user", "bot" turns become role "assistant"
# Then print each message as role: content
Why does a chat app send the whole conversation history with every request?
Summary
- Conversations are lists of system, user and assistant messages.
- LLM APIs are stateless: the app re-sends the history, so cost grows each turn.
- Trim long histories by keeping the system prompt and recent turns, and summarise or pin key facts.
- Use example turns, prefilling and tool messages to shape behaviour.
- History is just data: you can edit it, and untrusted history can be manipulated.
Next: controlling where an answer stops, with max tokens and stop sequences.
Finished reading? Tick it off to track your progress.