Documentation Index Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
消息是 LangChain 中模型上下文的基本单元。它们表示模型的输入和输出,携带与大语言模型(LLM)交互时表示对话状态所需的内容和元数据。
消息是包含以下内容的对象:
角色 - 标识消息类型(例如 system、user)
内容 - 表示消息的实际内容(如文本、图片、音频、文档等)
元数据 - 可选字段,如响应信息、消息 ID 和 Token 用量
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) ; // 返回 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 , // 插入,就像它来自模型一样
new HumanMessage ( "Great! What's 2+2?" )
]
const response = await model . invoke (messages) ;
工具调用
当模型进行工具调用 时,它们被包含在 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 字段中保存 Token 计数和其他使用元数据:
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 , // 模型的工具调用
toolMessage , // 工具执行结果
] ;
const response = await model . invoke (messages) ; // 模型处理结果
artifact 字段存储不会发送给模型但可以通过编程方式访问的补充数据。这对于存储原始结果、调试信息或用于下游处理的数据非常有用,而不会污染模型的上下文。
例如,检索 工具可以从文档中检索一段文本供模型参考。消息 content 包含模型将引用的文本,而 artifact 可以包含应用程序可以使用的文档标识符或其他元数据(例如用于渲染页面)。参见以下示例: import { ToolMessage } from "langchain" ;
// artifact 可在下游使用
const artifact = { document_id : "doc_123" , page : 0 };
const toolMessage = new ToolMessage ( {
content : "It was the best of times, it was the worst of times." ,
tool_call_id : "call_123" ,
name : "search_books" ,
artifact
} ) ;
参见 RAG 教程 了解使用 LangChain 构建检索智能体 的端到端示例。
消息内容
你可以将消息的内容视为发送给模型的数据载荷。消息有一个 content 属性,它是松散类型的,支持字符串和无类型对象列表(例如字典)。这允许在 LangChain 聊天模型中直接支持提供商原生结构,例如多模态 内容和其他数据。
另外,LangChain 为文本、推理过程、引用、多模态数据、服务端工具调用和其他消息内容提供了专用内容类型。参见下面的内容块 。
LangChain 聊天模型在 content 属性中接受消息内容。
它可以包含以下任一类型:
字符串
提供商原生格式的内容块列表
LangChain 标准内容块 列表
参见下面使用多模态 输入的示例:
import { HumanMessage } from "langchain" ;
// 字符串内容
const humanMessage = new HumanMessage ( "Hello, how are you?" ) ;
// 提供商原生格式(例如 OpenAI)
const humanMessage = new HumanMessage ( {
content : [
{ type : "text" , text : "Hello, how are you?" },
{
type : "image_url" ,
image_url : { url : "https://example.com/image.jpg" },
},
] ,
} ) ;
// 标准内容块列表
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) ;
import { AIMessage } from "@langchain/core/messages" ;
const message = new AIMessage ( {
content : [
{
"type" : "reasoning" ,
"id" : "rs_abc123" ,
"summary" : [
{ "type" : "summary_text" , "text" : "summary 1" },
{ "type" : "summary_text" , "text" : "summary 2" },
] ,
},
{ "type" : "text" , "text" : "..." },
] ,
response_metadata : { model_provider : "openai" },
} ) ;
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 包含这些数据的标准类型,可以跨提供商使用。
聊天模型 可以接受多模态数据作为输入并将其作为输出生成。下面展示包含多模态数据的输入消息的简短示例。
// 从 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"
},
] ,
} ) ;
// 从 base64 数据
const message = new HumanMessage ( {
content : [
{ type : "text" , text : "Describe the content of this image." },
{
type : "image" ,
source_type : "base64" ,
data : "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2..." ,
},
] ,
} ) ;
// 从提供商管理的文件 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
用途: 图片数据外部文件存储系统中图片的引用(例如 OpenAI 或 Anthropic 的 Files API)。
图片 MIME 类型 (例如 image/jpeg、image/png)。base64 数据时必需。
ContentBlock.Multimodal.Audio
用途: 音频数据外部文件存储系统中音频文件的引用(例如 OpenAI 或 Anthropic 的 Files API)。
音频 MIME 类型 (例如 audio/mpeg、audio/wav)。base64 数据时必需。
ContentBlock.Multimodal.Video
用途: 视频数据外部文件存储系统中视频文件的引用(例如 OpenAI 或 Anthropic 的 Files API)。
视频 MIME 类型 (例如 video/mp4、video/webm)。base64 数据时必需。
ContentBlock.Multimodal.File
用途: 通用文件(PDF 等)外部文件存储系统中文件的引用(例如 OpenAI 或 Anthropic 的 Files API)。
文件 MIME 类型 (例如 application/pdf)。base64 数据时必需。
ContentBlock.Multimodal.PlainText
用途: 文档文本(.txt、.md)文本的 MIME 类型 (例如 text/plain、text/markdown)
用途: 提供商特定的兜底方案用法: 用于实验性或提供商独有的功能其他提供商特定的内容类型可以在每个模型提供商的参考文档 中找到。
上述提到的每个内容块在导入 ContentBlock 类型时都可以作为独立类型单独引用。
import { ContentBlock } from "langchain" ;
// 文本块
const textBlock : ContentBlock . Text = {
type : "text" ,
text : "Hello world" ,
}
// 图片块
const imageBlock : ContentBlock . Multimodal . Image = {
type : "image" ,
url : "https://example.com/image.png" ,
mimeType : "image/png" ,
}
内容块作为消息的新属性在 LangChain v1 中引入,用于标准化跨提供商的内容格式,同时保持与现有代码的向后兼容性。 内容块不是 content 属性的替代品,而是一个可用于以标准化格式访问消息内容的新属性。
与聊天模型配合使用
聊天模型 接受消息对象序列作为输入,并返回 AIMessage 作为输出。交互通常是无状态的,因此简单的对话循环涉及使用不断增长的消息列表调用模型。
参考以下指南了解更多:
将这些文档连接 到 Claude、VSCode 等工具,通过 MCP 获取实时答案。