跳到主要内容
消息是 LangChain 中模型上下文的基本单位。它们代表模型的输入和输出,承载与 LLM 交互时表示对话状态所需的内容和元数据。 消息是包含以下内容的对象:
  • 角色 - 识别消息类型(例如 systemuser
  • 内容 - 表示消息的实际内容(如文本、图像、音频、文档等)
  • 元数据 - 可选字段,如响应信息、消息 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",  # Optional: identify different users
    id="msg_123",  # Optional: unique identifier for tracing
)
name 字段的行为因提供商而异 - 有些将其用于用户标识,有些则忽略它。要查看详情,请参阅模型提供商的参考

AI 消息

AIMessage 表示模型调用的输出。它们可以包含多模态数据、工具调用和提供商特定的元数据,您以后可以访问这些数据。
response = model.invoke("Explain AI")
print(type(response))  # <class 'langchain_core.messages.AIMessage'>
当调用模型时,模型会返回AIMessage 对象,其中包含响应中的所有相关元数据。 提供商对不同类型的消息进行不同权衡/语境化,这意味着有时手动创建新的AIMessage 对象并将其插入消息历史记录,就像它来自模型一样,会很有帮助。
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)
文本
字符串
消息的文本内容。
内容
字符串 | 字典[]
消息的原始内容。
内容块
ContentBlock[]
消息的标准化内容块
工具调用
字典[] | 无
模型进行的工具调用。如果没有调用工具,则为空。
id
字符串
消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)
使用元数据
字典 | 无
消息的使用元数据,其中包含可用的令牌计数。
响应元数据
ResponseMetadata | 无
消息的响应元数据。

工具调用

当模型进行工具调用时,它们包含在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']}")
其他结构化数据,例如推理或引用,也可以出现在消息内容中。

Token 用量

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 对象。下面我们展示一个简单的示例。在工具指南中阅读更多内容。
# 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
)

# 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
内容
字符串
必填
工具调用的字符串化输出。
工具调用 ID
字符串
必填
此消息响应的工具调用 ID。(此 ID 必须与AIMessage 中的工具调用 ID 匹配)
名称
字符串
必填
被调用的工具的名称。
artifact
字典
未发送到模型但可以通过编程访问的其他数据。
artifact 字段存储补充数据,这些数据不会发送到模型,但可以通过编程访问。这对于存储原始结果、调试信息或用于下游处理的数据非常有用,而不会使模型的上下文混乱。
例如,检索工具可以从文档中检索一段用于模型引用的内容。消息content包含模型将引用的文本,而artifact可以包含应用程序可用的文档标识符或其他元数据(例如,用于渲染页面)。请参阅下面的示例
from langchain.messages import ToolMessage

# Sent to model
message_content = "It was the best of times, it was the worst of times."

# Artifact available downstream
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属性中的消息内容,并且可以包含:
  1. 一个字符串
  2. 提供商原生格式的内容块列表
  3. LangChain 的标准内容块列表
请参阅下面的多模态输入示例
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"},
])
在初始化消息时指定content_blocks仍会填充消息content,但提供了类型安全的接口。

标准内容块

LangChain 提供了消息内容的标准表示,适用于所有提供商。 消息对象实现了一个content_blocks属性,该属性会将content属性延迟解析为标准、类型安全的表示。例如,从ChatAnthropicChatOpenAI 生成的消息将包含各自提供商格式的thinkingreasoning块,但可以延迟解析为一致的ReasoningContentBlock 表示:
  • Anthropic
  • OpenAI
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': '...'}]
请参阅集成指南以开始使用您选择的推理提供商。
序列化标准内容如果 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 包含这些数据的标准类型,可以在所有提供商中使用。 聊天模型可以接受多模态数据作为输入并将其作为输出生成。下面我们展示了包含多模态数据的输入消息的简短示例。
可以在内容块的顶层包含额外键,或嵌套在"extras": {"key": value}中。例如,OpenAIAWS Bedrock Converse 需要 PDF 的文件名。请参阅您选择的模型的提供商页面以了解具体信息。
# 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"},
    ]
}
并非所有模型都支持所有文件类型。请查阅模型提供商的参考文档,了解支持的格式和大小限制。

内容块参考

内容块表示为类型化字典列表(在创建消息或访问content_blocks属性时)。列表中的每个项都必须符合以下块类型之一
目的:标准文本输出
type
字符串
必填
始终为"text"
文本
字符串
必填
文本内容
注释
对象[]
文本注释列表
额外内容
对象
附加的提供商特定数据
示例
{
    "type": "text",
    "text": "Hello world",
    "annotations": []
}
目的:模型推理步骤
type
字符串
必填
始终为"reasoning"
推理
字符串
推理内容
额外内容
对象
附加的提供商特定数据
示例
{
    "type": "reasoning",
    "reasoning": "The user is asking about...",
    "extras": {"signature": "abc123"},
}
目的:图像数据
type
字符串
必填
始终为"image"
URL
字符串
指向图像位置的 URL。
Base64
字符串
Base64 编码的图像数据。
id
字符串
外部存储图像(例如,在提供商的文件系统或存储桶中)的引用 ID。
MIME 类型
字符串
图像MIME 类型(例如,image/jpegimage/png
目的:音频数据
type
字符串
必填
始终为"audio"
URL
字符串
指向音频位置的 URL。
Base64
字符串
Base64 编码的音频数据。
id
字符串
外部存储音频文件(例如,在提供商的文件系统或存储桶中)的引用 ID。
MIME 类型
字符串
音频MIME 类型(例如,audio/mpegaudio/wav
目的:视频数据
type
字符串
必填
始终为"video"
URL
字符串
指向视频位置的 URL。
Base64
字符串
Base64 编码的视频数据。
id
字符串
外部存储视频文件(例如,在提供商的文件系统或存储桶中)的引用 ID。
MIME 类型
字符串
视频MIME 类型(例如,video/mp4video/webm
目的:通用文件(PDF 等)
type
字符串
必填
始终为"file"
URL
字符串
指向文件位置的 URL。
Base64
字符串
Base64 编码的文件数据。
id
字符串
外部存储文件(例如,在提供商的文件系统或存储桶中)的引用 ID。
MIME 类型
字符串
文件MIME 类型(例如,application/pdf
目的:文档文本(.txt.md
type
字符串
必填
始终为"text-plain"
文本
字符串
文本内容
MIME 类型
字符串
文本的MIME 类型(例如,text/plaintext/markdown
目的:函数调用
type
字符串
必填
始终为"tool_call"
名称
字符串
必填
要调用的工具名称
参数
对象
必填
要传递给工具的参数
id
字符串
必填
此工具调用的唯一标识符
示例
{
    "type": "tool_call",
    "name": "search",
    "args": {"query": "weather"},
    "id": "call_123"
}
目的:流式传输工具调用片段
type
字符串
必填
始终为"tool_call_chunk"
名称
字符串
正在调用的工具名称
参数
字符串
部分工具参数(可能是不完整的 JSON)
id
字符串
工具调用标识符
索引
数字 | 字符串
此块在流中的位置
目的:格式错误的调用,旨在捕获 JSON 解析错误。
type
字符串
必填
始终为"invalid_tool_call"
名称
字符串
未能调用的工具名称
参数
对象
要传递给工具的参数
错误
字符串
发生错误时的描述
目的:在服务器端执行的工具调用。
type
字符串
必填
始终为"server_tool_call"
id
字符串
必填
与工具调用相关的标识符。
名称
字符串
必填
要调用的工具名称。
参数
字符串
必填
部分工具参数(可能是不完整的 JSON)
目的:流式传输服务器端工具调用片段
type
字符串
必填
始终为"server_tool_call_chunk"
id
字符串
与工具调用相关的标识符。
名称
字符串
正在调用的工具名称
参数
字符串
部分工具参数(可能是不完整的 JSON)
索引
数字 | 字符串
此块在流中的位置
目的:搜索结果
type
字符串
必填
始终为"server_tool_result"
工具调用 ID
字符串
必填
相应服务器工具调用的标识符。
id
字符串
与服务器工具结果关联的标识符。
状态
字符串
必填
服务器端工具的执行状态。"success""error"
输出
已执行工具的输出。
目的:提供商特定的逃逸口
type
字符串
必填
始终为"non_standard"
value
对象
必填
提供商特定数据结构
用法:用于实验性或提供商独有的功能
附加的提供商特定内容类型可在每个模型提供商的参考文档中找到。
API 参考中查看规范类型定义。
内容块作为 LangChain v1 中消息的新属性引入,旨在标准化跨提供商的内容格式,同时保持与现有代码的向后兼容性。内容块不是content属性的替代品,而是一个可以用于以标准化格式访问消息内容的新属性。

与聊天模型一起使用

聊天模型接受一系列消息对象作为输入,并返回一个AIMessage 作为输出。交互通常是无状态的,因此简单的会话循环涉及使用不断增长的消息列表调用模型。 请参阅以下指南了解更多信息:
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.