Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain message type

LangChain message type

In LangChain, chat models and Agents interact mainly through Messages (Message).

Messages can contain not only ordinary text, but also system instructions, tool calls, tool execution results, and multimodal content such as images.

Understanding LangChain's message types helps in developing multi-turn conversations, Agents, tool calls, and multimodal AI applications.

This section is based on the LangChain 1.x message API and introduces common message types, message attributes, streaming messages, and message history management.


I. Core message types of LangChain

The four commonly used message types in LangChain are:

Message types Role Main Use
HumanMessage User Represents a question or content sent by the user
AIMessage AI assistants Represents a model reply, which may also contain tool calls
SystemMessage System Sets the model's role, task, and behavior rules
ToolMessage Tool Stores tool execution results and associates the corresponding tool calls

A simple conversation can be represented as:

SystemMessage:你是一名 Python 编程助手。



HumanMessage:什么是 Python?



AIMessage:Python 是一种通用编程语言。

If tools are used, the message flow may become:

HumanMessage

    ↓

AIMessage(包含 tool_calls)

    ↓

ToolMessage(工具执行结果)

    ↓

AIMessage(最终回答)

These messages form a message list, which provides conversation context to the chat model.


II. HumanMessage: user message

HumanMessage Used to represent content sent by the user to the chat model.

For example:

Example

from

langchain.

messages

import

HumanMessage

Create a user message

message

=

HumanMessage

(

    content

=

"What is Runoob Tutorial RUNOOB?"

)

print

(

"Message type:"

,

message.

type

)

print

(

"Message content:"

,

message.

content

)

print

(

"Message ID:"

,

message.

id

)

Possible output:

消息类型: human

消息内容: Runoob Tutorial RUNOOB 是什么?

消息 ID: None

Where:

**Note:** You cannot directly assume HumanMessage the object has a role attribute. LangChain message objects usually use type to identify the message type, while OpenAI-style message dicts use role fields are read.

Call a model using HumanMessage

Example

from

dotenv

import

load_dotenv

from

langchain.

messages

import

HumanMessage

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

messages

=

[

    HumanMessage

(

        content

=

"Introduce Runoob Tutorial RUNOOB in one sentence."

   

)

]

response

=

model.

invoke

(

messages

)

print

(

response.

content

)

The model usually returns an AIMessage object containing the generated reply.

This example requires installing langchain、langchain-deepseek and python-dotenvin advance, and configuring DEEPSEEK_API_KEY。

Shortcut notation for HumanMessage

Besides creating message objects directly, LangChain also supports describing messages via tuples and dicts.

Example

from

langchain.

messages

import

HumanMessage

Method 1: message object

msg1

=

HumanMessage

(

content

=

"Hello" (Chinese)

)

Method 2: tuple

msg2

=

(

"user"

,

"Hello" (Chinese)

)

Method 3: dict

msg3

=

{

   

"role"

:

"user"

,

   

"content"

:

"Hello" (Chinese)

}

print

(

type

(

msg1

)

)

print

(

msg2

)

print

(

msg3

)

Note that tuples and dicts themselves do not immediately become HumanMessage object.

Only when passed to a LangChain API that accepts the MessageLike format will the framework perform message conversion as needed.

For example:

messages = [

    ("system", "你是一名编程助手"),

    ("user", "介绍 Python")

]



response = model.invoke(messages)

This notation can reduce code that repeatedly creates message objects.


III. AIMessage: AI reply

AIMessage Represents a message generated by a language model.

Besides ordinary text, AIMessage can also contain tool call information, Token usage statistics, and response metadata.

Create a regular AIMessage

Example

from

langchain.

messages

import

AIMessage

message

=

AIMessage

(

    content

=

"Runoob Tutorial is an online programming learning platform."

)

print

(

"Type:"

,

message.

type

)

print

(

"Content:"

,

message.

content

)

print

(

"Tool calls:"

,

message.

tool_calls

)

Execution result:

类型: ai

内容: Runoob Tutorial是一个在线编程学习平台。

工具调用: []

Here, tool_calls is an empty list, indicating that this message provides no standardized tool call request.

AIMessage with tool calls

When the model needs to call a tool, it can use tool_calls to return the tool name and arguments.

Example

from

langchain.

messages

import

AIMessage

message

=

AIMessage

(

    content

=

""

,

    tool_calls

=

[

       

{

           

"name"

:

"get_weather"

,

           

"args"

:

{

               

"city"

:

"Hangzhou"

           

}

,

           

"id"

:

"call_001"

,

           

"type"

:

"tool_call"

       

}

   

]

)

print

(

"Message content:"

,

message.

content

)

for

call

in

message.

tool_calls

:

   

print

(

"Tool name:"

,

call

[

"name"

]

)

   

print

(

"Tool arguments:"

,

call

[

"args"

]

)

   

print

(

"Call ID:"

,

call

[

"id"

]

)

Execution result:

消息内容:

工具名称: get_weather

工具参数: {'city': '杭州'}

调用 ID: call_001

Here a message with a tool call request is constructed manually, only to demonstrate the data structure.

In actual calls, the tool call ID is usually generated by the model service.

One thing to note in particular:The presence of tool_calls in an AIMessage does not mean the tool has been executed.

The tool must be executed by the application or Agent.

Additional information of AIMessage

The AIMessage returned by the model may also provide the following information:

property Description
content Content generated by the model
tool_calls Valid tool call requests
invalid_tool_calls Tool calls that could not be parsed normally
response_metadata Model response metadata
usage_metadata Standardized Token usage statistics
id Message identifier

Example: view model response information

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

   

"Introduce Runoob Tutorial RUNOOB."

)

print

(

"Content:"

,

response.

content

)

print

(

"Message ID:"

,

response.

id

)

Response metadata returned by the provider

print

(

"Response metadata:"

)

print

(

response.

response_metadata

)

Standardized Token usage

usage

=

response.

usage_metadata

if

usage:

   

print

(

"Input Tokens:"

,

usage.

get

(

"input_tokens"

)

)

   

print

(

"Output Tokens:"

,

usage.

get

(

"output_tokens"

)

)

   

print

(

"Total Tokens:"

,

usage.

get

(

"total_tokens"

)

)

else

:

   

print

(

"No standardized Token statistics returned"

)

Fields returned by different model providers response_metadata may differ.

For example, the names of fields such as model name and finish reason are not guaranteed to be completely consistent, so you should not rely on a fixed metadata structure.

usage_metadata is a standardized usage field provided by LangChain, but it also depends on whether the provider returns the relevant data.


IV. SystemMessage: system instruction

SystemMessage Usually used to provide system-level instructions to the model, such as role setting, answering style, and task requirements.

It is generally placed at the beginning of the message list.

Example: set answering style

Example

from

langchain.

messages

import

(

    SystemMessage

,

    HumanMessage

)

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

messages

=

[

    SystemMessage

(

        content

=

(

           

"You are a Python programming tutorial author."

           

"The answer should be concise and accurate,"

           

"try to use language that beginners can easily understand."

       

)

   

)

,

    HumanMessage

(

        content

=

"What is a Python decorator?"

   

)

]

response

=

model.

invoke

(

messages

)

print

(

response.

content

)

The model refers to the system instruction to organize its answer.

For example, you can require through SystemMessage:

**Note:** System instructions can influence model behavior, but cannot guarantee that the model strictly follows all requirements.

For business rules that must be enforced, such as user permissions, file access scope, and payment verification, they should still be implemented in the application and not rely solely on SystemMessage.


V. ToolMessage: tool execution result

ToolMessage Used to store information returned after tool execution.

Each tool result needs to be associated with the previous tool call request via tool_call_id the corresponding tool_call_id.

Example: complete tool call messages

Example

from

langchain.

messages

import

(

    HumanMessage

,

    AIMessage

,

    ToolMessage

)

from

langchain.

chat_models

import

init_chat_model

Manually construct a tool call history

messages

=

[

    HumanMessage

(

        content

=

"Based on simulated data, how is the weather in Hangzhou?"

   

)

,

   

Simulate the model requesting a tool call

    AIMessage

(

        content

=

""

,

        tool_calls

=

[

           

{

               

"name"

:

"get_weather"

,

               

"args"

:

{

                   

"city"

:

"Hangzhou"

               

}

,

               

"id"

:

"call_weather_001"

,

               

"type"

:

"tool_call"

           

}

       

]

   

)

,

   

Simulate the tool having executed and returned a result

    ToolMessage

(

        content

=

"Sunny, 25°C, humidity 60%"

,

        name

=

"get_weather"

,

        tool_call_id

=

"call_weather_001"

   

)

]

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

messages

)

print

(

response.

content

)

The model can generate a similar answer based on the tool result:

根据提供的模拟数据,杭州天气晴,

气温25°C,湿度60%。

Note here:

Mismatched or missing tool results may cause the model API to reject the request; the specific behavior depends on the provider.

**Note:** The weather data in this example is simulated, not a real-time query result.

Other attributes of ToolMessage

Besides content and tool_call_id, ToolMessage also supports some additional fields.

For example, in some scenarios you can use artifact to store the complete tool result that does not need to be sent directly to the model:

Example

from

langchain.

messages

import

ToolMessage

message

=

ToolMessage

(

    content

=

"Found 3 matching records"

,

    tool_call_id

=

"call_search_001"

,

    name

=

"search_database"

,

    artifact

=

{

       

"records"

:

[

           

{

"id"

:

1

,

"name"

:

"Python"

}

,

           

{

"id"

:

2

,

"name"

:

"Java"

}

,

           

{

"id"

:

3

,

"name"

:

"Go"

}

       

]

   

}

)

print

(

message.

content

)

print

(

message.

artifact

)

content can store a brief result for the model,artifact can store supplementary data needed by the application.

However,artifact is not something the model automatically understands or uses; the specific handling depends on the application.


VI. AIMessageChunk: streaming message fragment

Use stream() , the model can return message fragments step by step.

For common chat models, streaming responses usually contain AIMessageChunk。

Unlike a complete AIMessage , a message fragment may contain only partial text or partial tool call information.

Example: streaming output

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

print

(

"Starting streaming output:"

)

for

chunk

in

model.

stream

(

   

"Introduce Runoob Tutorial RUNOOB in one sentence."

)

:

   

print

(

       

chunk

.

text

,

        end

=

""

,

        flush

=

True

   

)

print

(

)

chunk.text Used to get the text content in a message fragment.

Note that streaming responses do not necessarily contain only text. Some models may return thinking information, tool call fragments, or other content.

Merge message fragments

LangChain supports using + to merge compatible message fragments.

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

full_chunk

=

None

for

chunk

in

model.

stream

(

"Introduce Python."

)

:

   

if

full_chunk

is

None

:

        full_chunk

=

chunk

   

else

:

        full_chunk

=

full_chunk +

chunk

if

full_chunk

is

not

None

:

   

print

(

"Complete text:"

)

   

print

(

full_chunk.

text

)

   

print

(

"Message type:"

)

   

print

(

type

(

full_chunk

)

)

This approach suits applications that need to accumulate streaming responses, tool call argument fragments, or statistics.

**Note:** When streaming output contains tool calls, you should not treat each tool call fragment directly as complete JSON arguments; you should wait for and merge the necessary fragments.


VII. LangChain message attributes quick reference

Message types type Common Properties Main Use
HumanMessage human content、id User input
AIMessage ai content、tool_calls、usage_metadata Model reply
SystemMessage system content System instructions
ToolMessage tool content、tool_call_id、name、artifact Tool result
AIMessageChunk ai content、tool_call_chunks Streaming model response
RemoveMessage remove id Delete a specified message in a state update

AIMessageChunk Although it can also display type="ai", but it is a different Python type from a complete AIMessage message.

In addition, LangChain message types are constantly expanding; besides the common types above, there are also ChatMessage and other message classes for custom roles.


VIII. ContentBlock: structured message content

Most of the previous examples use strings as content。

but in real applications, messages may also contain images, audio, video, files, and other structured information.

LangChain 1.x provides a standardized Content Blocks mechanism to represent these different types of content.

Common ContentBlock types

Type Description
TextContentBlock Plain text content
ImageContentBlock Image content
AudioContentBlock Audio content
VideoContentBlock Video content
FileContentBlock File content such as PDF and Word
PlainTextContentBlock Plain-text file content, such as TXT files
ReasoningContentBlock Standardized reasoning content provided by the model

A special distinction needs to be made:

In addition,ToolCall is usually stored in AIMessage's tool_calls field rather than being treated simply as an image or text content block.

Example: build a text content block

Example

from

langchain.

messages

import

HumanMessage

Plain string message

simple_message

=

HumanMessage

(

    content

=

"Hello, LangChain!"

)

Use a standardized text content block

block_message

=

HumanMessage

(

    content_blocks

=

[

       

{

           

"type"

:

"text"

,

           

"text"

:

"Hello, LangChain!"

       

}

   

]

)

print

(

simple_message.

content

)

print

(

block_message.

content_blocks

)

Pass content_blocks gives access to the standardized message content blocks.

The difference between content in Vue 2,content_blocks is more suitable for handling multimodal content formats from different providers.


IX. Multimodal messages: text and images

For models that support image input, text and images can be provided together in the same message.

For example, ask the model to describe a webpage screenshot.

**Note:** Not all chat models support image input. Whether multimodal is supported needs to be checked against the actual capabilities of the current model and its API.

This section uses OpenAI's vision model to demonstrate the message structure, and does not use DeepSeek Flash as the default image example.

Example: ask a question via an image URL

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

from

langchain.

messages

import

HumanMessage

load_dotenv

(

)

Use a model that supports image input

model

=

init_chat_model

(

   

"openai:gpt-4o"

)

messages

=

[

    HumanMessage

(

        content

=

[

           

{

               

"type"

:

"text"

,

               

"text"

:

"Please describe the main content of this image."

           

}

,

           

{

               

"type"

:

"image_url"

,

               

"image_url"

:

{

                   

"url"

:

"https://www.langchain.com/images/brand/langchain_logo_text_w_white.png"

               

}

           

}

       

]

   

)

]

response

=

model.

invoke

(

messages

)

print

(

response.

content

)

The above uses an OpenAI-compatible multimodal message format.

If using other providers, their underlying image formats may differ. LangChain also provides standardized ImageContentBlock to reduce format differences between providers.

Example: standardized image content block

Example

from

langchain.

messages

import

HumanMessage

message

=

HumanMessage

(

    content_blocks

=

[

       

{

           

"type"

:

"text"

,

           

"text"

:

"Please describe this image."

       

}

,

       

{

           

"type"

:

"image"

,

           

"url"

:

"https://www.langchain.com/images/brand/langchain_logo_text_w_white.png"

       

}

   

]

)

for

block

in

message.

content_blocks

:

   

print

(

block

)

A standardized image block usually uses type="image"。

Images can be provided via URL, Base64 data, or a file ID supported by some providers.

Example: read a local image

If you need to use a local image, you can first convert it to Base64 encoding.

Example

import

base64

from

pathlib

import

Path

from

langchain.

messages

import

HumanMessage

Read a local PNG image

image_path

=

Path

(

"screenshot.png"

)

image_base64

=

base64

.

b64encode

(

    image_path.

read_bytes

(

)

)

.

decode

(

"utf-8"

)

message

=

HumanMessage

(

    content_blocks

=

[

       

{

           

"type"

:

"text"

,

           

"text"

:

"Please describe the main content in the screenshot."

       

}

,

       

{

           

"type"

:

"image"

,

           

"base64"

: image_base64

,

           

"mime_type"

:

"image/png"

       

}

   

]

)

print

(

"Number of content blocks:"

,

len

(

message.

content_blocks

)

)

The above code shows how to create a message containing local image data; it does not automatically call a model.

Later you can pass message to a chat model that supports image input.

**Note:** Image uploads may incur additional Tokens or fees; the actual limits are determined by the model provider.


X. ToolCall: tool call request

In Agent and Tool Calling scenarios, the model may return one or more tool call requests.

Each tool call usually contains:

Example: manually build a ToolCall

Example

from

langchain.

messages

import

AIMessage

tool_call

=

{

   

"name"

:

"get_weather"

,

   

"args"

:

{

       

"city"

:

"Hangzhou"

   

}

,

   

"id"

:

"call_001"

,

   

"type"

:

"tool_call"

}

message

=

AIMessage

(

    content

=

""

,

    tool_calls

=

[

tool_call

]

)

print

(

message.

tool_calls

[

0

]

[

"name"

]

)

print

(

message.

tool_calls

[

0

]

[

"args"

]

)

print

(

message.

tool_calls

[

0

]

[

"id"

]

)

Execution result:

get_weather

{'city': '杭州'}

call_001

LangChain's ToolCall is a structured data type. In teaching code, you can directly use a dict that matches the format to build a tool call.

Correctly determine whether a tool call exists

You should check:

if response.tool_calls:

    print("模型请求调用工具")

Not recommended:

if not response.content:

    print("模型请求调用工具")

Because content being empty does not necessarily mean the model requested a tool.

If you need to check tool calls that failed to parse, you can also look at:

print(response.invalid_tool_calls)


XI. trim_messages(): trim message history

As a conversation grows longer, the message history may exceed the context window allowed by the model.

trim_messages() Used to trim the message list according to a specified count or Token budget.

For example, you can prioritize keeping the most recent conversation while retaining the initial system instruction.

Common parameters

Parameters Description
messages The message list to trim
max_tokens Message length budget, whose meaning depends on the counter
token_counter Token counting function, model, or approximate
strategy first keeps the earliest content, last keeps the most recent content
include_system Keep the initial system message when conditions are met
start_on Specify which message type the trimmed messages start with
allow_partial Whether to allow keeping partial content of a message
end_on Specify the message type with which the trim result ends

Example: Keeping recent conversations

Example

from

langchain.

messages

import

(

    HumanMessage

,

    AIMessage

,

    SystemMessage

,

    trim_messages

)

messages

=

[

    SystemMessage

(

        content

=

"You are the AI assistant of Runoob Tutorial RUNOOB."

   

)

,

    HumanMessage

(

content

=

"How to get started with Python?"

)

,

    AIMessage

(

content

=

"It is recommended to learn basic syntax first."

)

,

    HumanMessage

(

content

=

"Which IDE is recommended?"

)

,

    AIMessage

(

content

=

"You can use VS Code or PyCharm."

)

,

    HumanMessage

(

content

=

"How to install third-party libraries?"

)

,

    AIMessage

(

content

=

"You can use pip install."

)

,

    HumanMessage

(

content

=

"What is NumPy?"

)

,

    AIMessage

(

content

=

"NumPy is a Python numerical computing library."

)

,

    HumanMessage

(

content

=

"What is the difference between pandas and NumPy?"

)

]

Demonstrating trimming by message count gives more intuitive results

trimmed

=

trim_messages

(

    messages

,

    max_tokens

=

5

,

    strategy

=

"last"

,

    token_counter

=

len

,

    include_system

=

True

,

    start_on

=

"human"

)

print

(

"Before trimming:"

,

len

(

messages

)

)

print

(

"After trimming:"

,

len

(

trimmed

)

)

for

message

in

trimmed:

   

print

(

message.

type

,

message.

content

)

Here, the following is used token_counter=len, therefore max_tokens=5 means using message count as the budget rather than the actual number of Tokens.

This is more suitable for demonstrating the trimming mechanism.

In actual use, you should use Token counting based on the model's context window.

Trim by approximate Token count

Example

from

langchain.

messages

import

trim_messages

trimmed

=

trim_messages

(

    messages

,

    max_tokens

=

100

,

    strategy

=

"last"

,

    token_counter

=

"approximate"

,

    include_system

=

True

,

    start_on

=

"human"

)

for

message

in

trimmed:

   

print

(

message.

type

,

message.

content

)

token_counter="approximate" Using approximate counting suits scenarios where you want to reduce the overhead of precise Token counting.

But approximate counting is not equal to the real number of Tokens actually used by a specific model.

In addition,trim_messages() decides how many messages to keep based on the budget and message structure; you should not assume it always returns a fixed number of messages.

Tool messages need attention when trimming

When the history contains tool calls, you should try to keep the message structure intact.

For example:

AIMessage(tool_calls=[...])

ToolMessage(tool_call_id="...")

AIMessage(content="Final answer")

If you keep only the ToolMessage but delete the corresponding tool call message, the request may become invalid.

For complex Agents, you should not simply delete messages by character count; you can manage them using LangChain's message utilities, middleware, or context compression strategies.


XII. RemoveMessage: delete messages in state

RemoveMessage Used to represent the operation of deleting a message in flows that support message state merging.

It is usually used together with LangGraph's add_messages reducer or Agent state management mechanism.

Note:Creating a RemoveMessage object does not automatically delete a message from a normal Python list.

Example: create a deletion instruction

Example

from

langchain.

messages

import

(

    HumanMessage

,

    AIMessage

,

    RemoveMessage

)

messages

=

[

    HumanMessage

(

        content

=

"Hello" (Chinese)

,

       

id

=

"msg_1"

   

)

,

    AIMessage

(

        content

=

"Hello!"

,

       

id

=

"msg_2"

   

)

,

    HumanMessage

(

        content

=

"Query the weather"

,

       

id

=

"msg_3"

   

)

]

Construct an instruction to delete a specified message

removal

=

RemoveMessage

(

   

id

=

"msg_3"

)

print

(

"Deletion target:"

,

removal.

id

)

print

(

"Message type:"

,

removal.

type

)

A normal list does not change automatically

print

(

"Original list length:"

,

len

(

messages

)

)

Execution result:

删除目标: msg_3

消息类型: remove

原始列表长度: 3

If you need to actually update the message state, you should pass RemoveMessage to a state merger that supports this operation.

For example, in a LangGraph workflow, deletion can be implemented using the corresponding message state update mechanism.

**Note:** RemoveMessage is mainly used to modify message state in a workflow; it cannot replace database deletion, log cleanup, or other persistent data deletion operations.


XIII. Common attributes and methods of message objects

LangChain message types usually inherit from BaseMessage, sharing some common attributes and methods.

Example

Example

from

langchain.

messages

import

HumanMessage

message

=

HumanMessage

(

    content

=

"Hello, Runoob Tutorial RUNOOB"

)

Message content

print

(

"content:"

,

message.

content

)

LangChain message type

print

(

"type:"

,

message.

type

)

Message ID (may be empty)

print

(

"id:"

,

message.

id

)

Extract text

print

(

"text:"

,

message.

text

)

Standardized content blocks

print

(

"content_blocks:"

,

message.

content_blocks

)

Formatted output

print

(

message.

pretty_repr

(

)

)

Where:

Attribute or method Purpose
content Raw message content
content_blocks Standardized list of content blocks
type Message types
id Message identifier, may be None
text Extract the text content from the message
pretty_repr() Generate a message description useful for debugging

For example,pretty_repr() It can output text with a message type heading, making it easy to view the conversation record in a terminal.

Different LangChain versions may differ in text access interfaces; when using older tutorials, note the distinction between text the attribute and the method notation used in historical versions.


XIV. Complete example: build a conversation using a message list

Below, a complete Python program combines system messages, user messages, AI replies, and conversation history.

Filename:langchain_messages.py

Complete example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

from

langchain.

messages

import

(

    HumanMessage

,

    SystemMessage

)

load_dotenv

(

)

Initialize the model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Initialize conversation history

messages

=

[

    SystemMessage

(

        content

=

(

           

"You are a Python programming tutorial assistant."

           

"Please answer in concise and accurate Chinese."

       

)

   

)

]

def

chat

(

question:

str

)

:

   

"""Send a question to the model and save the conversation history."""

   

Add a user message

    messages.

append

(

        HumanMessage

(

content

=

question

)

   

)

   

Call the model

    response

=

model.

invoke

(

messages

)

   

Save the AI reply

    messages.

append

(

response

)

   

print

(

"User:"

,

question

)

   

print

(

"AI:"

,

response.

text

)

   

print

(

"-"

40

)

First Round

chat

(

"What is Python?"

)

Second Round

chat

(

"Is it suitable for beginners?"

)

Third round

chat

(

"Give me a simple study plan."

)

print

(

"\nCurrent message history:"

)

for

message

in

messages:

   

print

(

        f

"[{message.type}]"

,

        message.

text

   

)

In this example,messages The list stores previous user messages and model replies.

Therefore, in the second and third calls, the model can refer to the earlier conversation content.

Note:

If you need to support multi-user sessions and persistent history, you can use separate session storage and mechanisms such as LangGraph's state checkpoints.


XV. FAQ

1. What is the difference between HumanMessage and AIMessage?

HumanMessage represents user input;AIMessage represents model output.

AIMessage may also contain tool call information and model response metadata.

2. Why does message.role raise an error?

Because LangChain message objects usually use type the attribute to distinguish message types.

For example:

message.type

while the dict representation below uses role:

{

    "role": "user",

    "content": "你好"

}

You cannot completely mix the attributes of the two representations.

3. Why is the content of AIMessage empty?

Possibly the model returned a tool call, or it could be other non-text content or a special response case.

You should check:

response.tool_calls

response.invalid_tool_calls

response.content_blocks

Do not judge whether a tool was called based only on whether the content content is empty.

4. Can a ToolMessage be sent directly to the model?

A ToolMessage usually needs to correspond to a preceding tool call request.

If the related AIMessage is missing or the tool call ID does not match, some model services may reject the request outright.

5. Can LangChain handle images, audio, and video?

LangChain provides standardized multimodal message structures.

But which content can actually be handled depends on the specific model provider, model version, and API support.

6. How to limit the message history length?

You can use the trim_messages() Trim the history by message count or Token budget.

For example:

trimmed = trim_messages(

    messages,

    max_tokens=1000,

    token_counter="approximate",

    strategy="last",

    include_system=True,

    start_on="human"

)

For complex histories containing tool calls, you should also check whether the associations between messages remain intact after trimming.

7. Are message IDs generated automatically?

You cannot assume that all messages have automatically generated IDs.

Manually created messages may have no ID, while model responses or state management flows may assign corresponding identifiers.

If you need to manage messages yourself, you can explicitly specify:

message = HumanMessage(

    content="Hello",

    id="user_message_001"

)

8. Does RemoveMessage delete chat records in the database?

No.

It is mainly used in workflows that support message state merging to represent a state update operation that deletes a specified message.

Deletion in a database or other persistent storage needs to be handled through the corresponding storage interface.


Summary

LangChain's message system is an important foundation for chat models, Agents, and multimodal applications.

The following content is important to master:

When developing LangChain applications, pay special attention to distinguishing message objects from message dicts, tool call requests from tool execution results, and message content from standardized content blocks.

After mastering these concepts, it becomes easier to learn Agent tool calling, conversation memory, multimodal models, and LangGraph state management.