Skip to main content
消息是 LangChain 中模型上下文的基本单位。它们代表模型的输入和输出,承载着与 LLM 交互时表示对话状态所需的内容和元数据。 消息是包含以下内容的对象:
  • 角色 - 标识消息类型(例如 systemuser
  • 内容 - 表示消息的实际内容(如文本、图像、音频、文档等)
  • 元数据 - 可选字段,如响应信息、消息 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 表示一组初始指令,用于引导模型的行为。您可以使用系统消息来设置语气、定义模型的角色并建立响应指南。
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 字段的行为因提供商而异——有些用于用户标识,有些则忽略。要检查,请参阅模型提供商的参考

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);
text
string
消息的文本内容。
content
string | ContentBlock[]
消息的原始内容。
content_blocks
ContentBlock.Standard[]
消息的标准化内容块。(参见内容
tool_calls
ToolCall[] | None
模型进行的工具调用。如果未调用任何工具,则为空。
id
string
消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)
usage_metadata
UsageMetadata | None
消息的使用元数据,可在可用时包含令牌计数。参见 UsageMetadata
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}`);
}
其他结构化数据,例如推理或引用,也可能出现在消息内容中。

令牌使用情况

一个 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
content
string
required
工具调用的字符串化输出。
tool_call_id
string
required
此消息响应的工具调用 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(
  "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
始终为 "text"
text
string
required
文本内容
annotations
Citation[]
文本的注释列表
示例:
{
    type: "text",
    text: "Hello world",
    annotations: []
}
目的: 模型推理步骤
type
string
required
始终为 "reasoning"
reasoning
string
required
推理内容
示例:
{
    type: "reasoning",
    reasoning: "The user is asking about..."
}
目的: 图像数据
type
string
required
始终为 "image"
url
string
指向图像位置的 URL。
data
string
Base64 编码的图像数据。
fileId
string
外部文件存储系统中图像的引用(例如,OpenAI 或 Anthropic 的 Files API)。
mimeType
string
图像 MIME 类型(例如,image/jpegimage/png)。对于 base64 数据是必需的。
目的: 音频数据
type
string
required
始终为 "audio"
url
string
指向音频位置的 URL。
data
string
Base64 编码的音频数据。
fileId
string
外部文件存储系统中音频文件的引用(例如,OpenAI 或 Anthropic 的 Files API)。
mimeType
string
音频 MIME 类型(例如,audio/mpegaudio/wav)。对于 base64 数据是必需的。
目的: 视频数据
type
string
required
始终为 "video"
url
string
指向视频位置的 URL。
data
string
Base64 编码的视频数据。
fileId
string
外部文件存储系统中视频文件的引用(例如,OpenAI 或 Anthropic 的 Files API)。
mimeType
string
视频 MIME 类型(例如,video/mp4video/webm)。对于 base64 数据是必需的。
目的: 通用文件(PDF 等)
type
string
required
始终为 "file"
url
string
指向文件位置的 URL。
data
string
Base64 编码的文件数据。
fileId
string
外部文件存储系统中文件的引用(例如,OpenAI 或 Anthropic 的 Files API)。
mimeType
string
文件 MIME 类型(例如,application/pdf)。对于 base64 数据是必需的。
目的: 文档文本(.txt.md
type
string
required
始终为 "text-plain"
text
string
required
文本内容
title
string
文本内容的标题
mimeType
string
文本的 MIME 类型(例如,text/plaintext/markdown
目的: 函数调用
type
string
required
始终为 "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
始终为 "tool_call_chunk"
name
string
正在调用的工具名称
args
string
部分工具参数(可能是不完整的 JSON)
id
string
工具调用标识符
index
number | string
required
此分块在流中的位置
目的: 格式错误的调用
type
string
required
始终为 "invalid_tool_call"
name
string
未能调用的工具名称
args
string
未能解析的原始参数
error
string
required
出错原因的描述
常见错误: 无效的 JSON,缺少必填字段
目的: 在服务器端执行的工具调用。
type
string
required
始终为 "server_tool_call"
id
string
required
与工具调用关联的标识符。
name
string
required
要调用的工具名称。
args
string
required
部分工具参数(可能是不完整的 JSON)
目的: 流式服务器端工具调用片段
type
string
required
始终为 "server_tool_call_chunk"
id
string
与工具调用关联的标识符。
name
string
正在调用的工具名称
args
string
部分工具参数(可能是不完整的 JSON)
index
number | string
此分块在流中的位置
目的: 搜索结果
type
string
required
始终为 "server_tool_result"
tool_call_id
string
required
相应服务器工具调用的标识符。
id
string
与服务器工具结果关联的标识符。
status
string
required
服务器端工具的执行状态。"success""error"
output
执行工具的输出。
目的: 提供商特定的逃生舱
type
string
required
始终为 "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 v1 中引入,用于标准化跨提供商的内容格式,同时保持与现有代码的向后兼容性。内容块不是 content 属性的替代品,而是一个新属性,可用于以标准化格式访问消息的内容。

与聊天模型一起使用

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