LangChain Messages API Reference
In LangChain, whether it is ordinary chat, Agent tool calls, multi-turn conversations, or multimodal inputs such as images and audio, Messages are always involved.
Messages are the fundamental data structure for LangChain's interaction with chat models, used to distinguish system instructions, user input, AI replies, and tool execution results.
For example:
SystemMessage → 告诉模型应该如何回答
HumanMessage → 用户提出问题
AIMessage → 模型生成回答或工具调用
ToolMessage → 工具返回执行结果
This chapter is based on LangChain 1.x and covers common message types, the ContentBlock multimodal structure, ToolCall, message conversion, history trimming, and practical usage in Agents.
1. LangChain Message Type Quick Reference
LangChain message objects typically inherit from BaseMessage.
Common messages are as follows:
| Message types | Corresponding role | type Attribute | Main Use |
|---|---|---|---|
HumanMessage |
user | human | User input |
AIMessage |
assistant | ai | Model replies and tool call requests |
SystemMessage |
system | system | System instructions |
ToolMessage |
tool | tool | Tool execution result |
AIMessageChunk |
assistant | AIMessageChunk | Model streaming output chunks |
RemoveMessage |
No ordinary conversation role | remove | Request to delete a message in the state |
ChatMessage |
Custom role | chat | Custom message role |
Two concepts need to be distinguished here:
- **role:** The roles typically used by the model API, such as user, assistant, system, tool.
- **type:** The type identifier of the LangChain message object itself, such as human, ai, tool.
Therefore, the type of HumanMessage is human, which is not equal to user in the model API.
Also, although AIMessageChunk represents the assistant's streaming reply, its Python object's type is AIMessageChunk。
2. Creating Basic Messages
A precompiled binary is available from the langchain.messages Import common message classes.
Example: Creating message objects
Example
from
langchain.
messages
import
(
SystemMessage
,
HumanMessage
,
AIMessage
,
ToolMessage
)
system
=
SystemMessage
(
content
=
"You are a Python programming assistant."
)
human
=
HumanMessage
(
content
=
"What is Python?"
)
ai
=
AIMessage
(
content
=
"Python is a general-purpose programming language."
)
tool
=
ToolMessage
(
content
=
"Calculation result: 42"
,
tool_call_id
=
"call_001"
,
name
=
"calculator"
)
for
message
in
[
system
,
human
,
ai
,
tool
]
:
(
message.
type
,
message.
content
)
Output:
system 你是 Python 编程助手。
human 什么是 Python?
ai Python 是一种通用编程语言。
tool 计算结果:42
Note that the ToolMessage here is a separately created example object.
When actually sending to the model, the ToolMessage should be paired with the corresponding tool call request in the earlier AIMessage; you cannot arbitrarily insert a tool result without context.
3. Common Attributes of Message Objects
BaseMessage provides some common attributes.
| property | Description |
|---|---|
content |
Raw message content, which can be a string or a list of content blocks |
content_blocks |
Normalized list of multimodal ContentBlocks |
type |
LangChain message type |
id |
Message ID, which may be empty |
name |
Optional message name |
additional_kwargs |
Provider-specific additional data |
response_metadata |
Response metadata, such as model name or other statistical information |
Example: Reading message attributes
Example
from
langchain.
messages
import
HumanMessage
message
=
HumanMessage
(
content
=
"Introduce Python lists."
,
id
=
"user-msg-001"
,
name
=
"student"
)
(
"Type:"
,
message.
type
)
(
"Content:"
,
message.
content
)
(
"Message ID:"
,
message.
id
)
(
"Name:"
,
message.
name
)
(
"Standard content blocks:"
,
message.
content_blocks
)
If content is an ordinary string, LangChain can also represent it as a standard text content block.
**Note:** The message ID is not necessarily returned by the model provider. When a stable identifier is actually needed, you can assign an ID to the message at the application layer.
4. HumanMessage: User Messages
HumanMessage Used to represent user input.
It can contain plain text as well as multimodal content such as images and files when the model supports it.
Example: Ordinary user message
Example
from
langchain.
messages
import
HumanMessage
message
=
HumanMessage
(
content
=
"What is a Python dictionary?"
)
(
message.
type
)
(
message.
content
)
Output:
human
Python 字典是什么?
When calling a Chat Model or Agent, you usually do not need to manually create a HumanMessage; you can use a role dictionary directly.
5. SystemMessage: System Instructions
SystemMessage Used to provide the model with role settings, behavior rules, and other high-priority instructions.
Example
Example
from
langchain.
messages
import
SystemMessage
,
HumanMessage
messages
=
[
SystemMessage
(
content
=
"You are a programming teacher; please answer in concise Chinese."
)
,
HumanMessage
(
content
=
"Explain Python loop statements."
)
]
Messages are usually arranged in conversation order.
If you use create_agent(), a more common way is through system_prompt to set system instructions.
agent = create_agent(
model="deepseek:deepseek-chat",
tools=[],
system_prompt="You are a Python programming teacher."
)
It is not recommended to directly convert untrusted document content into a SystemMessage, because this raises the privilege of external data in the prompt.
6. AIMessage: Model Replies
AIMessage Represents the response generated by the model.
Besides text, it may also contain tool calls, Token usage, and model metadata.
Main attributes
| property | Purpose |
|---|---|
content |
Model content |
tool_calls |
List of valid tool calls |
invalid_tool_calls |
Tool calls that could not be parsed properly |
usage_metadata |
Token usage |
response_metadata |
Model response metadata |
id |
Message identifier |
Example: Viewing AIMessage
Example
from
dotenv
import
load_dotenv
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
model
=
init_chat_model
(
"deepseek:deepseek-chat"
)
response
=
model.
invoke
(
"Hello" (Chinese)
)
(
"Answer:"
,
response.
content
)
(
"Type:"
,
response.
type
)
(
"Tool calls:"
,
response.
tool_calls
)
(
"Token usage:"
,
response.
usage_metadata
)
(
"Response metadata:"
,
response.
response_metadata
)
If the provider returns Token data, usage_metadata may contain:
{
"input_tokens": 12,
"output_tokens": 20,
"total_tokens": 32
}
This is a sample format, not a real call result.
Different providers may vary in their support for Token usage, additional metadata, and content blocks.
7. ToolCall: Model Requests to Call Tools
ToolCall is used to represent the model's desire to call a tool.
Typically through:
AIMessage.tool_calls
to read it.
Common fields of a tool call include:
| Field | Description |
|---|---|
name |
Tool name |
args |
Tool arguments dictionary |
id |
Tool call ID |
type |
Tool call type identifier |
Example: Creating a tool call message
Example
from
langchain.
messages
import
AIMessage
ai
=
AIMessage
(
content
=
""
,
tool_calls
=
[
{
"name"
:
"get_weather"
,
"args"
:
{
"city"
:
"Hangzhou"
}
,
"id"
:
"call_weather_001"
,
"type"
:
"tool_call"
}
]
)
for
call
in
ai.
tool_calls
:
(
"Tool:"
,
call
[
"name"
]
)
(
"Arguments:"
,
call
[
"args"
]
)
(
"Call ID:"
,
call
[
"id"
]
)
**Important:** Creating AIMessage.tool_calls does not automatically execute the tool.
If you use the Chat Model directly, the application needs to execute the tool and then return the result to the model as a ToolMessage.
When using create_agent(), LangChain can automatically manage common tool call loops.
8. ToolMessage: Tool Execution Results
ToolMessage Used to represent the result returned after tool execution.
The most important attribute is:
tool_call_id
It must correspond to the ID of a ToolCall in the earlier AIMessage.
Common Properties
| property | Description |
|---|---|
content |
Tool result provided to the model |
tool_call_id |
Corresponding tool call ID |
name |
Tool name, optional |
status |
Execution status, such as success, error |
artifact |
Additional data that does not need to be sent directly to the model |
Example: Pairing tool requests and results
Example
from
langchain.
messages
import
AIMessage
,
ToolMessage
ai
=
AIMessage
(
content
=
""
,
tool_calls
=
[
{
"name"
:
"get_weather"
,
"args"
:
{
"city"
:
"Hangzhou"
}
,
"id"
:
"call_001"
,
"type"
:
"tool_call"
}
]
)
tool_result
=
ToolMessage
(
content
=
"Hangzhou mock weather: sunny, 25°C"
,
tool_call_id
=
"call_001"
,
name
=
"get_weather"
,
status
=
"success"
)
messages
=
[
ai
,
tool_result
]
(
ai.
tool_calls
[
0
]
[
"id"
]
)
(
tool_result.
tool_call_id
)
The two IDs must match:
call_001
call_001
If the model proposes multiple tool calls at once, you need to provide the correct tool response for each call according to the provider's protocol.
Do not arbitrarily insert unrelated user messages into a message sequence that has not yet responded to all tool calls.
9. Complete Tool Call Message Sequence
The following shows a valid model tool call interaction.
HumanMessage
↓
AIMessage(tool_calls)
↓
ToolMessage
↓
AIMessage(最终回答)
Example: Manually executing tools
Complete example
from
dotenv
import
load_dotenv
from
langchain.
chat_models
import
init_chat_model
from
langchain.
messages
import
HumanMessage
,
ToolMessage
from
langchain.
tools
import
tool
load_dotenv
(
)
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query simulated city weather."""
return
f
"{city}: mock sunny, 25°C"
model
=
init_chat_model
(
"deepseek:deepseek-chat"
)
model_with_tools
=
model.
bind_tools
(
[
get_weather
]
)
messages
=
[
HumanMessage
(
content
=
"Please use the tool to query the simulated weather in Hangzhou."
)
]
ai
=
model_with_tools.
invoke
(
messages
)
messages.
append
(
ai
)
for
call
in
ai.
tool_calls
:
if
call
[
"name"
]
==
"get_weather"
:
result
=
get_weather.
invoke
(
call
[
"args"
]
)
messages.
append
(
ToolMessage
(
content
=
result
,
tool_call_id
=
call
[
"id"
]
,
name
=
"get_weather"
)
)
if
ai.
tool_calls
:
final
=
model_with_tools.
invoke
(
messages
)
(
"Final answer: "
,
final.
content
)
else
:
(
"Model did not request a tool:"
,
ai.
content
)
This demonstrates three key steps of tool calling:
- The model generates an AIMessage containing tool_calls.
- The application executes the tool according to the call arguments and returns the corresponding ToolMessage.
- Put the tool execution result back into the message history, then call the model to generate an answer.
This example handles only one round of tool calls. If the model returns tool_calls again, you need to continue the loop.
In production, it is recommended to use create_agent() to manage the tool loop, execution count limits, and exception handling.
10. AIMessageChunk: Streaming Messages
When calling the model's stream() method, it typically returns progressively AIMessageChunk。
It represents an incremental fragment of the model output.
For example:
Chunk 1:Python
Chunk 2: 是一种
Chunk 3: 编程语言。
An actual Chunk does not necessarily correspond one-to-one with a single Token.
Example: Reading streaming messages
Example
from
langchain.
chat_models
import
init_chat_model
model
=
init_chat_model
(
"deepseek:deepseek-chat"
)
for
chunk
in
model.
stream
(
"Briefly introduce Python."
)
:
if
isinstance
(
chunk
.
content
,
str
)
:
(
chunk
.
content
,
end
=
""
,
flush
=
True
)
(
)
AIMessageChunk can have the following fields:
content: an increment of text or other content.tool_call_chunks: streaming fragments of tool call arguments.usage_metadata: Token information when available.chunk_position: chunk position markers in some streams.
Note that the type of AIMessageChunk is usually:
AIMessageChunk
not AIMessage's ai。
11. Merging Streaming Message Chunks
If you want not only to print text progressively but also to obtain a complete message object, you can merge multiple AIMessageChunks.
Example: Merging message increments
Example
from
langchain.
messages
import
AIMessageChunk
chunks
=
[
AIMessageChunk
(
content
=
"Python"
)
,
AIMessageChunk
(
content
=
" is a"
)
,
AIMessageChunk
(
content
=
" programming language."
)
]
merged
=
chunks
[
0
]
for
chunk
in
chunks
[
1
:
]
:
merged
=
merged +
chunk
(
merged.
content
)
Output:
Python 是一种 编程语言。
Here, the following is used + Merge message fragments.
In actual streaming tool calls, tool names and arguments may also be returned in batches and need to be processed according to LangChain's Chunk merging rules, rather than treating all tool argument fragments directly as complete JSON.
12. ContentBlock: Standardized Multimodal Content
LangChain 1.x provides a standardized ContentBlock structure for describing different content such as text, images, audio, video, and files.
A model message is not necessarily a single string; it may also contain multiple content blocks.
For example:
HumanMessage
|
├── TextContentBlock
└── ImageContentBlock
Common ContentBlock types:
| Type | type identifier | Purpose |
|---|---|---|
TextContentBlock |
text | Ordinary message text |
PlainTextContentBlock |
text-plain | Plain text file data such as TXT and Markdown |
ImageContentBlock |
image | Picture |
AudioContentBlock |
audio | Audio |
VideoContentBlock |
video | Video |
FileContentBlock |
file | File data such as PDF and Word |
ReasoningContentBlock |
reasoning | Reasoning-related content publicly returned by the model API |
NonStandardContentBlock |
non_standard | Non-standardized provider-specific content |
In addition, there are standard structures related to tool calls such as ToolCall, ServerToolCall, and ServerToolResult.
**Note:** ContentBlock is a unified data representation format and does not mean that all models support all modalities. Whether images, audio, PDF, or video can be sent still needs to be checked against the specific model and provider integration.
13. The Difference Between TextContentBlock and PlainTextContentBlock
These two names are quite similar, but their uses differ.
TextContentBlock
Represents ordinary message body text, for example:
{
"type": "text",
"text": "请解释 Python 列表"
}
PlainTextContentBlock
Used to represent plain text file data, such as Markdown and TXT file content.
{
"type": "text-plain",
"mime_type": "text/plain",
"text": "# Python 教程\n变量用于保存数据"
}
For ordinary chat, using a plain string or TextContentBlock is sufficient; there is no need to wrap every piece of ordinary text in a PlainTextContentBlock.
Example: Creating a standard text content block
Example
from
langchain.
messages
import
HumanMessage
from
langchain_core.
messages
.
content
import
create_text_block
message
=
HumanMessage
(
content
=
[
create_text_block
(
"What is Python?"
)
]
)
(
message.
content_blocks
)
create_text_block() can automatically create a text content block in the standard format.
14. Image Input ImageContentBlock
If you use a model that supports image understanding, you can add an image content block to the HumanMessage.
For example:
Example: Image message structure
from
langchain.
messages
import
HumanMessage
from
langchain_core.
messages
.
content
import
create_text_block
,
create_image_block
message
=
HumanMessage
(
content
=
[
create_text_block
(
"Please describe this image."
)
,
create_image_block
(
url
=
"https://example.com/sample.png"
,
mime_type
=
"image/png"
)
]
)
for
block
in
message.
content_blocks
:
(
block
[
"type"
]
)
Output:
text
image
The URL here is only for demonstrating the data structure and does not guarantee that a corresponding image exists.
Image content can use URLs, Base64 data, or other supported file reference methods according to the model API requirements.
**Note:** Use deepseek-chat and other chat models, do not assume they support image input. Choose a model that explicitly supports vision capabilities.
15. Audio, Video, and File Content Blocks
Standardized ContentBlock also covers the following types:
| Content-Type | Common data forms | Application scenarios |
|---|---|---|
| AudioContentBlock | Audio data, file references, etc. | Speech transcription, speech understanding |
| VideoContentBlock | Video data or frame information | Video content analysis |
| FileContentBlock | URL, Base64, file ID | PDF and other document inputs |
| PlainTextContentBlock | Text content or file references | TXT, Markdown documents |
For files that are not images, audio, or ordinary text, you can use FileContentBlock to represent them.
However, file input capabilities vary greatly across different models.
For example, some models support reading PDFs directly; others require developers to first use a Document Loader to extract text and then put the text into the message.
Therefore, you cannot assume that any chat model can directly analyze PDFs just because LangChain supports FileContentBlock.
16. content and content_blocks
In LangChain message objects, two fields are easily confused:
| property | Purpose |
|---|---|
content |
The raw or provider-related content representation of the message |
content_blocks |
Content blocks standardized by LangChain |
For example:
Example
from
langchain.
messages
import
AIMessage
message
=
AIMessage
(
content
=
"Hello, I am a Python assistant."
)
(
"Raw content:"
,
message.
content
)
(
"Standard content blocks:"
,
message.
content_blocks
)
If you only want to display ordinary text, you can usually just read content directly.
If you need to uniformly handle multimodal data from different providers, you can consider using content_blocks.
**Note:** Do not assume that all content is a string. Multimodal models may return a list of content blocks.
17. RemoveMessage: Deleting Messages
RemoveMessage Used to remove a specified message in state management that supports message deletion.
It is not an ordinary user chat message.
For example, LangGraph's messages state field typically uses add_messages Reducer。
If you need to delete an existing message, you can return the corresponding RemoveMessage.
Example: Deleting a specified message
Example
from
langchain.
messages
import
HumanMessage
,
AIMessage
,
RemoveMessage
from
langgraph.
graph
.
message
import
add_messages
messages
=
[
HumanMessage
(
content
=
"Old question"
,
id
=
"msg-001"
)
,
AIMessage
(
content
=
"Old answer"
,
id
=
"msg-002"
)
]
updated
=
add_messages
(
messages
,
[
RemoveMessage
(
id
=
"msg-001"
)
]
)
for
msg
in
updated:
(
msg.
id
,
msg.
content
)
Output:
msg-002 旧回答
Here, messages are deleted via the add_messages Reducer, not automatically through a normal Python list.
**Note:** RemoveMessage should be used with a Reducer that supports this semantics. For messages that do not contain a corresponding ID, the deletion operation may fail.
A formal Agent should also pay attention to message dependencies, for example, do not delete only the AIMessage of a tool call while keeping the ToolMessage that depends on it.
18. Why Can't Message History Be Directly Truncated?
Many beginners truncate history like this:
messages = messages[-10:]
For ordinary text conversations, this approach may sometimes work.
But for Agents that include tool calls, it may produce an invalid message sequence.
For example:
AIMessage(tool_calls=[...])
ToolMessage(tool_call_id="call_001")
If you happen to delete the AIMessage and keep only the ToolMessage, then the tool result loses its corresponding call request.
Therefore, when trimming Agent history, you should pay special attention to the valid order of messages.
For complex multi-turn tool calls, it is usually more appropriate to use LangChain Middleware or specialized conversation compression strategies.
19. trim_messages(): Trimming Message History
LangChain provides trim_messages(), which can trim a message list according to a specified budget.
It supports controlling length by Token count or using a custom counting method.
Main Parameters
| Parameters | Default value | Description |
|---|---|---|
messages |
Required | The message list to be trimmed |
max_tokens |
Required | Token or specified counting budget |
token_counter |
Required | Model, counting function, or approximate |
strategy |
last | Keep the first or last messages |
allow_partial |
False | Whether to allow keeping partial messages |
start_on |
None | Restrict the starting message type after trimming |
end_on |
None | Restrict the ending message type after trimming |
include_system |
False | Whether to keep the first SystemMessage |
text_splitter |
None | Text splitter used for partial trimming |
Example: Keeping recent conversations
Example
from
langchain.
messages
import
(
SystemMessage
,
HumanMessage
,
AIMessage
,
trim_messages
)
messages
=
[
SystemMessage
(
content
=
"You are a Python assistant."
)
,
HumanMessage
(
content
=
"What is a list?"
)
,
AIMessage
(
content
=
"A list can store multiple elements."
)
,
HumanMessage
(
content
=
"What is a dictionary?"
)
,
AIMessage
(
content
=
"A dictionary stores data using key-value pairs."
)
,
HumanMessage
(
content
=
"What is the difference between a list and a dictionary?"
)
]
trimmed
=
trim_messages
(
messages
,
max_tokens
=
80
,
strategy
=
"last"
,
token_counter
=
"approximate"
,
include_system
=
True
,
start_on
=
"human"
,
end_on
=
(
"human"
,
"tool"
)
)
for
msg
in
trimmed:
(
msg.
type
,
msg.
content
)
Here, token_counter="approximate" Using approximate Token counting is suitable for scenarios that need a quick estimate of context length.
It does not guarantee complete consistency with the actual Token billing count of a specific model provider.
The final number of retained messages in the example depends on the actual counting result.
20. Trimming by Message Count
If you only want to keep a fixed number of messages, you can also pass in:
token_counter=len
In this case, max_tokens actually represents a message count budget, not the model Token count.
Example
Example
trimmed
=
trim_messages
(
messages
,
max_tokens
=
4
,
strategy
=
"last"
,
token_counter
=
len
,
include_system
=
True
,
start_on
=
"human"
)
for
msg
in
trimmed:
(
msg.
type
,
msg.
content
)
This approach is simpler, but it cannot reflect the actual Token length of different messages.
For example, a message of 5000 characters and a message containing only "hello" both count as one when counting by message number.
**Recommendation:** For context control in production environments, you should prioritize combining with the actual Token budget rather than relying only on message count.
21. filter_messages(): Filtering Messages
If you only want to extract a certain type of message, you can use filter_messages()。
For example, to view only user messages.
Example: Filtering HumanMessage
Example
from
langchain.
messages
import
filter_messages
messages
=
[
HumanMessage
(
content
=
"Hello" (Chinese)
)
,
AIMessage
(
content
=
"Hello!"
)
,
HumanMessage
(
content
=
"Introduce Python"
)
,
AIMessage
(
content
=
"Python is a programming language"
)
]
users
=
filter_messages
(
messages
,
include_types
=
"human"
)
for
msg
in
users:
(
msg.
content
)
Output:
你好
介绍 Python
You can also filter by message ID, name, or message type.
For example:
filter_messages(messages, exclude_types="system")
Used to exclude SystemMessage.
22. convert_to_messages(): Converting Message Formats
LangChain can express chat messages in multiple ways.
For example:
("user", "你好")
{"role": "user", "content": "你好"}
HumanMessage(content="Hello")
convert_to_messages() Supported message representations can be converted into message objects.
Example
Example
from
langchain.
messages
import
convert_to_messages
raw_messages
=
[
(
"system"
,
"You are a Python assistant."
)
,
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
,
(
"assistant"
,
"Hello!"
)
]
messages
=
convert_to_messages
(
raw_messages
)
for
msg
in
messages:
(
type
(
msg
)
.name
,
msg.
content
)
Output:
SystemMessage 你是 Python 助手。
HumanMessage 你好
AIMessage 你好!
This is very practical when you need to be compatible with different historical message formats.
23. merge_message_runs(): Merging Consecutive Messages
If there are multiple consecutive messages of the same type in a message list, you can use merge_message_runs() to merge them.
Example
Example
from
langchain.
messages
import
merge_message_runs
messages
=
[
HumanMessage
(
content
=
"Please introduce Python."
)
,
HumanMessage
(
content
=
"It should be suitable for complete beginners."
)
,
AIMessage
(
content
=
"Python is a programming language."
)
]
merged
=
merge_message_runs
(
messages
)
for
msg
in
merged:
(
msg.
type
,
msg.
content
)
This function can merge adjacent messages of the same type.
But note:
- It only processes consecutive messages that can be merged.
- Not all message types are suitable for merging.
- ToolMessage is usually not merged because it has an independent tool_call_id.
Therefore, do not use the merge function to arbitrarily modify an unfinished tool call message sequence.
24. MessageLikeRepresentation: Shortcut Message Format
LangChain supports multiple message input formats in many model and Agent APIs.
Common forms:
| Format | Example |
|---|---|
| String | "你好" |
| Message object | HumanMessage(content="Hello") |
| Tuple | ("user", "你好") |
| Dictionaries | {"role": "user", "content": "你好"} |
For example, calling the Chat Model directly:
model.invoke("你好")
or:
model.invoke([
("system", "你是助手"),
("user", "你好")
])
Calling the Agent:
agent.invoke({
"messages": [
{"role": "user", "content": "你好"}
]
})
For simple development, using dictionaries or tuples is more convenient.
If you need to directly read and process attributes such as message.id, tool_calls, and metadata, using explicit message objects is usually more convenient.
25. LangChain Messages and Conversation Memory
The message history in an Agent's multi-turn conversation is usually stored in the State.
For example:
{
"messages": [
HumanMessage(content="I am learning Python"),
AIMessage(content="OK"),
HumanMessage(content="Recommended learning path")
]
}
LangGraph's default messages state is typically managed through add_messages a Reducer.
This means:
- New messages are usually appended.
- Messages with the same ID can replace existing messages.
- RemoveMessage can request the deletion of a specified message.
But merely creating a messages list does not mean the Agent can automatically remember history across program restarts.
To achieve multi-turn memory, you need to use a Checkpointer according to the application.
If you need to store user preferences long-term, you can further combine with a Store.
26. Complete Example: Comprehensive Use of the Messages API
The following example, which can be run directly, demonstrates message creation, attribute reading, tool call formatting, message filtering, and message trimming.
Filename:messages_api_demo.py
Installation:
pip install -U langchain langchain-core
This example uses only local mock messages and does not require an API Key.
Complete example
from
langchain.
messages
import
(
SystemMessage
,
HumanMessage
,
AIMessage
,
AIMessageChunk
,
ToolMessage
,
RemoveMessage
,
trim_messages
,
filter_messages
,
convert_to_messages
)
from
langgraph.
graph
.
message
import
add_messages
========== 1. Basic Messages ==========
messages
=
[
SystemMessage
(
content
=
"You are a Python assistant."
,
id
=
"sys-001"
)
,
HumanMessage
(
content
=
"Hello" (Chinese)
,
id
=
"user-001"
)
,
AIMessage
(
content
=
"Hello!"
,
id
=
"ai-001"
)
,
HumanMessage
(
content
=
"Introduce Python lists."
,
id
=
"user-002"
)
,
AIMessage
(
content
=
"A list can hold multiple elements."
,
id
=
"ai-002"
)
]
(
"=== Basic Messages ==="
)
for
msg
in
messages:
(
msg.
type
,
msg.
content
)
========== 2. ToolCall + ToolMessage ==========
tool_request
=
AIMessage
(
content
=
""
,
id
=
"ai-tool-001"
,
tool_calls
=
[
{
"name"
:
"get_weather"
,
"args"
:
{
"city"
:
"Hangzhou"
}
,
"id"
:
"call-001"
,
"type"
:
"tool_call"
}
]
)
tool_result
=
ToolMessage
(
content
=
"Hangzhou mock weather: sunny, 25°C"
,
tool_call_id
=
"call-001"
,
name
=
"get_weather"
,
id
=
"tool-msg-001"
)
(
"\n=== Tool Calls ==="
)
(
tool_request.
tool_calls
)
(
tool_result.
tool_call_id
)
========== 3. Streaming Message Merging ==========
chunk1
=
AIMessageChunk
(
content
=
"Python"
)
chunk2
=
AIMessageChunk
(
content
=
" is easy to get started with."
)
merged
=
chunk1 + chunk2
(
"\n=== Chunk Merging ==="
)
(
merged.
content
)
========== 4. Message Trimming ==========
trimmed
=
trim_messages
(
messages
,
max_tokens
=
4
,
strategy
=
"last"
,
token_counter
=
len
,
include_system
=
True
,
start_on
=
"human"
)
(
"\n=== Trimming Result ==="
)
for
msg
in
trimmed:
(
msg.
type
,
msg.
content
)
========== 5. Message Filtering ==========
users
=
filter_messages
(
messages
,
include_types
=
"human"
)
(
"\n=== User Messages ==="
)
for
msg
in
users:
(
msg.
content
)
========== 6. Message Conversion ==========
converted
=
convert_to_messages
(
[
(
"user"
,
"What is a dictionary?"
)
,
(
"assistant"
,
"A dictionary stores data through key-value pairs."
)
]
)
(
"\n=== Format Conversion ==="
)
for
msg
in
converted:
(
type
(
msg
)
.name
,
msg.
content
)
========== 7. Message Deletion ==========
updated
=
add_messages
(
messages
,
[
RemoveMessage
(
id
=
"user-001"
)
]
)
(
"\n=== After Deleting Messages ==="
)
for
msg
in
updated:
(
msg.
id
,
msg.
content
)
This program does not call a model, so the above message objects and helper functions can be tested without an internet connection.
For specific trimming results, refer to the currently installed LangChain version and configuration.
27. Frequently asked questions
1. What is the difference between HumanMessage and role=user?
HumanMessage is a LangChain message object; user is a role name in the chat model API.
2. Is the type of AIMessage assistant?
No. The type of AIMessage is usually ai; assistant is the corresponding conversation role.
3. Is the type of AIMessageChunk ai?
No. Python's AIMessageChunk uses its own type identifier AIMessageChunk.
4. What is the difference between ToolCall and ToolMessage?
ToolCall is the model's tool call request; ToolMessage is the returned message after the tool is actually executed.
5. Why does ToolMessage need tool_call_id?
Because the model may request multiple tools at once, the results need to be matched to the original requests via IDs.
6. Does bind_tools() automatically create a ToolMessage?
No. bind_tools() mainly enables the model to generate tool call requests; actual tool execution is usually handled by application code or an Agent.
7. Is content always a string?
Not necessarily. Multimodal messages may contain a list of content blocks.
8. What is the difference between TextContentBlock and PlainTextContentBlock?
The former is for ordinary text; the latter is mainly for plain-text file data such as TXT and Markdown.
9. Can ImageContentBlock be used with any Chat Model?
No. The model must support image input, and the provider integration must be able to handle the corresponding content format.
10. Is an AIMessageChunk always a single Token?
No. A Chunk represents a streaming increment and may contain the content of one or more Tokens.
11. How to merge multiple AIMessageChunks?
You can use the + operator to aggregate multiple Chunks of the same message.
12. Why do tool calls fail after trim_messages()?
Possibly because trimming broke the relationship between AIMessage.tool_calls and the corresponding ToolMessage; a valid message sequence must be preserved.
13. Does token_counter=len mean counting by Token?
No. It means counting by number of messages.
14. Does RemoveMessage directly delete Python list elements?
No. It needs to be processed by a message Reducer that supports deletion semantics.
15. How to get only user messages?
You can use filter_messages(messages, include_types="human").
16. How to convert a dict into a message object?
You can use convert_to_messages().
17. Do Chat Model and Agent use the same message types?
They usually share the LangChain Messages system, but an Agent also combines tool messages, state updates, and a Checkpointer to manage the full execution flow.
18. Can Messages store long-term user preferences?
Message history can provide conversation context, but long-term cross-session preferences are better stored using a Store or a business database.
Summary
The Messages API is one of the core foundations of LangChain 1.x.
This chapter introduces:
HumanMessage: user message.AIMessage: model reply.SystemMessage: system instruction.ToolMessage: tool execution result.AIMessageChunk: streaming message increment.ToolCall: model tool call request.RemoveMessage: delete state message.TextContentBlock: plain text.ImageContentBlock、AudioContentBlocketc.: multimodal data.content_blocks: standardized content block.trim_messages(): trim message history.filter_messages(): filter messages.convert_to_messages(): convert message format.merge_message_runs(): merge consecutive messages.
The most basic chat message structure:
messages = [
SystemMessage(content="You are an assistant"),
HumanMessage(content="Hello"),
AIMessage(content="Hello!")
]
The basic structure of a tool call:
HumanMessage
↓
AIMessage(tool_calls)
↓
ToolMessage(tool_call_id)
↓
AIMessage(最终回答)
**Core principle:** LangChain Messages are not just chat text containers; they also handle role distinction, tool call association, streaming increments, multimodal content representation, and state updates.
Only after understanding the message structure can you use Agent, Middleware, Checkpointer, Streaming, and Human-in-the-Loop more accurately.