> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 消息

消息是 LangChain 中模型上下文的基本单元。它们代表模型的输入和输出，携带内容和元数据，用于在与 LLM 交互时表示对话状态。

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

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

LangChain 提供了一种标准消息类型，适用于所有模型提供商，确保无论调用哪个模型，行为都保持一致。

## 基本用法

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

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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
```

### 文本提示

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

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const response = await model.invoke("Write a haiku about spring");
```

**在以下情况下使用文本提示：**

* 你有一个单一的、独立的请求
* 你不需要对话历史
* 你希望代码复杂度最小

### 消息提示

或者，你可以通过提供消息对象列表来向模型传递消息列表。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 聊天补全格式中指定消息。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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);
```

## 消息类型

* <Icon icon="settings" size={16} /> [系统消息](#系统消息) - 告诉模型如何行为并为交互提供上下文
* <Icon icon="user" size={16} /> [人类消息](#人类消息) - 代表用户输入和与模型的交互
* <Icon icon="robot" size={16} /> [AI 消息](#ai-消息) - 模型生成的响应，包括文本内容、工具调用和元数据
* <Icon icon="tool" size={16} /> [工具消息](#工具消息) - 代表[工具调用](/oss/javascript/langchain/models#tool-calling)的输出

### 系统消息

[`SystemMessage`](https://reference.langchain.com/javascript/langchain-core/messages/SystemMessage) 代表一组初始指令，用于引导模型的行为。你可以使用系统消息来设定基调、定义模型的角色，并建立响应的准则。

```typescript 基本指令 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 详细角色设定 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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`](https://reference.langchain.com/javascript/langchain-core/messages/HumanMessage) 代表用户输入和交互。它们可以包含文本、图像、音频、文件以及任何其他数量的多模态[内容](#消息内容)。

#### 文本内容

```typescript 消息对象 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const response = await model.invoke([
  new HumanMessage("What is machine learning?"),
]);
```

```typescript 字符串快捷方式 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const response = await model.invoke("What is machine learning?");
```

#### 消息元数据

```typescript 添加元数据 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const humanMsg = new HumanMessage({
  content: "Hello!",
  name: "alice",
  id: "msg_123",
});
```

<Note>
  `name` 字段的行为因提供商而异——有些用它来识别用户，有些则忽略它。要检查，请参阅模型提供商的[参考文档](https://reference.langchain.com/python/integrations/)。
</Note>

***

### AI 消息

[`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 代表模型调用的输出。它们可以包含多模态数据、工具调用以及提供商特定的元数据，你稍后可以访问这些数据。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const response = await model.invoke("Explain AI");
console.log(typeof response);  // AIMessage
```

[`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 对象在调用模型时返回，其中包含响应中所有相关的元数据。

提供商对不同类型的消息进行不同的加权/上下文化，这意味着有时手动创建一个新的 [`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 对象并将其插入消息历史记录中（就像它来自模型一样）会很有帮助。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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);
```

<Accordion title="属性">
  <ParamField path="text" type="string">
    消息的文本内容。
  </ParamField>

  <ParamField path="content" type="string | ContentBlock[]">
    消息的原始内容。
  </ParamField>

  <ParamField path="content_blocks" type="ContentBlock.Standard[]">
    消息的标准化内容块。（参见[内容](#消息内容)）
  </ParamField>

  <ParamField path="tool_calls" type="ToolCall[] | None">
    模型进行的工具调用。

    如果没有调用工具，则为空。
  </ParamField>

  <ParamField path="id" type="string">
    消息的唯一标识符（由 LangChain 自动生成或在提供商响应中返回）
  </ParamField>

  <ParamField path="usage_metadata" type="UsageMetadata | None">
    消息的使用元数据，可在可用时包含令牌计数。参见 [`UsageMetadata`](https://reference.langchain.com/javascript/langchain-core/messages/UsageMetadata)。
  </ParamField>

  <ParamField path="response_metadata" type="ResponseMetadata | None">
    消息的响应元数据。
  </ParamField>
</Accordion>

#### 工具调用

当模型进行[工具调用](/oss/javascript/langchain/models#tool-calling)时，它们包含在 [`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 中：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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#消息内容)中。

#### 令牌使用情况

[`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 可以在其 [`usage_metadata`](https://reference.langchain.com/javascript/langchain-core/messages/UsageMetadata) 字段中保存令牌计数和其他使用元数据：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { initChatModel } from "langchain";

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

const response = await model.invoke("Hello!");
console.log(response.usage_metadata);
```

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "output_tokens": 304,
  "input_tokens": 8,
  "total_tokens": 312,
  "input_token_details": {
    "cache_read": 0
  },
  "output_token_details": {
    "reasoning": 256
  }
}
```

详情请参阅 [`UsageMetadata`](https://reference.langchain.com/javascript/langchain-core/messages/UsageMetadata)。

#### 流式传输和分块

在流式传输期间，你将收到 [`AIMessageChunk`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessageChunk) 对象，这些对象可以组合成一个完整的消息对象：

<CodeGroup>
  ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import { AIMessageChunk } from "langchain";

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

<Note>
  了解更多：

  * [从聊天模型流式传输令牌](/oss/javascript/langchain/models#stream)
  * [从代理流式传输令牌和/或步骤](/oss/javascript/langchain/streaming)
</Note>

***

### 工具消息

对于支持[工具调用](/oss/javascript/langchain/models#tool-calling)的模型，AI 消息可以包含工具调用。工具消息用于将单个工具执行的结果传递回模型。

[工具](/oss/javascript/langchain/tools)可以直接生成 [`ToolMessage`](https://reference.langchain.com/javascript/langchain-core/messages/ToolMessage) 对象。下面，我们展示一个简单的例子。在[工具指南](/oss/javascript/langchain/tools)中阅读更多内容。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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);  // 模型处理结果
```

<Accordion title="属性">
  <ParamField path="content" type="string" required>
    工具调用的字符串化输出。
  </ParamField>

  <ParamField path="tool_call_id" type="string" required>
    此消息正在响应的工具调用的 ID。必须与 [`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 中工具调用的 ID 匹配。
  </ParamField>

  <ParamField path="name" type="string" required>
    被调用的工具的名称。
  </ParamField>

  <ParamField path="artifact" type="dict">
    未发送给模型但可通过编程方式访问的附加数据。
  </ParamField>
</Accordion>

<Note>
  `artifact` 字段存储不会发送给模型但可通过编程方式访问的补充数据。这对于存储原始结果、调试信息或用于下游处理的数据非常有用，而不会使模型的上下文变得混乱。

  <Accordion title="示例：使用 artifact 存储检索元数据">
    例如，一个[检索](/oss/javascript/langchain/retrieval)工具可以检索文档中的一段文字供模型参考。其中消息 `content` 包含模型将参考的文本，而 `artifact` 可以包含应用程序可以使用的文档标识符或其他元数据（例如，用于渲染页面）。参见下面的示例：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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 教程](/oss/javascript/langchain/rag)了解使用 LangChain 构建检索[代理](/oss/javascript/langchain/agents)的端到端示例。
  </Accordion>
</Note>

***

## 消息内容

你可以将消息的内容视为发送给模型的数据负载。消息有一个 `content` 属性，它是松散类型的，支持字符串和无类型对象（例如字典）的列表。这允许直接在 LangChain 聊天模型中支持提供商原生结构，例如[多模态](#多模态)内容和其他数据。

另外，LangChain 为文本、推理、引用、多模态数据、服务器端工具调用和其他消息内容提供了专用的内容类型。参见下面的[内容块](#标准内容块)。

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

这可能包含：

1. 一个字符串
2. 提供商原生格式的内容块列表
3. [LangChain 标准内容块](#标准内容块)的列表

参见下面使用[多模态](#多模态)输入的示例：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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`](/oss/javascript/integrations/chat/anthropic) 或 [`ChatOpenAI`](/oss/javascript/integrations/chat/openai) 生成的消息将包含各自提供商格式的 `thinking` 或 `reasoning` 块，但可以延迟解析为一致的 [`ReasoningContentBlock`](#内容块参考) 表示：

<Tabs>
  <Tab title="Anthropic">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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);
    ```
  </Tab>

  <Tab title="OpenAI">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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);
    ```
  </Tab>
</Tabs>

参见[集成指南](/oss/javascript/integrations/providers/overview)以开始使用你选择的推理提供商。

<Note>
  **序列化标准内容**

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

  为此，你可以将 `LC_OUTPUT_VERSION` 环境变量设置为 `v1`。或者，使用 `outputVersion: "v1"` 初始化任何聊天模型：

  ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import { initChatModel } from "langchain";

  const model = await initChatModel(
    "gpt-5-nano",
    { outputVersion: "v1" }
  );
  ```
</Note>

### 多模态

**多模态**是指处理以不同形式（如文本、音频、图像和视频）呈现的数据的能力。LangChain 包含这些数据的标准类型，可在所有提供商之间使用。

[聊天模型](/oss/javascript/langchain/models)可以接受多模态数据作为输入并生成多模态数据作为输出。下面我们展示包含多模态数据的输入消息的简短示例。

<Note>
  额外的键可以包含在内容块的顶层或嵌套在 `"extras": {"key": value}` 中。

  例如，[OpenAI](/oss/javascript/integrations/chat/openai) 和 [AWS Bedrock Converse](/oss/javascript/integrations/chat/bedrock) 要求 PDF 文件提供文件名。有关具体信息，请参阅你选择的模型的[提供商页面](/oss/javascript/integrations/providers/overview)。
</Note>

<CodeGroup>
  ```typescript 图像输入 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  // 来自 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" },
    ],
  });
  ```

  ```typescript PDF 文档输入 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  // 来自 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 音频输入 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  // 来自 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 视频输入 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  // 来自 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" },
    ],
  });
  ```
</CodeGroup>

<Warning>
  并非所有模型都支持所有文件类型。请检查模型提供商的[参考文档](https://reference.langchain.com/python/integrations/)以了解支持的格式和大小限制。
</Warning>

### 内容块参考

内容块（在创建消息或访问 `contentBlocks` 字段时）表示为类型化对象的列表。列表中的每个项目必须遵循以下块类型之一：

<AccordionGroup>
  <Accordion title="核心" icon="cube">
    <AccordionGroup>
      <Accordion title="ContentBlock.Text" icon="typography">
        **用途：** 标准文本输出

        <ParamField body="type" type="string" required>
          始终为 `"text"`
        </ParamField>

        <ParamField body="text" type="string" required>
          文本内容
        </ParamField>

        <ParamField body="annotations" type="Citation[]">
          文本的注释列表
        </ParamField>

        **示例：**

        ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
        {
            type: "text",
            text: "Hello world",
            annotations: []
        }
        ```
      </Accordion>

      <Accordion title="ContentBlock.Reasoning" icon="brain">
        **用途：** 模型推理步骤

        <ParamField body="type" type="string" required>
          始终为 `"reasoning"`
        </ParamField>

        <ParamField body="reasoning" type="string" required>
          推理内容
        </ParamField>

        **示例：**

        ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
        {
            type: "reasoning",
            reasoning: "The user is asking about..."
        }
        ```
      </Accordion>
    </AccordionGroup>
  </Accordion>

  <Accordion title="多模态" icon="photo">
    <AccordionGroup>
      <Accordion title="ContentBlock.Multimodal.Image" icon="photo">
        **用途：** 图像数据

        <ParamField body="type" type="string" required>
          始终为 `"image"`
        </ParamField>

        <ParamField body="url" type="string">
          指向图像位置的 URL。
        </ParamField>

        <ParamField body="data" type="string">
          Base64 编码的图像数据。
        </ParamField>

        <ParamField body="fileId" type="string">
          对外部文件存储系统（例如 OpenAI 或 Anthropic 的 Files API）中图像的引用。
        </ParamField>

        <ParamField body="mimeType" type="string">
          图像 [MIME 类型](https://www.iana.org/assignments/media-types/media-types.xhtml#image)（例如 `image/jpeg`、`image/png`）。对于 base64 数据是必需的。
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Multimodal.Audio" icon="volume">
        **用途：** 音频数据

        <ParamField body="type" type="string" required>
          始终为 `"audio"`
        </ParamField>

        <ParamField body="url" type="string">
          指向音频位置的 URL。
        </ParamField>

        <ParamField body="data" type="string">
          Base64 编码的音频数据。
        </ParamField>

        <ParamField body="fileId" type="string">
          对外部文件存储系统（例如 OpenAI 或 Anthropic 的 Files API）中音频文件的引用。
        </ParamField>

        <ParamField body="mimeType" type="string">
          音频 [MIME 类型](https://www.iana.org/assignments/media-types/media-types.xhtml#audio)（例如 `audio/mpeg`、`audio/wav`）。对于 base64 数据是必需的。
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Multimodal.Video" icon="video">
        **用途：** 视频数据

        <ParamField body="type" type="string" required>
          始终为 `"video"`
        </ParamField>

        <ParamField body="url" type="string">
          指向视频位置的 URL。
        </ParamField>

        <ParamField body="data" type="string">
          Base64 编码的视频数据。
        </ParamField>

        <ParamField body="fileId" type="string">
          对外部文件存储系统（例如 OpenAI 或 Anthropic 的 Files API）中视频文件的引用。
        </ParamField>

        <ParamField body="mimeType" type="string">
          视频 [MIME 类型](https://www.iana.org/assignments/media-types/media-types.xhtml#video)（例如 `video/mp4`、`video/webm`）。对于 base64 数据是必需的。
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Multimodal.File" icon="file">
        **用途：** 通用文件（PDF 等）

        <ParamField body="type" type="string" required>
          始终为 `"file"`
        </ParamField>

        <ParamField body="url" type="string">
          指向文件位置的 URL。
        </ParamField>

        <ParamField body="data" type="string">
          Base64 编码的文件数据。
        </ParamField>

        <ParamField body="fileId" type="string">
          对外部文件存储系统（例如 OpenAI 或 Anthropic 的 Files API）中文件的引用。
        </ParamField>

        <ParamField body="mimeType" type="string">
          文件 [MIME 类型](https://www.iana.org/assignments/media-types/media-types.xhtml)（例如 `application/pdf`）。对于 base64 数据是必需的。
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Multimodal.PlainText" icon="align-left">
        **用途：** 文档文本（`.txt`、`.md`）

        <ParamField body="type" type="string" required>
          始终为 `"text-plain"`
        </ParamField>

        <ParamField body="text" type="string" required>
          文本内容
        </ParamField>

        <ParamField body="title" type="string">
          文本内容的标题
        </ParamField>

        <ParamField body="mimeType" type="string">
          文本的 [MIME 类型](https://www.iana.org/assignments/media-types/media-types.xhtml)（例如 `text/plain`、`text/markdown`）
        </ParamField>
      </Accordion>
    </AccordionGroup>
  </Accordion>

  <Accordion title="工具调用" icon="tool">
    <AccordionGroup>
      <Accordion title="ContentBlock.Tools.ToolCall" icon="function">
        **用途：** 函数调用

        <ParamField body="type" type="string" required>
          始终为 `"tool_call"`
        </ParamField>

        <ParamField body="name" type="string" required>
          要调用的工具的名称
        </ParamField>

        <ParamField body="args" type="object" required>
          传递给工具的参数
        </ParamField>

        <ParamField body="id" type="string" required>
          此工具调用的唯一标识符
        </ParamField>

        **示例：**

        ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
        {
            type: "tool_call",
            name: "search",
            args: { query: "weather" },
            id: "call_123"
        }
        ```
      </Accordion>

      <Accordion title="ContentBlock.Tools.ToolCallChunk" icon="puzzle">
        **用途：** 流式工具片段

        <ParamField body="type" type="string" required>
          始终为 `"tool_call_chunk"`
        </ParamField>

        <ParamField body="name" type="string">
          正在调用的工具的名称
        </ParamField>

        <ParamField body="args" type="string">
          部分工具参数（可能是不完整的 JSON）
        </ParamField>

        <ParamField body="id" type="string">
          工具调用标识符
        </ParamField>

        <ParamField body="index" type="number | string" required>
          此分块在流中的位置
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Tools.InvalidToolCall" icon="alert-triangle">
        **用途：** 格式错误的调用

        <ParamField body="type" type="string" required>
          始终为 `"invalid_tool_call"`
        </ParamField>

        <ParamField body="name" type="string">
          未能调用的工具的名称
        </ParamField>

        <ParamField body="args" type="string">
          解析失败的原始参数
        </ParamField>

        <ParamField body="error" type="string" required>
          错误描述
        </ParamField>

        **常见错误：** 无效的 JSON，缺少必需字段
      </Accordion>
    </AccordionGroup>
  </Accordion>

  <Accordion title="服务器端工具执行" icon="server">
    <AccordionGroup>
      <Accordion title="ContentBlock.Tools.ServerToolCall" icon="tool">
        **用途：** 在服务器端执行的工具调用。

        <ParamField body="type" type="string" required>
          始终为 `"server_tool_call"`
        </ParamField>

        <ParamField body="id" type="string" required>
          与工具调用关联的标识符。
        </ParamField>

        <ParamField body="name" type="string" required>
          要调用的工具的名称。
        </ParamField>

        <ParamField body="args" type="string" required>
          部分工具参数（可能是不完整的 JSON）
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Tools.ServerToolCallChunk" icon="puzzle">
        **用途：** 流式服务器端工具调用片段

        <ParamField body="type" type="string" required>
          始终为 `"server_tool_call_chunk"`
        </ParamField>

        <ParamField body="id" type="string">
          与工具调用关联的标识符。
        </ParamField>

        <ParamField body="name" type="string">
          正在调用的工具的名称
        </ParamField>

        <ParamField body="args" type="string">
          部分工具参数（可能是不完整的 JSON）
        </ParamField>

        <ParamField body="index" type="number | string">
          此分块在流中的位置
        </ParamField>
      </Accordion>

      <Accordion title="ContentBlock.Tools.ServerToolResult" icon="package">
        **用途：** 搜索结果

        <ParamField body="type" type="string" required>
          始终为 `"server_tool_result"`
        </ParamField>

        <ParamField body="tool_call_id" type="string" required>
          对应服务器工具调用的标识符。
        </ParamField>

        <ParamField body="id" type="string">
          与服务器工具结果关联的标识符。
        </ParamField>

        <ParamField body="status" type="string" required>
          服务器端工具的执行状态。`"success"` 或 `"error"`。
        </ParamField>

        <ParamField body="output">
          执行工具的输出。
        </ParamField>
      </Accordion>
    </AccordionGroup>
  </Accordion>

  <Accordion title="提供商特定块" icon="plug">
    <Accordion title="ContentBlock.NonStandard" icon="asterisk">
      **用途：** 提供商特定的逃生舱口

      <ParamField body="type" type="string" required>
        始终为 `"non_standard"`
      </ParamField>

      <ParamField body="value" type="object" required>
        提供商特定的数据结构
      </ParamField>

      **用法：** 用于实验性或提供商独有的功能
    </Accordion>

    其他提供商特定的内容类型可以在每个模型提供商的[参考文档](/oss/javascript/integrations/providers/overview)中找到。
  </Accordion>
</AccordionGroup>

上述每个内容块在导入 [`ContentBlock`](https://reference.langchain.com/javascript/langchain-core/messages/ContentBlock) 类型时，都可以作为类型单独寻址。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 参考](https://reference.langchain.com/javascript/modules/_langchain_core.messages.html)中查看规范类型定义。
</Tip>

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

  内容块不是 [`content`](https://reference.langchain.com/javascript/langchain-core/messages/BaseMessage) 属性的替代品，而是一个新属性，可用于以标准化格式访问消息的内容。
</Info>

## 与聊天模型一起使用

[聊天模型](/oss/javascript/langchain/models)接受一系列消息对象作为输入，并返回一个 [`AIMessage`](https://reference.langchain.com/javascript/langchain-core/messages/AIMessage) 作为输出。交互通常是无状态的，因此一个简单的对话循环涉及使用不断增长的消息列表来调用模型。

参阅以下指南了解更多：

* 用于[持久化和管理对话历史](/oss/javascript/langchain/短时记忆)的内置功能
* 管理上下文窗口的策略，包括[修剪和总结消息](/oss/javascript/langchain/短时记忆#常见模式)

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/messages.mdx)或[提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
