消息是 LangChain 中模型上下文的基本单位。它们代表模型的输入和输出,携带着与大型语言模型交互时表示对话状态所需的内容和元数据。 消息是包含以下内容的对象:
角色 - 标识消息类型(例如 system、user)
内容 - 表示消息的实际内容(如文本、图像、音频、文档等)
元数据 - 可选字段,如响应信息、消息 ID 和令牌使用量
LangChain 提供了一种适用于所有模型提供商的标准消息类型,确保无论调用哪个模型,行为都一致。
基本用法
使用消息最简单的方法是创建消息对象并在调用 时将其传递给模型。
import { initChatModel , HumanMessage , SystemMessage } from "langchain" ;
const model = await initChatModel ( "gpt-5-nano" );
const systemMsg = new SystemMessage ( "You are a helpful assistant." );
const humanMsg = new HumanMessage ( "Hello, how are you?" );
const messages = [ systemMsg , humanMsg ];
const response = await model . invoke ( messages ); // Returns AIMessage
文本提示
文本提示是字符串 - 适用于不需要保留对话历史记录的简单生成任务。
const response = await model . invoke ( "Write a haiku about spring" );
在以下情况下使用文本提示:
您有一个单独的独立请求
您不需要对话历史记录
您想要最小的代码复杂性
消息提示
或者,您可以通过提供消息对象列表将消息列表传递给模型。
import { SystemMessage , HumanMessage , AIMessage } from "langchain" ;
const messages = [
new SystemMessage ( "You are a poetry expert" ),
new HumanMessage ( "Write a haiku about spring" ),
new AIMessage ( "Cherry blossoms bloom..." ),
];
const response = await model . invoke ( messages );
在以下情况下使用消息提示:
管理多轮对话
处理多模态内容(图像、音频、文件)
包含系统指令
您也可以直接以 OpenAI 聊天补全格式指定消息。
const messages = [
{ role: "system" , content: "You are a poetry expert" },
{ role: "user" , content: "Write a haiku about spring" },
{ role: "assistant" , content: "Cherry blossoms bloom..." },
];
const response = await model . invoke ( messages );
消息类型
系统消息
@[SystemMessage] 代表一组初始指令,用于预设模型的行为。您可以使用系统消息来设定语调、定义模型的角色并建立响应指南。
import { SystemMessage , HumanMessage , AIMessage } from "langchain" ;
const systemMsg = new SystemMessage ( "You are a helpful coding assistant." );
const messages = [
systemMsg ,
new HumanMessage ( "How do I create a REST API?" ),
];
const response = await model . invoke ( messages );
import { SystemMessage , HumanMessage } from "langchain" ;
const systemMsg = new SystemMessage ( `
You are a senior TypeScript developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.
Be concise but thorough in your explanations.
` );
const messages = [
systemMsg ,
new HumanMessage ( "How do I create a REST API?" ),
];
const response = await model . invoke ( messages );
人类消息
@[HumanMessage] 代表用户输入和交互。它们可以包含文本、图像、音频、文件以及任何其他多模态内容 。
文本内容
const response = await model . invoke ([
new HumanMessage ( "What is machine learning?" ),
]);
const response = await model . invoke ( "What is machine learning?" );
const humanMsg = new HumanMessage ({
content: "Hello!" ,
name: "alice" ,
id: "msg_123" ,
});
name 字段的行为因提供商而异 - 有些将其用于用户标识,有些则忽略它。要查看,请参阅模型提供商的参考文档 。
AI 消息
AIMessage 代表模型调用的输出。它们可以包含多模态数据、工具调用和您可以稍后访问的特定于提供商的元数据。
const response = await model . invoke ( "Explain AI" );
console . log ( typeof response ); // AIMessage
调用模型时会返回AIMessage 对象,其中包含响应中的所有相关元数据。 提供商对消息类型的权重/语境化不同,这意味着有时手动创建新的AIMessage 对象并将其插入到消息历史记录中,就好像它来自模型一样,会很有帮助。 import { AIMessage , SystemMessage , HumanMessage } from "langchain" ;
const aiMsg = new AIMessage ( "I'd be happy to help you with that question!" );
const messages = [
new SystemMessage ( "You are a helpful assistant" ),
new HumanMessage ( "Can you help me?" ),
aiMsg , // Insert as if it came from the model
new HumanMessage ( "Great! What's 2+2?" )
]
const response = await model . invoke ( messages );
消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)
当模型进行工具调用 时,它们会包含在AIMessage 中。
const modelWithTools = model . bindTools ([ getWeather ]);
const response = await modelWithTools . invoke ( "What's the weather in Paris?" );
for ( const toolCall of response . tool_calls ) {
console . log ( `Tool: ${ toolCall . name } ` );
console . log ( `Args: ${ toolCall . args } ` );
console . log ( `ID: ${ toolCall . id } ` );
}
其他结构化数据,例如推理或引用,也可以出现在消息内容 中。
Token 用量
AIMessage 可以在其usage_metadata 字段中保存令牌计数和其他使用元数据。
import { initChatModel } from "langchain" ;
const model = await initChatModel ( "gpt-5-nano" );
const response = await model . invoke ( "Hello!" );
console . log ( response . usage_metadata );
{
"output_tokens" : 304 ,
"input_tokens" : 8 ,
"total_tokens" : 312 ,
"input_token_details" : {
"cache_read" : 0
},
"output_token_details" : {
"reasoning" : 256
}
}
有关详细信息,请参阅UsageMetadata 。
流式传输和分块
在流式传输过程中,您将收到AIMessageChunk 对象,这些对象可以组合成一个完整的消息对象。
import { AIMessageChunk } from "langchain" ;
let finalChunk : AIMessageChunk | undefined ;
for ( const chunk of chunks ) {
finalChunk = finalChunk ? finalChunk . concat ( chunk ) : chunk ;
}
对于支持工具调用 的模型,AI 消息可以包含工具调用。工具消息用于将单个工具执行的结果返回给模型。 工具 可以直接生成 @[ToolMessage] 对象。下面我们展示一个简单的例子。在工具指南 中阅读更多内容。import { AIMessage , ToolMessage } from "langchain" ;
const aiMessage = new AIMessage ({
content: [],
tool_calls: [{
name: "get_weather" ,
args: { location: "San Francisco" },
id: "call_123"
}]
});
const toolMessage = new ToolMessage ({
content: "Sunny, 72°F" ,
tool_call_id: "call_123"
});
const messages = [
new HumanMessage ( "What's the weather in San Francisco?" ),
aiMessage , // Model's tool call
toolMessage , // Tool execution result
];
const response = await model . invoke ( messages ); // Model processes the result
artifact 字段存储不会发送到模型但可以通过编程访问的补充数据。这对于存储原始结果、调试信息或用于下游处理的数据非常有用,而不会使模型的上下文混乱。
消息内容
您可以将消息内容视为发送到模型的数据负载。消息具有松散类型的 content 属性,支持字符串和未类型化对象(例如字典)列表。这允许直接在 LangChain 聊天模型中支持提供商原生的结构,例如多模态 内容和其他数据。 另外,LangChain 为文本、推理、引用、多模态数据、服务器端工具调用和其他消息内容提供了专门的内容类型。请参阅下面的内容块 。 LangChain 聊天模型接受 content 属性中的消息内容,并且可以包含:
一个字符串
提供商原生格式的内容块列表
LangChain 的标准内容块 列表
有关使用多模态 输入的示例,请参见下文。
import { HumanMessage } from "langchain" ;
// String content
const humanMessage = new HumanMessage ( "Hello, how are you?" );
// Provider-native format (e.g., OpenAI)
const humanMessage = new 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
const humanMessage = new HumanMessage ({
contentBlocks: [
{ type: "text" , text: "Hello, how are you?" },
{ type: "image" , url: "https://example.com/image.jpg" },
],
});
标准内容块
LangChain 提供了适用于所有提供商的消息内容的标准表示形式。 消息对象实现了一个 contentBlocks 属性,该属性将延迟将 content 属性解析为标准、类型安全的表示形式。例如,从ChatAnthropic 或ChatOpenAI 生成的消息将包含各自提供商格式的 thinking 或 reasoning 块,但可以延迟解析为一致的ReasoningContentBlock 表示形式: import { AIMessage } from "@langchain/core/messages" ;
const message = new AIMessage ({
content: [
{
"type" : "thinking" ,
"thinking" : "..." ,
"signature" : "WaUjzkyp..." ,
},
{
"type" : "text" ,
"text" : "..." ,
"id" : "msg_abc123" ,
},
],
response_metadata: { model_provider: "anthropic" },
});
console . log ( message . contentBlocks );
请参阅集成指南 ,开始使用您选择的推理提供商。
序列化标准内容 如果 LangChain 外部的应用程序需要访问标准内容块表示,您可以选择将内容块存储在消息内容中。 为此,您可以将 LC_OUTPUT_VERSION 环境变量设置为 v1。或者,使用 outputVersion: "v1" 初始化任何聊天模型: import { initChatModel } from "langchain" ;
const model = await initChatModel (
"gpt-5-nano" ,
{ outputVersion: "v1" }
);
多模态
多模态 是指处理不同形式数据(如文本、音频、图像和视频)的能力。LangChain 包含了这些数据的标准类型,可以在不同提供商之间使用。 聊天模型 可以接受多模态数据作为输入并生成多模态数据作为输出。下面我们展示了包含多模态数据的输入消息的简短示例。
// From URL
const message = new HumanMessage ({
content: [
{ type: "text" , text: "Describe the content of this image." },
{
type: "image" ,
source_type: "url" ,
url: "https://example.com/path/to/image.jpg"
},
],
});
// From base64 data
const message = new HumanMessage ({
content: [
{ type: "text" , text: "Describe the content of this image." },
{
type: "image" ,
source_type: "base64" ,
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2..." ,
},
],
});
// From provider-managed File ID
const message = new HumanMessage ({
content: [
{ type: "text" , text: "Describe the content of this image." },
{ type: "image" , source_type: "id" , id: "file-abc123" },
],
});
并非所有模型都支持所有文件类型。请查阅模型提供商的参考文档 以了解支持的格式和大小限制。
内容块参考
内容块表示为类型化对象列表(在创建消息或访问 contentBlocks 字段时)。列表中的每个项都必须符合以下块类型之一:
目的: 标准文本输出示例 {
type : "text" ,
text : "Hello world" ,
annotations : []
}
目的: 模型推理步骤示例 {
type : "reasoning" ,
reasoning : "The user is asking about..."
}
ContentBlock.Multimodal.Image
目的: 图像数据外部存储图像(例如,在提供商的文件系统或存储桶中)的引用 ID。
ContentBlock.Multimodal.Audio
目的: 音频数据外部存储音频文件(例如,在提供商的文件系统或存储桶中)的引用 ID。
ContentBlock.Multimodal.Video
目的: 视频数据外部存储视频文件(例如,在提供商的文件系统或存储桶中)的引用 ID。
ContentBlock.Multimodal.File
目的: 通用文件(PDF 等)外部存储文件(例如,在提供商的文件系统或存储桶中)的引用 ID。
ContentBlock.Multimodal.PlainText
目的: 文档文本(.txt,.md)文本的MIME 类型 (例如,text/plain,text/markdown)
目的: 提供商特定的逃生舱口用法: 用于实验性或提供商独有的功能附加的提供商特定内容类型可在每个模型提供商的参考文档 中找到。
上面提到的每个内容块在导入 @[ContentBlock] 类型时都可以作为类型单独寻址。
import { ContentBlock } from "langchain" ;
// Text block
const textBlock : ContentBlock . Text = {
type: "text" ,
text: "Hello world" ,
}
// Image block
const imageBlock : ContentBlock . Multimodal . Image = {
type: "image" ,
url: "https://example.com/image.png" ,
mimeType: "image/png" ,
}
在 @[API reference][langchain.messages] 中查看规范类型定义。
内容块作为 LangChain v1 中消息的新属性引入,旨在标准化跨提供商的内容格式,同时保持与现有代码的向后兼容性。内容块不是 @[content][BaseMessage(content)] 属性的替代品,而是一个可以用于以标准化格式访问消息内容的新属性。
与聊天模型一起使用
聊天模型 接受一系列消息对象作为输入,并返回一个AIMessage 作为输出。交互通常是无状态的,因此一个简单的对话循环涉及使用不断增长的消息列表调用模型。 请参阅以下指南了解更多信息: