Sub topic 4
Setting behavior with a system message
The chat loop and the message list from the earlier chapters work, but the bot has no defined personality, format, or limits. This chapter adds a system message to control those, and covers where it must live so that trimming, resetting, and saving don't lose it.
This chapter assumes you have:
- the chat loop from the earlier chapters, with a
historylist of role-tagged dictionaries - a working
trim_historyfunction - basic Python: functions, lists, dictionaries, and string handling
What a system message is
Each message in history has a role. You already use user and assistant. The third common role is system. A system message is an instruction written by the developer rather than the person typing. It tells the model how to behave for the whole conversation.
Typical uses:
- Persona or task: "You are a code reviewer for Python."
- Output format: "Reply in plain text. Do not use Markdown."
- Length and tone: "Keep answers under 100 words."
- Boundaries: "If a question is not about cooking, say so and stop."
The model is trained to give system instructions more weight than ordinary user text. It is not an enforced rule, though, and the security section below covers why.
Where it goes in the history
The system message is the first element of the list, and it is sent on every request. The API is stateless, so the model only knows the instructions if you resend them each turn.
Build the history with a helper instead of writing the dictionary inline. The same helper can then be used at startup, in /reset, and when loading a save file.
SYSTEM_PROMPT = (
"You are a concise assistant in a terminal chat. "
"Reply in plain text without Markdown. "
"Keep replies under 120 words unless the user asks for more. "
"If you are unsure, say so instead of guessing."
)
def new_history(system_prompt=SYSTEM_PROMPT):
return [{"role": "system", "content": system_prompt}]In main(), replace the inline list with history = new_history().
Why position matters
Three operations from other chapters can silently remove or duplicate the system message. Check each one.
Trimming
The trim_history function from the sliding-window chapter splits the list into system messages and everything else, trims only the second group, and puts the system messages back at the front. If you had written history[-20:] instead, the oldest message would be the first to go, and that is the system message. The bot would then slowly lose its instructions in a long chat, with no error to warn you.
Resetting
A /reset command should clear the conversation but keep the instructions. Build a fresh list rather than emptying the old one:
def reset_history(history, system_prompt=SYSTEM_PROMPT):
history[:] = new_history(system_prompt)The slice assignment history[:] = ... changes the list in place. Any other part of the program that holds a reference to the same list sees the reset. Writing history = new_history() inside a function would only rebind a local name and leave the caller's list unchanged.
Loading a saved conversation
A save file contains the system message that was current when it was saved. If you edit SYSTEM_PROMPT and then load an old file, the old instructions are still in force. Decide which one you want. For most chatbots the current code should win, so replace the stored system message on load:
def with_current_system_prompt(history, system_prompt=SYSTEM_PROMPT):
rest = [m for m in history if m["role"] != "system"]
return new_history(system_prompt) + restUse it like this: history = with_current_system_prompt(load_history(path, new_history())). If you would rather have saved chats keep the behavior they were started with, skip this step. Both choices are valid. What matters is that you pick one on purpose.
Provider differences
Not every API accepts a system entry inside the message list. Some, such as OpenAI-style chat endpoints, accept it as the first message. Others take the system text as a separate parameter and reject a system role in the list. Some newer models rename the role (for example developer), and the name may change again.
Keep the difference out of your chat logic. The history always stores {"role": "system", ...}, and the complete function you wrote in the model-call chapter converts to whatever the provider needs. Here is a helper for the separate-parameter case:
def split_system(history):
"""Return (system_text, other_messages) for APIs with a separate system field."""
system_text = "\n\n".join(m["content"] for m in history if m["role"] == "system")
others = [m for m in history if m["role"] != "system"]
return system_text, othersJoining several system messages with a blank line keeps them readable. Inside complete, you would call split_system(history) and pass the two results to your SDK's system= and messages= arguments. Check your provider's documentation for the exact parameter names.
Writing a good system prompt
A few habits make the prompt more reliable:
- Be specific and testable. "Keep replies under 120 words" can be checked. "Be brief" cannot.
- State the output format. If the terminal cannot render Markdown, say so, or you will see stray asterisks and backticks.
- Say what to do when the rule applies, not only what to avoid. "If the question is off-topic, reply with one sentence saying so" works better than "Don't answer off-topic questions."
- Keep it short. The system message is resent on every turn, so it counts against the context window and the bill every time. A 600-token prompt costs 600 tokens on turn 1 and again on turn 50.
- Test with awkward input. Ask the bot to ignore its instructions, to switch format, or to answer something off-topic, and see what happens.
Edge cases and limits
Instructions drift in long chats
Models follow the system message best near the start of a conversation. After many turns, especially if the user pushes in another direction, adherence can weaken. Mitigations include a short prompt, trimming old turns, and repeating a key rule in a final reminder message if you see drift. Do not rely on the prompt for anything that must never fail.
The system prompt is not a secret or a security boundary
Users can often coax a model into revealing or ignoring its system message. Never put API keys, passwords, or private data in it. If the bot must not do something, enforce that in code, for example by validating output or limiting which tools it can call, and use the prompt only as guidance.
Changing the prompt mid-conversation
You can change history[0]["content"] between turns, for instance in a /persona command. The next request uses the new text, but earlier assistant replies were written under the old one, so the model may imitate their style. If you need a clean switch, reset the history as well.
Empty or duplicated system messages
An empty string wastes a slot, and some providers reject it. A second system message can appear if you load a file and then also call new_history(). Keep exactly one source of truth. A small check catches this early:
def check_history(history):
system_count = sum(1 for m in history if m["role"] == "system")
assert system_count <= 1, "history has more than one system message"
if system_count:
assert history[0]["role"] == "system", "system message must come first"A runnable check
This script ties the pieces together without calling a model. It shows that trimming and resetting keep the prompt in place.
SYSTEM_PROMPT = "You are a concise assistant."
def new_history(system_prompt=SYSTEM_PROMPT):
return [{"role": "system", "content": system_prompt}]
def trim_history(history, max_messages):
system = [m for m in history if m["role"] == "system"]
rest = [m for m in history if m["role"] != "system"]
rest = rest[-max_messages:]
while rest and rest[0]["role"] != "user":
rest.pop(0)
return system + rest
def reset_history(history, system_prompt=SYSTEM_PROMPT):
history[:] = new_history(system_prompt)
history = new_history()
for i in range(10):
history.append({"role": "user", "content": f"question {i}"})
history.append({"role": "assistant", "content": f"answer {i}"})
trimmed = trim_history(history, 4)
assert trimmed[0] == {"role": "system", "content": SYSTEM_PROMPT}
assert len(trimmed) == 5
assert trimmed[1]["content"] == "question 8"
reset_history(history)
assert history == new_history()
print("system message survived trimming and reset")Summary of rules
| Situation | What to do |
|---|---|
| Starting a chat | Build the list with `new_history()` |
| Trimming | Keep system messages, slice only the rest |
| `/reset` | Rebuild the list in place with the system message |
| Loading a save | Decide whether the stored or current prompt wins |
| Provider has a separate system field | Convert inside `complete`, not in the chat loop |
| Anything security-critical | Enforce in code, not in the prompt |
Exercise
A user chats for two hours, and the bot gradually stops following its "reply in plain text" rule. Your trimming code is history = history[-20:]. Give the most likely cause and the fix.
Show answer
The slice keeps only the last 20 messages, so once the history passes 20 entries the system message at index 0 is discarded and the model never sees the formatting rule again. Fix it by splitting system messages from the rest, slicing only the rest, and prepending the system messages again, as trim_history does.
Exercise
You change SYSTEM_PROMPT in your code, restart the bot, and load an old save file. The bot still follows the old instructions. Why, and what function from this chapter would make the new prompt apply?
Show answer
The save file stores the whole history, including the old system message at index 0, and loading restores it unchanged. Passing the loaded history through with_current_system_prompt removes the stored system message and puts the current one at the front, so the new instructions apply while the earlier user and assistant turns are kept.