Skip to main content
TODO: 关于元数据类型(响应和用法)的章节 */}



消息是LangChain中模型的上下文基本单位。它们代表模型的输入和输出,携带了在与大型语言模型交互时表示对话状态的所需内容和元数据。

消息是包含以下内容的对象:

* <Icon icon="user" size={16} /> [**角色**](#message-types) - 识别消息类型(例如 `system`,`user`)
* <Icon icon="folder-closed" size={16} /> [**内容**](#message-content) - 表示消息的实际内容(如文本、图片、音频、文档等)
* <Icon icon="tag" size={16} /> [**元数据**](#message-metadata) - 可选字段,如响应信息、消息ID和令牌使用情况

LangChain提供了一种标准消息类型,该类型适用于所有模型提供者,确保无论调用哪种模型,都能保持一致的行为。

## 基本用法

最简单使用消息的方式是创建消息对象,并在[调用](/oss/javascript/langchain/models#invocation)时将它们传递给模型。



```typescript
import { initChatModel, HumanMessage, SystemMessage } from "langchain";

const model = await initChatModel("openai: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] 代表一组初始指令,用于启动模型的行为。您可以使用系统消息来设定语气、定义模型的角色,并建立响应的指导方针。
Basic instructions
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);
Detailed persona
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] 代表用户输入和交互。它们可以包含文本、图片、音频、文件以及其他任何数量的多模态 内容

文本内容

Message object
const response = await model.invoke([
  new HumanMessage("What is machine learning?"),
]);
String shortcut
const response = await model.invoke("What is machine learning?");

消息元数据

Add metadata
const humanMsg = new HumanMessage({
  content: "Hello!",
  name: "alice",
  id: "msg_123",
});
name 字段的行为因提供商而异 - 有些用于用户识别,而有些则忽略它。要进行检查,请参阅模型提供商的参考

人工智能消息

一个 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);
text
string
消息的文本内容。
content
string | ContentBlock[]
消息的原始内容。
content_blocks
ContentBlock.Standard[]
消息的标准内容块。(见 [内容](#message-content))
tool_calls
ToolCall[] | None
模型调用的工具。如果没有调用工具,则为空。
id
string
消息的唯一标识符(由 LangChain 自动生成或由提供者响应返回)
usage_metadata
UsageMetadata | None
消息的使用元数据,其中可能包含可用的令牌计数。见 [参考](https://reference.langchain.com/javascript/types/_langchain_core.messages.UsageMetadata.html)。
response_metadata
ResponseMetadata | None
消息的响应元数据。

工具调用

当模型进行工具调用时,它们被包含在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}`);
}
其他结构化数据,例如推理或引用,也可以出现在消息内容 /oss/javascript/langchain/messages#message-content

令牌使用

一个 AIMessage 可以在其 usage_metadata 字段中存储令牌计数和其他使用元数据:
import { initChatModel } from "langchain";

const model = await initChatModel("openai: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
content
string
required
工具调用的字符串化输出。
tool_call_id
string
required
此消息响应的工具调用的ID。(此ID必须与AIMessage中的工具调用ID匹配)
name
string
required
被调用的工具名称。
artifact
dict
未发送到模型但可以通过程序访问的附加数据。
artifact 字段存储了不会发送到模型但可以通过程序访问的补充数据。这对于存储原始结果、调试信息或下游处理所需的数据非常有用,而不会使模型上下文变得杂乱。
例如,一个检索工具可以检索文档中的一段内容供模型参考。当消息content包含模型将引用的文本时,artifact可以包含文档标识符或其他应用程序可以使用(例如,用于渲染页面)的元数据。以下是一个示例:
import { ToolMessage } from "langchain";

// Artifact available downstream
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属性中,并且可以包含:
  1. 一串字符串
  2. 一系列以提供者原生格式的内容块列表
  3. 一系列 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 属性并将其解析为标准、类型安全的表示。例如,从 ChatAnthropicChatOpenAI 生成的消息将包含相应提供者格式的 thinkingreasoning 块,但可以懒加载解析为一致的 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(
  "openai:gpt-5-nano",
  { outputVersion: "v1" }
);

多模态

多模态指的是能够处理不同形式的数据的能力,例如文本、音频、图像和视频。LangChain 包含了这些数据的标准类型,可以在不同的提供商之间使用。 聊天模型 可以接受多模态数据作为输入并生成输出。以下我们展示了包含多模态数据的输入消息的简短示例。
额外的键可以包含在内容块的最高级别或嵌套在 "extras": {"key": value} 中。OpenAIAWS Bedrock Converse, 例如,需要为 PDF 文件指定一个文件名。请参阅您选择的模型的 提供者页面 获取详细信息。
// 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
string
required
Always "text"
text
string
required
文本内容
annotations
Citation[]
文本注释列表
示例:
                {
                    type: "text",
                    text: "Hello world",
                    annotations: []
                }
目的: 模型推理步骤
type
string
required
Always "reasoning"
reasoning
string
required
推理内容
Example:
{
    type: "reasoning",
    reasoning: "The user is asking about..."
}
目的: 图像数据
type
string
required
Always "image"
url
string
指向图像位置的URL。
data
string
Base64编码的图像数据。
fileId
string
引用外部存储的图像的参考ID(例如,在提供商的文件系统或存储桶中)。
mimeType
string
Image MIME type (e.g., image/jpeg, image/png)
Purpose: Audio data
type
string
required
Always "audio"
url
string
指向音频位置的URL。
data
string
Base64编码的音频数据。
fileId
string
引用外部存储的音频文件的参考ID(例如,在提供商的文件系统中或在存储桶中)。
mimeType
string
Audio MIME type (e.g., audio/mpeg, audio/wav)
Purpose: Video data
type
string
required
Always "video"
url
string
指向视频位置的URL。
data
string
Base64编码的视频数据。
fileId
string
引用外部存储的视频文件(例如,在提供商的文件系统或存储桶中)的参考ID。
mimeType
string
视频 MIME 类型(例如,video/mp4video/webm
目的: 通用文件(PDF 等)
type
string
required
Always "file"
url
string
指向文件位置的URL。
data
string
Base64编码的文件数据。
fileId
string
引用外部存储文件(例如,在提供商的文件系统或存储桶中)的参考ID。
mimeType
string
File MIME type (e.g., application/pdf)
Purpose: Document text (.txt, .md)
type
string
required
Always "text-plain"
text
string
required
文本内容
title
string
文本内容标题
mimeType
string
MIME type of the text (e.g., text/plain, text/markdown)
目的: 函数调用
type
string
required
Always "tool_call"
name
string
required
工具名称
args
object
required
需要传递给工具的参数
id
string
required
此工具调用的唯一标识符
示例:
                {
                    type: "tool_call",
                    name: "search",
                    args: { query: "weather" },
                    id: "call_123"
                }
目的: 流媒体工具片段
type
string
required
Always "tool_call_chunk"
name
string
被调用的工具名称
args
string
部分工具参数(可能是不完整的JSON)
id
string
工具调用标识符
index
number | string
required
此块在流中的位置
目的: 格式不正确的调用
type
string
required
Always "invalid_tool_call"
name
string
工具名称,调用失败
args
string
原始解析失败的参数
error
string
required
错误描述
常见错误: 无效的JSON,缺少必填字段
目的: 在服务器端执行的工具调用。
type
string
required
Always "server_tool_call"
id
string
required
与工具调用关联的标识符。
name
string
required
要调用的工具名称。
args
string
required
部分工具参数(可能是不完整的JSON)
目的: 流式化服务器端工具调用片段
type
string
required
Always "server_tool_call_chunk"
id
string
与工具调用关联的标识符。
name
string
被调用的工具名称
args
string
部分工具参数(可能是不完整的JSON)
index
number | string
此数据块在流中的位置
目的: 搜索结果
type
string
required
Always "server_tool_result"
tool_call_id
string
required
对应服务器工具调用的标识符。
id
string
与服务器工具结果关联的标识符。
status
string
required
服务器端工具的执行状态。"success""error"
output
执行工具的输出。
目的: 提供商特定的逃生门
type
string
required
Always "non_standard"
value
object
required
特定提供者数据结构
用法: 用于实验性或供应商特有的功能
在各个模型提供者的参考文档中可以找到额外的特定提供者内容类型。
上述提到的每个内容块都可以在导入 @[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参考][langchain.messages]中的规范类型定义。
在LangChain v1中引入了内容块作为消息的新属性,以在保持与现有代码向后兼容的同时,标准化提供者之间的内容格式。内容块不是@[content][BaseMessage(content)]属性的替代品,而是一个新的属性,可以用来以标准化格式访问消息的内容。

与聊天模型一起使用

聊天模型 接受一系列消息对象作为输入,并返回一个 AIMessage 作为输出。交互通常是无状态的,因此一个简单的对话循环涉及调用一个模型,并传递一个不断增长的消息列表。 参考以下指南以获取更多信息: