Understanding LangChain Message Types: Human, AI, System, and Tool Messages
This guide explains how LangChain structures interactions with chat models using role‑based Message objects—HumanMessage, AIMessage, SystemMessage, ToolMessage, and others—detailing their purposes, code examples, and how they enable multi‑turn AI agent workflows.
All interactions with a ChatModel are performed through structured Message objects that contain content and a role indicating the speaker.
This role‑based format is the standard input for modern chat models such as GPT‑4, Claude 3, and Gemini, enabling complex multi‑turn conversations.
LangChain wraps these messages in classes that inherit from BaseMessage. The most common subclasses are:
1. HumanMessage
Role: human Purpose: Represents the end‑user’s input, i.e., the question or instruction sent to the model.
2. AIMessage
Role: ai Purpose: Holds the model’s response. When placed back into the message history it provides context for subsequent calls. It can also contain a tool_calls field when the model wants to invoke a tool.
3. SystemMessage
Role: system Purpose: Sets high‑level instructions, persona, or context for the AI. It is usually the first element in the message list, e.g., “You are a professional Python programmer; answer only with code.”
4. ToolMessage
Role: tool Purpose: Returns the result of a tool (function) execution to the model. After the model issues a tool_calls entry in an AIMessage, the tool is run and its output is wrapped in a ToolMessage together with the corresponding tool_call_id.
Other message types
FunctionMessage: legacy name for ToolMessage, kept for backward compatibility. ChatMessage: a generic message class that lets you specify any role manually, useful for non‑standard roles.
from langchain_core.messages import ChatMessage
# Equivalent to HumanMessage(content="你好")
message = ChatMessage(role="human", content="你好")Mastering these message classes is the foundation for building advanced agents with ChatModel. The chapter’s examples instantiate each type and demonstrate how they combine to form a complete dialogue flow.
BirdNest Tech Talk
Author of the rpcx microservice framework, original book author, and chair of Baidu's Go CMC committee.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
