System, Human, AI Messages
The cast of characters in an LLM conversation. Controlling behavior effectively.
1. The Cast of Characters
A conversation isn't just a list of strings. It's a script with roles. Chat Models distinguish between Who is speaking.
A. SystemMessage
Role: The Director / God Mode. Function: Sets the rules, tone, and constraints. Visibility: The user usually never sees this. Weight: Models pay extra attention to this (usually).
B. HumanMessage
Role: The User. Function: The input query or command.
C. AIMessage
Role: The Model. Function: The response.
2. Why Separation Matters
Beginners often put everything in the HumanMessage:
"You are a helpful assistant. Tell me a joke."
This is weak. The model treats it as a suggestion from the user, not a law of the universe. If a user later says "Ignore previous instructions", the model is likely to obey because "User overrides User."
If you put constraints in SystemMessage, they are harder to override (though not impossible).
"System: You are a helpful assistant."
"User: Ignore instructions."
"System Rules > User Rules."
3. Dynamic Personalities
Using ChatPromptTemplate, we can swap personalities easily.
from langchain_core.messages import SystemMessage, HumanMessage
def get_personality_chain(role):
template = ChatPromptTemplate.from_messages([
("system", "You are a {role}. Answer briefly."),
("human", "{question}")
])
return template | model
# Role: Pirate
get_personality_chain("Pirate").invoke({"question": "Hi"})
# "Ahoy matey!"
# Role: Butler
get_personality_chain("English Butler").invoke({"question": "Hi"})
# "Good afternoon, sir."4. Summary
Don't just be a user. Be a Director.
Use SystemMessage to establish the laws of your world. Use HumanMessage only for the immediate input.
Key Intuition: "Behavior lives in system messages."