Messages 是 LangChain 中模型上下文的基本单元。它们表示模型的输入和输出,并携带与 LLM 交互时表示对话状态所需的内容和 metadata。 Messages 是包含以下内容的对象:
  • Role:标识 message 类型,例如 systemuser
  • Content:表示 message 的实际内容,例如文本、图像、音频、文档等
  • Metadata:可选字段,例如响应信息、message IDs 和 token 用量
LangChain 提供可跨所有模型 provider 使用的标准 message 类型,确保无论调用哪个模型都具有一致行为。

基本用法

使用 messages 最简单的方式,是创建 message 对象,并在 invoking 模型时将其传给模型。
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
多轮 agents 会累积很长的 message 历史。LangSmith 会记录每一轮、工具结果和模型响应,便于你检查完整对话。按照 tracing quickstart 启用 tracing。建议同时设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

Text prompts

Text prompts 是字符串,适合不需要保留对话历史的简单生成任务。
const response = await model.invoke("Write a haiku about spring");
在以下情况下使用 text prompts:
  • 你有单个独立请求
  • 你不需要对话历史
  • 你希望代码复杂度最低

Message prompts

也可以通过提供 message 对象列表,将一组 messages 传给模型。
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);
在以下情况下使用 message prompts:
  • 管理多轮对话
  • 处理多模态内容(图像、音频、文件)
  • 包含 system instructions

Dictionary format

也可以直接使用 OpenAI chat completions 格式指定 messages。
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);

Message types

System message

SystemMessage 表示一组用于引导模型行为的初始指令。可以使用 system message 设置语气、定义模型角色,并建立响应准则。
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);

Human message

HumanMessage 表示用户输入和交互。它可以包含文本、图像、音频、文件,以及任意数量的多模态 content

Text content

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

Message metadata

Add metadata
const humanMsg = new HumanMessage({
  content: "Hello!",
  name: "alice",
  id: "msg_123",
});
name 字段的行为因 provider 而异,有些 provider 会用它识别用户,其他 provider 会忽略它。如需确认,请参阅模型 provider 的 reference

AI message

AIMessage 表示模型调用的输出。它可以包含多模态数据、工具调用,以及稍后可访问的 provider-specific metadata。
const response = await model.invoke("Explain AI");
console.log(typeof response);  // AIMessage
调用模型时,模型会返回 AIMessage 对象,其中包含响应中的所有相关 metadata。 不同 providers 会以不同方式权衡和理解不同类型的 messages,因此有时手动创建新的 AIMessage 对象并将其插入 message 历史会很有用,就像它来自模型一样。
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
Message 的文本内容。
content
string | ContentBlock[]
Message 的原始内容。
content_blocks
ContentBlock.Standard[]
Message 的标准化 content blocks。(参阅 content
tool_calls
ToolCall[] | None
模型发出的工具调用。如果没有调用 tools,则为空。
id
string
Message 的唯一标识符,由 LangChain 自动生成或在 provider 响应中返回。
usage_metadata
UsageMetadata | None
Message 的 usage metadata,可在可用时包含 token 计数。参阅 UsageMetadata
response_metadata
ResponseMetadata | None
Message 的 response metadata。

Tool calls

当模型发出 tool calls 时,这些调用会包含在 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}`);
}
其他结构化数据,例如 reasoning 或 citations,也可以出现在 message content 中。

Token usage

AIMessage 可以在其 usage_metadata 字段中保存 token 计数和其他 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

Streaming and chunks

在 streaming 期间,你会收到 AIMessageChunk 对象,它们可以合并成完整的 message 对象:
import { AIMessageChunk } from "langchain";

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

Tool message

对于支持 tool calling 的模型,AI messages 可以包含工具调用。Tool messages 用于将单个工具执行的结果传回模型。 Tools 可以直接生成 ToolMessage 对象。下面展示一个简单示例。更多内容请阅读 tools guide
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
此 message 响应的工具调用 ID。必须与 AIMessage 中的工具调用 ID 匹配。
name
string
required
被调用工具的名称。
artifact
dict
不发送给模型、但可通过程序访问的额外数据。
artifact 字段存储不会发送给模型、但可通过程序访问的补充数据。这适合存储原始结果、调试信息或用于下游处理的数据,同时避免污染模型上下文。
例如,retrieval 工具可以从文档中检索一段文本,供模型参考。Message content 包含模型会引用的文本,而 artifact 可以包含文档标识符或应用可使用的其他 metadata,例如用于渲染页面。请参阅下面的示例:
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
});
如需查看使用 LangChain 构建 retrieval agents 的端到端示例,请参阅 RAG tutorial

Message content

可以将 message 的 content 理解为发送给模型的数据负载。Messages 具有一个弱类型的 content 属性,支持字符串和无类型对象列表(例如字典)。这让 LangChain chat models 能够直接支持 provider-native 结构,例如 multimodal 内容和其他数据。 此外,LangChain 为文本、reasoning、citations、多模态数据、server-side tool calls 以及其他 message content 提供专用 content 类型。请参阅下面的 content blocks LangChain chat models 通过 content 属性接收 message content。 它可以包含以下任一内容:
  1. 字符串
  2. provider-native 格式的 content blocks 列表
  3. LangChain’s standard content blocks 列表
下面是使用 multimodal 输入的示例:
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" },
  ],
});

Standard content blocks

LangChain 为 message content 提供可跨 providers 使用的标准表示。 Message 对象实现了 contentBlocks 属性,会将 content 属性惰性解析为标准、类型安全的表示。例如,由 ChatAnthropicChatOpenAI 生成的 messages 会包含对应 provider 格式的 thinkingreasoning blocks,但可以惰性解析为一致的 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);
请参阅 integrations guides,开始使用你选择的 inference provider。
序列化标准 content如果 LangChain 外部的应用需要访问标准 content block 表示,可以选择将 content blocks 存储在 message content 中。为此,可以将 LC_OUTPUT_VERSION 环境变量设置为 v1。也可以使用 outputVersion: "v1" 初始化任意 chat model:
import { initChatModel } from "langchain";

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

Multimodal

Multimodality 指处理不同形式数据的能力,例如文本、音频、图像和视频。LangChain 为这些数据提供可跨 providers 使用的标准类型。 Chat models 可以接受多模态数据作为输入,并生成多模态数据作为输出。下面展示包含多模态数据的输入 messages 简短示例。
额外 keys 可以包含在 content block 顶层,或嵌套在 "extras": {"key": value} 中。OpenAI, 例如,PDF 需要 filename。具体要求请参阅所选模型的 provider page
// 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",
      mime_type: "image/jpeg",
      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" },
  ],
});
并非所有模型都支持所有文件类型。请查看模型 provider 的 reference,了解支持的格式和大小限制。

Content block reference

Content blocks 表示为类型化对象列表,无论是在创建 message 时,还是访问 contentBlocks 字段时都是如此。列表中的每一项都必须符合以下 block 类型之一:
用途: 标准文本输出
type
string
required
始终为 "text"
text
string
required
文本内容
annotations
Citation[]
文本的 annotations 列表
示例:
{
    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 type,例如 image/jpegimage/png。base64 数据必须提供。
用途: 音频数据
type
string
required
始终为 "audio"
url
string
指向音频位置的 URL。
data
string
Base64 编码的音频数据。
fileId
string
对外部文件存储系统中音频文件的引用,例如 OpenAI 或 Anthropic 的 Files API。
mimeType
string
音频 MIME type,例如 audio/mpegaudio/wav。base64 数据必须提供。
用途: 视频数据
type
string
required
始终为 "video"
url
string
指向视频位置的 URL。
data
string
Base64 编码的视频数据。
fileId
string
对外部文件存储系统中视频文件的引用,例如 OpenAI 或 Anthropic 的 Files API。
mimeType
string
视频 MIME type,例如 video/mp4video/webm。base64 数据必须提供。
用途: 通用文件(PDF 等)
type
string
required
始终为 "file"
url
string
指向文件位置的 URL。
data
string
Base64 编码的文件数据。
fileId
string
对外部文件存储系统中文件的引用,例如 OpenAI 或 Anthropic 的 Files API。
mimeType
string
文件 MIME type,例如 application/pdf。base64 数据必须提供。
用途: 文档文本(.txt.md
type
string
required
始终为 "text-plain"
text
string
required
文本内容
title
string
文本内容的标题
mimeType
string
文本的 MIME type,例如 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
此 chunk 在 stream 中的位置
用途: 格式错误的调用
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)
用途: 流式 server-side 工具调用片段
type
string
required
始终为 "server_tool_call_chunk"
id
string
与工具调用关联的标识符。
name
string
正在调用的工具名称
args
string
部分工具参数(可能是不完整 JSON)
index
number | string
此 chunk 在 stream 中的位置
用途: 搜索结果
type
string
required
始终为 "server_tool_result"
tool_call_id
string
required
对应 server tool call 的标识符。
id
string
与 server tool result 关联的标识符。
status
string
required
Server-side tool 的执行状态。"success""error"
output
已执行工具的输出。
用途: Provider-specific escape hatch
type
string
required
始终为 "non_standard"
value
object
required
Provider-specific 数据结构
用法: 用于实验性功能或 provider 独有功能
其他 provider-specific content 类型可在各模型 provider 的 reference documentation 中找到。
导入 ContentBlock 类型后,上述每个 content block 都可以作为单独类型寻址。
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 中查看规范类型定义。
Content blocks 是 LangChain v1 在 messages 上引入的新属性,用于在保持现有代码向后兼容的同时,跨 providers 标准化 content 格式。Content blocks 并不是 content 属性的替代品,而是一个新属性,可用于以标准化格式访问 message content。

Use with chat models

Chat models 接受一组 message 对象作为输入,并返回 AIMessage 作为输出。交互通常是无状态的,因此简单的对话循环会使用不断增长的 messages 列表调用模型。 请参阅以下指南了解更多: