LangChainLangChain 1.4 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
43 small wins to finish your pathNext lesson

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.

Example
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.

Example
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.

Example
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.

Try it yourself
  • Add a second HumanMessage asking about order B22 and print the list again.
  • Call pretty_print() on the AIMessage and compare its header with the human one.
  • Print SystemMessage("x").type and see which name it uses.

You understood something today that you didn't yesterday.