Skip to content

消息(Messages) ​

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

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

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

基础用法 ​

使用消息最简单的方式是创建消息对象,并在调用时将其传递给模型。

typescript
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

TIP

多轮智能体会累积较长的消息历史。LangSmith 会记录每一轮交互、工具执行结果和模型响应,以便您检查完整的对话。请按照追踪快速入门开启追踪。

我们还建议您配置 LangSmith Engine,它可以监控您的追踪、检测问题并提出修复建议。

文本提示词 ​

文本提示词是字符串——非常适合不需要保留对话历史的简单生成任务。

typescript
const response = await model.invoke("Write a haiku about spring");

在以下情况下使用文本提示词:

  • 只有单个独立的请求
  • 不需要对话历史
  • 希望代码复杂度尽可能低

消息提示词 ​

或者,您可以通过提供消息对象列表,将消息列表传递给模型。

typescript
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 聊天补全(chat completions)格式来指定消息。

typescript
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 表示一组用于引导模型行为的初始指令。您可以使用系统消息来设定基调、定义模型的角色,并确立响应准则。

typescript
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);
typescript
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 表示用户输入和交互。它们可以包含文本、图像、音频、文件以及任何数量的多模态内容。

文本内容 ​

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

消息元数据 ​

Add metadata
typescript
const humanMsg = new HumanMessage({
  content: "Hello!",
  name: "alice",
  id: "msg_123",
});

NOTE

name 字段的行为因提供商而异——有些提供商用它来进行用户标识,有些则会忽略它。如需确认,请参阅模型提供商的参考文档。


AI 消息 ​

AIMessage 表示模型调用的输出。它们可以包含多模态数据、工具调用以及您稍后可以访问的提供商专用元数据。

typescript
const response = await model.invoke("Explain AI");
console.log(typeof response);  // AIMessage

调用模型时会返回 AIMessage 对象,其中包含响应中的所有关联元数据。

不同的提供商对不同类型的消息赋予的权重/上下文理解有所不同,这意味着有时手动创建一个新的 AIMessage 对象并将其插入到消息历史中(就如同它来自模型一样)会很有帮助。

typescript
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);

Attributes(属性)

text string

消息的文本内容。

content string | ContentBlock[]

消息的原始内容。

content_blocks ContentBlock.Standard[]

消息的标准化内容块。(参见内容)

tool_calls ToolCall[] | None

模型发起的工具调用。

如果未调用任何工具则为空。

id string

消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)

usage_metadata UsageMetadata | None

消息的用量元数据,在可用时可包含 Token 计数。参见 UsageMetadata。

response_metadata ResponseMetadata | None

消息的响应元数据。

工具调用 ​

当模型发起工具调用时,它们会被包含在 AIMessage 中:

typescript
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 计数和其他用量元数据:

typescript
import { initChatModel } from "langchain";

const model = await initChatModel("gpt-5-nano");

const response = await model.invoke("Hello!");
console.log(response.usage_metadata);
json
{
  "output_tokens": 304,
  "input_tokens": 8,
  "total_tokens": 312,
  "input_token_details": {
    "cache_read": 0
  },
  "output_token_details": {
    "reasoning": 256
  }
}

详情请参阅 UsageMetadata。

流式传输与分块 ​

在流式传输期间,您将收到 AIMessageChunk 对象,它们可以合并为一个完整的消息对象:

typescript
import { AIMessageChunk } from "langchain";

let finalChunk: AIMessageChunk | undefined;
for (const chunk of chunks) {
  finalChunk = finalChunk ? finalChunk.concat(chunk) : chunk;
}

工具消息 ​

对于支持工具调用的模型,AI 消息中可以包含工具调用。工具消息用于将单次工具执行的结果传回给模型。

工具可以直接生成 ToolMessage 对象。下面我们展示一个简单的示例。更多内容请参阅工具指南。

typescript
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);  // 模型处理该结果

Attributes(属性)

content string 必需

工具调用的字符串化输出。

tool_call_id string 必需

此消息所响应的工具调用 ID。必须与 AIMessage 中的工具调用 ID 相匹配。

name string 必需

被调用的工具名称。

artifact dict

不会发送给模型但可以通过编程方式访问的附加数据。

NOTE

artifact 字段用于存储补充数据,这些数据不会发送给模型,但可以通过代码以编程方式访问。这对于存储原始结果、调试信息或供下游处理的数据非常有用,且不会污染模型的上下文。

示例:使用 artifact 存储检索元数据

例如,检索工具可以从文档中检索出供模型参考的段落。消息的 content 包含模型引用的文本,而 artifact 可以包含应用程序可使用的文档标识符或其他元数据(例如用于渲染页面)。参见以下示例:

typescript
import { ToolMessage } from "langchain";

// 可在下游使用的工件数据
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
});

有关使用 LangChain 构建检索智能体的端到端示例,请参阅 RAG 教程。


消息内容 ​

您可以将消息的内容视为发送给模型的有效数据载荷(payload)。消息具有一个弱类型的 content 属性,支持字符串和非类型化对象列表(例如字典)。这使得 LangChain 聊天模型可以直接支持提供商的原生结构,例如多模态内容及其他数据。

此外,LangChain 为文本、推理、引用、多模态数据、服务端工具调用以及其他消息内容提供了专用的内容类型。请参见下文的内容块。

LangChain 聊天模型在 content 属性中接收消息内容。

该属性可以包含以下任一项:

  1. 字符串
  2. 提供商原生格式的内容块列表
  3. LangChain 的标准内容块列表

有关使用多模态输入的示例,请参见下文:

typescript
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 表示:

Anthropic

typescript
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);

OpenAI

typescript
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);

请参阅集成指南以开始使用您选择的推理提供商。

NOTE

序列化标准内容

如果 LangChain 之外的应用程序需要访问标准内容块表示,您可以选择在消息内容中存储内容块。

为此,您可以将 LC_OUTPUT_VERSION 环境变量设置为 v1。或者,在初始化任何聊天模型时指定 outputVersion: "v1":

typescript
import { initChatModel } from "langchain";

const model = await initChatModel(
  "gpt-5-nano",
  { outputVersion: "v1" }
);

多模态 ​

多模态(Multimodality)是指处理以不同形式出现的数据的能力,例如文本、音频、图像和视频。LangChain 包含了可跨提供商使用的这些数据的标准类型。

聊天模型可以接收多模态数据作为输入,并将其生成为输出。下面我们展示包含多模态数据的输入消息的简短示例。

NOTE

额外的键可以直接包含在内容块的顶层,也可以嵌套在 "extras": {"key": value} 中。

例如,OpenAI 对 PDF 文件要求提供文件名。具体细节请参阅您所选模型的提供商页面。

typescript
// 来自 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",
      mime_type: "image/jpeg",
      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" },
  ],
});
typescript
// 来自 URL
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this document." },
    { type: "file", source_type: "url", url: "https://example.com/path/to/document.pdf", mime_type: "application/pdf" },
  ],
});

// 来自 Base64 数据
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this document." },
    {
      type: "file",
      source_type: "base64",
      data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
      mime_type: "application/pdf",
    },
  ],
});

// 来自提供商托管的文件 ID
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this document." },
    { type: "file", source_type: "id", id: "file-abc123" },
  ],
});
typescript
// 来自 Base64 数据
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this audio." },
    {
      type: "audio",
      source_type: "base64",
      data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
    },
  ],
});

// 来自提供商托管的文件 ID
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this audio." },
    { type: "audio", source_type: "id", id: "file-abc123" },
  ],
});
typescript
// 来自 Base64 数据
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this video." },
    {
      type: "video",
      source_type: "base64",
      data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
    },
  ],
});

// 来自提供商托管的文件 ID
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this video." },
    { type: "video", source_type: "id", id: "file-abc123" },
  ],
});

WARNING

并非所有模型都支持所有文件类型。请查阅模型提供商的参考文档以了解支持的格式和大小限制。

内容块参考 ​

内容块(无论是在创建消息时还是访问 contentBlocks 字段时)均表示为类型化对象的列表。列表中的每一项都必须符合以下块类型之一:

Core

ContentBlock.Text

用途: 标准文本输出

type string 必需

固定为 "text"

text string 必需

文本内容

annotations Citation[]

文本的注释列表

示例:

typescript
{
    type: "text",
    text: "Hello world",
    annotations: []
}

ContentBlock.Reasoning

用途: 模型推理步骤

type string 必需

固定为 "reasoning"

reasoning string 必需

推理内容

示例:

typescript
{
    type: "reasoning",
    reasoning: "The user is asking about..."
}

Multimodal

ContentBlock.Multimodal.Image

用途: 图像数据

type string 必需

固定为 "image"

url string

指向图像位置的 URL。

data string

Base64 编码的图像数据。

fileId string

对外部文件存储系统(例如 OpenAI 或 Anthropic 的 Files API)中图像的引用。

mimeType string

图像 MIME 类型(例如 image/jpeg、image/png)。对于 Base64 数据是必需的。

ContentBlock.Multimodal.Audio

用途: 音频数据

type string 必需

固定为 "audio"

url string

指向音频位置的 URL。

data string

Base64 编码的音频数据。

fileId string

对外部文件存储系统(例如 OpenAI 或 Anthropic 的 Files API)中音频文件的引用。

mimeType string

音频 MIME 类型(例如 audio/mpeg、audio/wav)。对于 Base64 数据是必需的。

ContentBlock.Multimodal.Video

用途: 视频数据

type string 必需

固定为 "video"

url string

指向视频位置的 URL。

data string

Base64 编码的视频数据。

fileId string

对外部文件存储系统(例如 OpenAI 或 Anthropic 的 Files API)中视频文件的引用。

mimeType string

视频 MIME 类型(例如 video/mp4、video/webm)。对于 Base64 数据是必需的。

ContentBlock.Multimodal.File

用途: 通用文件(PDF 等)

type string 必需

固定为 "file"

url string

指向文件位置的 URL。

data string

Base64 编码的文件数据。

fileId string

对外部文件存储系统(例如 OpenAI 或 Anthropic 的 Files API)中文件的引用。

mimeType string

文件 MIME 类型(例如 application/pdf)。对于 Base64 数据是必需的。

ContentBlock.Multimodal.PlainText

用途: 文档文本(.txt、.md)

type string 必需

固定为 "text-plain"

text string 必需

文本内容

title string

文本内容的标题

mimeType string

文本的 MIME 类型(例如 text/plain、text/markdown)

Tool Calling

ContentBlock.Tools.ToolCall

用途: 函数调用

type string 必需

固定为 "tool_call"

name string 必需

要调用的工具名称

args object 必需

传递给工具的参数

id string 必需

该工具调用的唯一标识符

示例:

typescript
{
    type: "tool_call",
    name: "search",
    args: { query: "weather" },
    id: "call_123"
}

ContentBlock.Tools.ToolCallChunk

用途: 流式传输的工具分片

type string 必需

固定为 "tool_call_chunk"

name string

正在调用的工具名称

args string

部分工具参数(可能是不完整的 JSON)

id string

工具调用标识符

index number | string 必需

该分块在流中的位置

ContentBlock.Tools.InvalidToolCall

用途: 格式错误的调用

type string 必需

固定为 "invalid_tool_call"

name string

调用失败的工具名称

args string

解析失败的原始参数

error string 必需

错误原因说明

常见错误: 无效的 JSON、缺少必填字段

Server-Side Tool Execution

ContentBlock.Tools.ServerToolCall

用途: 在服务端执行的工具调用。

type string 必需

固定为 "server_tool_call"

id string 必需

与工具调用关联的标识符。

name string 必需

要调用的工具名称。

args string 必需

部分工具参数(可能是不完整的 JSON)

ContentBlock.Tools.ServerToolCallChunk

用途: 流式传输的服务端工具调用分片

type string 必需

固定为 "server_tool_call_chunk"

id string

与工具调用关联的标识符。

name string

正在调用的工具名称

args string

部分工具参数(可能是不完整的 JSON)

index number | string 必需

该分块在流中的位置

ContentBlock.Tools.ServerToolResult

用途: 搜索结果

type string 必需

固定为 "server_tool_result"

tool_call_id string 必需

对应服务端工具调用的标识符。

id string

与服务端工具结果关联的标识符。

status string 必需

服务端工具的执行状态。"success" 或 "error"。

output

已执行工具的输出。

Provider-Specific Blocks

ContentBlock.NonStandard

用途: 提供商特定的应急扩展出口(escape hatch)

type string 必需

固定为 "non_standard"

value object 必需

提供商特定的数据结构

用法: 用于实验性功能或提供商特有功能

其他提供商专用的内容类型可以在各模型提供商的参考文档中找到。

导入 ContentBlock 类型时,上述提到的每一个内容块都可以作为独立的类型来使用。

typescript
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",
}

TIP

在 API 参考中查看规范的类型定义。

NOTE

内容块作为消息的一个新属性在 LangChain v1 中引入,旨在标准化跨提供商的内容格式,同时保持与现有代码的向后兼容性。

内容块并不是 content 属性的替代品,而是一个可以以标准化格式访问消息内容的新属性。

序列化 ​

您可以将消息序列化为普通对象进行存储,并反序列化回消息实例。这对于持久化对话历史和恢复会话非常有用。

ts
import { HumanMessage } from "@langchain/core/messages";
import { load } from "@langchain/core/load";

const message = new HumanMessage("What is the capital of France?");

// 序列化为普通对象
const serialized = message.toJSON();

// 反序列化回消息对象
const restored = await load<HumanMessage>(JSON.stringify(serialized));

WARNING

load() 通过实例化类和调用构造函数来反序列化数据。切勿在不受信任或用户提供的输入上调用 load()。 仅反序列化来自您控制的来源(例如您自己的数据库)的数据。

与聊天模型配合使用 ​

聊天模型接受一系列消息对象作为输入,并返回 AIMessage 作为输出。交互通常是无状态的,因此一个简单的对话循环就是使用不断增长的消息列表来调用模型。

请参阅以下指南了解更多信息: