消息是 LangChain 中模型上下文的基本单位。它们代表模型的输入和输出,承载着与 LLM 交互时表示对话状态所需的内容和元数据。
消息是包含以下内容的对象:
角色 - 标识消息类型(例如
system、user)
内容 -
表示消息的实际内容(如文本、图像、音频、文档等)
元数据 -
可选字段,如响应信息、消息 ID 和令牌使用情况
LangChain 提供了一种标准消息类型,适用于所有模型提供商,确保无论调用何种模型,行为都保持一致。
基本用法
使用消息的最简单方法是创建消息对象,并在调用 时将它们传递给模型。
from langchain . chat_models import init_chat_model
from langchain . messages import HumanMessage , AIMessage , SystemMessage
model = init_chat_model ( "gpt-5-nano" )
system_msg = SystemMessage ( "You are a helpful assistant." )
human_msg = HumanMessage ( "Hello, how are you?" )
# Use with chat models
messages = [ system_msg , human_msg ]
response = model . invoke ( messages ) # Returns AIMessage
文本提示
文本提示是字符串 - 非常适合不需要保留对话历史的直接生成任务。
response = model . invoke ( "Write a haiku about spring" )
使用文本提示时:
您有一个独立的请求
您不需要对话历史
您希望代码复杂度最小化
消息提示
或者,您可以通过提供消息对象列表来将消息列表传递给模型。
from langchain . messages import SystemMessage , HumanMessage , AIMessage
messages = [
SystemMessage ( "You are a poetry expert" ),
HumanMessage ( "Write a haiku about spring" ),
AIMessage ( "Cherry blossoms bloom..." )
]
response = model . invoke ( messages )
使用消息提示时:
管理多轮对话
处理多模态内容(图像、音频、文件)
包含系统指令
字典格式
您也可以直接在 OpenAI 聊天完成格式中指定消息。
messages = [
{ "role" : "system" , "content" : "You are a poetry expert" },
{ "role" : "user" , "content" : "Write a haiku about spring" },
{ "role" : "assistant" , "content" : "Cherry blossoms bloom..." }
]
response = model . invoke ( messages )
消息类型
系统消息
一个 SystemMessage 表示一组初始指令,用于引导模型的行为。您可以使用系统消息来设置语气、定义模型的角色并建立响应指南。
system_msg = SystemMessage ( "You are a helpful coding assistant." )
messages = [
system_msg ,
HumanMessage ( "How do I create a REST API?" )
]
response = model . invoke ( messages )
from langchain . messages import SystemMessage , HumanMessage
system_msg = SystemMessage ( """
You are a senior Python developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.
Be concise but thorough in your explanations.
""" )
messages = [
system_msg ,
HumanMessage ( "How do I create a REST API?" )
]
response = model . invoke ( messages )
人类消息
一个 HumanMessage 表示用户输入和交互。它们可以包含文本、图像、音频、文件以及任何数量的多模态内容 。
文本内容
response = model . invoke ([
HumanMessage ( "What is machine learning?" )
])
消息元数据
human_msg = HumanMessage (
content = "Hello!" ,
name = "alice" , # 可选:标识不同用户
id = "msg_123" , # 可选:用于跟踪的唯一标识符
)
name
字段的行为因提供商而异——有些用于用户标识,有些则忽略。要检查,请参阅模型提供商的参考 。
AI 消息
一个 AIMessage 表示模型调用的输出。它们可以包含多模态数据、工具调用以及特定于提供商的元数据,您可以稍后访问这些元数据。
response = model . invoke ( "Explain AI" )
print ( type ( response )) # <class 'langchain.messages.AIMessage'>
AIMessage 对象在调用模型时返回,其中包含响应中的所有关联元数据。
提供商对消息类型的加权/上下文化方式不同,这意味着有时手动创建一个新的 AIMessage 对象并将其插入消息历史记录中(就好像它来自模型)会很有帮助。
from langchain . messages import AIMessage , SystemMessage , HumanMessage
# 手动创建 AI 消息(例如,用于对话历史)
ai_msg = AIMessage ( "I'd be happy to help you with that question!" )
# 添加到对话历史
messages = [
SystemMessage ( "You are a helpful assistant" ),
HumanMessage ( "Can you help me?" ),
ai_msg , # 插入为好像来自模型
HumanMessage ( "Great! What's 2+2?" )
]
response = model . invoke ( messages )
消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)
工具调用
当模型进行工具调用 时,它们会包含在 AIMessage 中:
from langchain . chat_models import init_chat_model
model = init_chat_model ( "gpt-5-nano" )
def get_weather ( location : str ) -> str :
"""Get the weather at a location."""
...
model_with_tools = model . bind_tools ([ get_weather ])
response = model_with_tools . invoke ( "What's the weather in Paris?" )
for tool_call in response . tool_calls :
print ( f "Tool: { tool_call [ ' name ' ] } " )
print ( f "Args: { tool_call [ ' args ' ] } " )
print ( f "ID: { tool_call [ ' id ' ] } " )
其他结构化数据,例如推理或引用,也可以出现在消息内容 中。
令牌使用情况
一个 AIMessage 可以在其 usage_metadata 字段中保存令牌计数和其他使用元数据:
from langchain . chat_models import init_chat_model
model = init_chat_model ( "gpt-5-nano" )
response = model . invoke ( "Hello!" )
response . usage_metadata
{'input_tokens': 8,
'output_tokens': 304,
'total_tokens': 312,
'input_token_details': {'audio': 0, 'cache_read': 0},
'output_token_details': {'audio': 0, 'reasoning': 256}}
有关详细信息,请参阅 UsageMetadata 。
流式传输和分块
在流式传输期间,您将收到 AIMessageChunk 对象,这些对象可以组合成完整的消息对象:
chunks = []
full_message = None
for chunk in model . stream ( "Hi" ):
chunks . append ( chunk )
print ( chunk . text )
full_message = chunk if full_message is None else full_message + chunk
工具消息
对于支持工具调用 的模型,AI 消息可以包含工具调用。工具消息用于将单个工具执行的结果传递回模型。
工具 可以直接生成 ToolMessage 对象。下面,我们展示一个简单的示例。请阅读工具指南 了解更多。
from langchain . messages import AIMessage
from langchain . messages import ToolMessage
# 在模型进行工具调用后
# (这里,我们手动创建消息以简洁起见)
ai_message = AIMessage (
content = [],
tool_calls = [{
"name" : "get_weather" ,
"args" : { "location" : "San Francisco" },
"id" : "call_123"
}]
)
# 执行工具并创建结果消息
weather_result = "Sunny, 72°F"
tool_message = ToolMessage (
content = weather_result ,
tool_call_id = "call_123" # 必须与调用 ID 匹配
)
# 继续对话
messages = [
HumanMessage ( "What's the weather in San Francisco?" ),
ai_message , # 模型的工具调用
tool_message , # 工具执行结果
]
response = model . invoke ( messages ) # 模型处理结果
artifact 字段存储补充数据,这些数据不会发送给模型,但可以以编程方式访问。这对于存储原始结果、调试信息或用于下游处理的数据非常有用,而不会使模型的上下文变得混乱。
例如,一个检索 工具可以从文档中检索一段供模型参考的文本。其中消息 content 包含模型将引用的文本,而 artifact 可以包含文档标识符或其他元数据,应用程序可以使用这些元数据(例如,渲染页面)。请参见下面的示例: from langchain . messages import ToolMessage
# 发送给模型
message_content = "It was the best of times, it was the worst of times."
# 下游可用的 artifact
artifact = { "document_id" : "doc_123" , "page" : 0 }
tool_message = ToolMessage (
content = message_content ,
tool_call_id = "call_123" ,
name = "search_books" ,
artifact = artifact ,
)
请参阅 RAG 教程 以获取使用 LangChain 构建检索代理 的端到端示例。
消息内容
您可以将消息的内容视为发送给模型的数据有效载荷。消息具有 content 属性,该属性是松散类型的,支持字符串和未类型化对象(例如字典)的列表。这允许 LangChain 聊天模型直接支持提供商原生的结构,例如多模态 内容和其他数据。
此外,LangChain 为文本、推理、引用、多模态数据、服务器端工具调用和其他消息内容提供了专用的内容类型。请参阅下面的内容块 。
LangChain 聊天模型在 content 属性中接受消息内容。
这可能包含:
字符串
提供商原生格式的内容块列表
LangChain 的标准内容块 列表
请参阅下面使用多模态 输入的示例:
from langchain . messages import HumanMessage
# 字符串内容
human_message = HumanMessage ( "Hello, how are you?" )
# 提供商原生格式(例如,OpenAI)
human_message = HumanMessage ( content = [
{ "type" : "text" , "text" : "Hello, how are you?" },
{ "type" : "image_url" , "image_url" : { "url" : "https://example.com/image.jpg" }}
])
# 标准内容块列表
human_message = HumanMessage ( content_blocks = [
{ "type" : "text" , "text" : "Hello, how are you?" },
{ "type" : "image" , "url" : "https://example.com/image.jpg" },
])
在初始化消息时指定 content_blocks 仍会填充消息的
content,但为此提供了类型安全的接口。
标准内容块
LangChain 提供了一种标准的消息内容表示,适用于所有提供商。
消息对象实现了一个 content_blocks 属性,该属性将延迟解析 content 属性为标准的、类型安全的表示。例如,从 ChatAnthropic 或 ChatOpenAI 生成的消息将包含相应提供商格式的 thinking 或 reasoning 块,但可以延迟解析为一致的 ReasoningContentBlock 表示:
from langchain . messages import AIMessage
message = AIMessage (
content = [
{ "type" : "thinking" , "thinking" : "..." , "signature" : "WaUjzkyp..." },
{ "type" : "text" , "text" : "..." },
],
response_metadata = { "model_provider" : "anthropic" }
)
message . content_blocks
[{'type': 'reasoning',
'reasoning': '...',
'extras': {'signature': 'WaUjzkyp...'}},
{'type': 'text', 'text': '...'}]
from langchain . messages import AIMessage
message = AIMessage (
content = [
{
"type" : "reasoning" ,
"id" : "rs_abc123" ,
"summary" : [
{ "type" : "summary_text" , "text" : "summary 1" },
{ "type" : "summary_text" , "text" : "summary 2" },
],
},
{ "type" : "text" , "text" : "..." , "id" : "msg_abc123" },
],
response_metadata = { "model_provider" : "openai" }
)
message . content_blocks
[{'type': 'reasoning', 'id': 'rs_abc123', 'reasoning': 'summary 1'},
{'type': 'reasoning', 'id': 'rs_abc123', 'reasoning': 'summary 2'},
{'type': 'text', 'text': '...', 'id': 'msg_abc123'}]
请参阅集成指南 以开始使用您选择的推理提供商。
序列化标准内容 如果 LangChain 之外的应用程序需要访问标准内容块表示,您可以选择将内容块存储在消息内容中。 为此,您可以将 LC_OUTPUT_VERSION 环境变量设置为 v1。或者,使用 output_version="v1" 初始化任何聊天模型: from langchain . chat_models import init_chat_model
model = init_chat_model ( "gpt-5-nano" , output_version = "v1" )
多模态
多模态性 指的是处理不同形式数据的能力,例如文本、音频、图像和视频。LangChain 包含这些数据的标准类型,可在所有提供商中使用。
聊天模型 可以接受多模态数据作为输入并生成多模态数据作为输出。下面我们展示包含多模态数据的输入消息的简短示例。
# 从 URL
message = {
"role" : "user" ,
"content" : [
{ "type" : "text" , "text" : "Describe the content of this image." },
{ "type" : "image" , "url" : "https://example.com/path/to/image.jpg" },
]
}
# 从 base64 数据
message = {
"role" : "user" ,
"content" : [
{ "type" : "text" , "text" : "Describe the content of this image." },
{
"type" : "image" ,
"base64" : "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2..." ,
"mime_type" : "image/jpeg" ,
},
]
}
# 从提供商管理的文件 ID
message = {
"role" : "user" ,
"content" : [
{ "type" : "text" , "text" : "Describe the content of this image." },
{ "type" : "image" , "file_id" : "file-abc123" },
]
}
并非所有模型都支持所有文件类型。请检查模型提供商的参考 以获取支持的格式和大小限制。
内容块参考
内容块(在创建消息或访问 content_blocks 属性时)表示为类型化字典的列表。列表中的每个项目必须遵循以下块类型之一:
目的: 图像数据此内容块的唯一标识符(由提供商或 LangChain 生成)。
图像 MIME 类型 (例如,image/jpeg、image/png)。对于 base64 数据是必需的。
目的: 音频数据此内容块的唯一标识符(由提供商或 LangChain 生成)。
音频 MIME 类型 (例如,audio/mpeg、audio/wav)。对于 base64 数据是必需的。
目的: 视频数据此内容块的唯一标识符(由提供商或 LangChain 生成)。
视频 MIME 类型 (例如,video/mp4、video/webm)。对于 base64 数据是必需的。
目的: 通用文件(PDF 等)此内容块的唯一标识符(由提供商或 LangChain 生成)。
文件 MIME 类型 (例如,application/pdf)。对于 base64 数据是必需的。
目的: 文档文本(.txt、.md)文本的 MIME 类型 (例如,text/plain、text/markdown)
目的: 提供商特定的逃生舱用法: 用于实验性或提供商独有的功能其他提供商特定的内容类型可以在每个模型提供商的参考文档 中找到。
内容块作为 LangChain v1 中消息的新属性引入,用于标准化跨提供商的内容格式,同时保持与现有代码的向后兼容性。 内容块不是 content 属性的替代品,而是一个新属性,可用于以标准化格式访问消息的内容。
与聊天模型一起使用
聊天模型 接受消息对象序列作为输入,并返回一个 AIMessage 作为输出。交互通常是无状态的,因此一个简单的对话循环涉及使用不断增长的消息列表调用模型。
请参阅以下指南以了解更多信息: