一、消息组件概述
在LangChain框架中,消息(Messages)是模型交互的核心载体,是对话模型的输入输出的标准形式。每个消息对象包含三个关键部分:
- 角色:识别消息类型(例如 system、user)
- 内容:表示消息的实际内容(如文本、图像、音频、文档等)
- 元数据:可选字段,如响应信息、消息 ID 和令牌使用情况
这种设计通过标准化消息格式,实现了不同AI模型间的调用一致性。无论对接何种底层模型服务,开发者都能使用统一的接口规范进行交互操作。这种抽象层有效降低了多模型集成的复杂度。
基本用法
使用消息最简单的方法是创建消息对象并在调用时将其传递给模型。
python
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("你是一个高效的个人助手")
human_msg = HumanMessage("你好,最近怎么样?")
# Use with chat models
messages = [system_msg, human_msg]
response = model.invoke(messages) # Returns AIMessage
二、消息与提示词
提示词是引导大模型完成生成任务的指令及解释性或限定性说明。提示词可以是文本提示词(Text prompts),也可以是消息提示词(Message prompts)。
1、文本提示词(Text prompts)
文本提示词是字符串类型。它适用于不需要保留对话历史记录的简单生成任务。
python
text_prompt="请写一篇关于春天的散文。"
response = model.invoke(text_prompt)
文本提示词通常适用于以下情景:
- 单一的、独立的请求;
- 不需要对话历史记录;
- 希望代码复杂性最小化;
2、消息提示词(Message prompts)
消息提示词是由消息列表构成的提示词。例如:
python
from langchain.messages import SystemMessage, HumanMessage, AIMessage
messages = [
SystemMessage("你是一位诗人"),
HumanMessage("写一首关于春天的诗吧"),
AIMessage("竹外桃花三两枝...")
]
response = model.invoke(messages)
也可以采用字典格式生成消息列表,例如:
python
messages = [
{"role": "system", "content": "你是一位诗人"},
{"role": "user", "content": "写一首关于春天的诗吧"},
{"role": "assistant", "content": "竹外桃花三两枝..."}
]
response = model.invoke(messages)
消息提示词通常应用于如下场景:
- 管理多轮对话
- 处理多模态内容(图像、音频、文件)
- 包含系统指令
三、消息的类型
根据消息的来源不同,LangChain定义了四种消息类型:SystemMessage、HumanMessage、AIMessage、ToolMessage。
- SystemMessage:系统消息,告诉模型如何行为并为交互提供上下文。
- HumanMessage:人类消息,表示用户输入和与模型的交互。
- AIMessage:AI 消息,由模型生成的响应,包括文本内容、工具调用和元数据。
- ToolMessage:工具消息,表示工具调用的输出。
1、系统消息
SystemMessage 表示一组初始指令,用于预设模型的行为。您可以使用系统消息来设置语气、定义模型的角色并建立响应指南。
示例:
pyton
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)
2、人类消息
HumanMessage 表示用户输入和交互。它们可以包含文本、图像、音频、文件以及任何其他多模态内容。
简单示例:
python
response = model.invoke([
HumanMessage("什么是大模型?")
])
带有元数据的人类消息:
python
human_msg = HumanMessage(
content="你好!",
name="alice", # Optional: identify different users
id="msg_123", # Optional: unique identifier for tracing
)
3、AI 消息
AIMessage 表示模型调用的输出。它们可以包含多模态数据、工具调用和提供商特定的元数据。用户可根据需要访问这些数据。
python
response = model.invoke("请解释人工智能之一名词。")
print(type(response)) # <class 'langchain_core.messages.AIMessage'>
当调用模型时,模型会返回AIMessage 对象,其中包含响应中的所有相关元数据。
提供商对不同类型的消息进行不同权衡/语境化,这意味着有时手动创建新的AIMessage 对象并将其插入消息历史记录,就像它来自模型一样,会很有帮助。
python
from langchain.messages import AIMessage, SystemMessage, HumanMessage
# Create an AI message manually (e.g., for conversation history)
ai_msg = AIMessage("I'd be happy to help you with that question!")
# Add to conversation history
messages = [
SystemMessage("You are a helpful assistant"),
HumanMessage("Can you help me?"),
ai_msg, # Insert as if it came from the model
HumanMessage("Great! What's 2+2?")
]
response = model.invoke(messages)
3.1 AIMessage的基本属性
- text:字符串
消息的文本内容。 - content:字符串 | 字典
消息的原始内容。 - content_blocks:List(ContentBlock)
消息的标准化内容块。 - tool_calls:字典 | None
模型进行的工具调用。如果没有调用工具,则为空。 - id:字符串
消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回) - usage_metadata:字典 | None
消息的消耗元数据,其中包含可用的令牌计数。 - response_metadata:ResponseMetadata | None
消息的响应元数据。
3.2 AIMessage.tool_calls
当模型进行工具调用时,AIMessage 会包含tool_calls信息。
python
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']}")
其他结构化数据,例如reasoning或citations,也可以出现在消息中。
3.3 AIMessage.usage_metadata
AIMessage 可以在其usage_metadata 字段中包含令牌计数和其他使用元数据。
python
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-5-nano")
response = model.invoke("Hello!")
response.usage_metadata
text
`{'input_tokens': 8,
'output_tokens': 304,
'total_tokens': 312,
'input_token_details': {'audio': 0, 'cache_read': 0},
'output_token_details': {'audio': 0, 'reasoning': 256}}`
3.4 AIMessage的流式传输
在流式传输期间,您将收到可以组合成完整消息对象的AIMessageChunk对象。
python
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
4、工具消息
对于支持工具调用的模型,AI 消息可以包含工具调用。工具消息用于将单个工具执行的结果传回模型。
工具可以直接生成ToolMessage 对象。下面我们展示一个简单的示例:
python
# After a model makes a tool call
ai_message = AIMessage(
content=[],
tool_calls=[{
"name": "get_weather",
"args": {"location": "San Francisco"},
"id": "call_123"
}]
)
# Execute tool and create result message
weather_result = "Sunny, 72°F"
tool_message = ToolMessage(
content=weather_result,
tool_call_id="call_123", # Must match the call ID
name="get_weather"
)
# Continue conversation
messages = [
HumanMessage("What's the weather in San Francisco?"),
ai_message, # Model's tool call
tool_message, # Tool execution result
]
response = model.invoke(messages) # Model processes the result
ToolMessage的基本属性:
- content:字符串必填
工具调用的字符串化输出。 - tool_call_id:字符串必填
此消息响应的工具调用 ID。(此 ID 必须与AIMessage 中的工具调用 ID 匹配) - name:字符串必填
被调用的工具的名称。 - artifact:字典
未发送到模型但可以通过编程访问的其他数据。
四、消息的内容
可以将消息内容视为发送到模型的数据负载。消息具有content属性,其数据类型较为宽松,支持字符串和未类型化对象列表(例如字典)。这允许直接在 LangChain 聊天模型中支持提供商原生结构,例如多模态内容和其他数据。
另外,LangChain 为文本、推理、引用、多模态数据、服务器端工具调用和其他消息内容提供了专门的内容类型。
LangChain 聊天模型接受消息对象content属性中的内容,其可以是:
- 一个字符串。
- 提供商原生格式的内容块列表。
- LangChain 的标准内容块列表。
示例:
python
from langchain.messages import HumanMessage
# String content
human_message = HumanMessage("Hello, how are you?")
# Provider-native format (e.g., OpenAI)
human_message = HumanMessage(content=[
{"type": "text", "text": "Hello, how are you?"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
])
# List of standard content blocks
human_message = HumanMessage(content_blocks=[
{"type": "text", "text": "Hello, how are you?"},
{"type": "image", "url": "https://example.com/image.jpg"},
])
1、标准化的内容块
LangChain 提供了消息内容的标准表示,适用于所有提供商。
消息对象实现了一个content_blocks属性,该属性会将content属性延迟解析为标准、类型安全的表示。例如,从ChatAnthropic 或 ChatOpenAI 生成的消息将包含各自提供商格式的thinking或reasoning块,但可以延迟解析为一致的ReasoningContentBlock 表示。
python
from langchain.messages import AIMessage
message = AIMessage(
content=[
{"type": "thinking", "thinking": "...", "signature": "WaUjzkyp..."},
{"type": "text", "text": "..."},
],
response_metadata={"model_provider": "anthropic"}
)
message.content_blocks
text
[{'type': 'reasoning',
'reasoning': '...',
'extras': {'signature': 'WaUjzkyp...'}},
{'type': 'text', 'text': '...'}]
2、多模态内容
多模态是指处理不同形式的数据的能力,例如文本、音频、图像和视频。LangChain 包含这些数据的标准类型,可以在所有提供商中使用。
聊天模型可以接受多模态数据作为输入并将其作为输出生成。下面我们展示了包含多模态数据的输入消息的简短示例。
图像消息
python
# From URL
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this image."},
{"type": "image", "url": "https://example.com/path/to/image.jpg"},
]
}
# From base64 data
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this image."},
{
"type": "image",
"base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
"mime_type": "image/jpeg",
},
]
}
# From provider-managed File ID
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this image."},
{"type": "image", "file_id": "file-abc123"},
]
}
音频消息
python
# From base64 data
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this audio."},
{
"type": "audio",
"base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
"mime_type": "audio/wav",
},
]
}
# From provider-managed File ID
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this audio."},
{"type": "audio", "file_id": "file-abc123"},
]
}
3、Content Block类型参考
内容块表示为字典列表。列表中的每一项都必须符合以下块类型之一:
- 核心类型
TextContentBlock
ReasoningContentBlock
- 多模态类型
ImageContentBlock
AudioContentBlock
VideoContentBlock
FileContentBlock
PlainTextContentBlock
- 工具调用
ToolCall
ToolCallChunk
InvalidToolCall
- 服务端工具执行
ServerToolCall
ServerToolCallChunk
ServerToolResult
- 提供商特定块
NonStandardContentBlock
五、总结
本期我们介绍了LangChain框架中消息的基本概念、构成、使用方法、作为提示词的消息列表、消息的类型、标准化的消息内容等知识点。
消息作为大模型交互的核心载体,其重要性不言而喻。熟练掌握这些知识点是基于LangChain开发智能体的基本功。