Messages: a conversation as a list
Before any model or agent, there is the conversation. A chat model reads a list of messages and adds one to it. LangChain gives each kind of message its own class.
A conversation can live in a plain Python list, one dictionary per turn. Each has a role, who is speaking, and content, what they said.
conversation = [
{"role": "system", "content": "You help customers of a small online shop."},
{"role": "user", "content": "Where is my order A17?"},
]
for turn in conversation:
print(f"{turn['role']:<7} {turn['content']}")The system turn tells the model how to behave. The user turn is the customer. A model's reply would be a third dictionary with the role assistant.
The same conversation as message objects
LangChain has one class per role. They work with every provider, so the same list can go to any model.
from langchain.messages import AIMessage, HumanMessage, SystemMessage
conversation = [
SystemMessage("You help customers of a small online shop."),
HumanMessage("Where is my order A17?"),
AIMessage("Order A17 shipped on 3 March."),
]
for message in conversation:
print(f"{message.type:<7} {message.text}")Each message has a type, and text gives its text. The type of a user turn is human and a model turn is ai. Models and agents also accept the dictionary form and convert it to these classes.
Printing a message readably
pretty_print shows a message with a header naming its type, which is easier to read once a conversation gets long.
from langchain.messages import HumanMessage
HumanMessage("Where is my order A17?").pretty_print()There is a fourth type, ToolMessage, which carries a tool's result back to the model. It arrives in lesson 6, once there is a tool to produce one.
- Add a second
HumanMessageasking about order B22 and print the list again. - Call
pretty_print()on theAIMessageand compare its header with the human one. - Print
SystemMessage("x").typeand see which name it uses.
You understood something today that you didn't yesterday.