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

# ChatMistralAI 集成

> 使用 LangChain JavaScript 集成 ChatMistralAI 聊天模型。

[Mistral AI](https://mistral.ai/) 是一个提供其强大[开源模型](https://docs.mistral.ai/getting-started/models/)托管服务的平台。

本文将帮助您开始使用 Mistral [聊天模型](/oss/javascript/langchain/models)。有关 `ChatMistralAI` 所有功能和配置的详细文档，请参阅 [API 参考](https://reference.langchain.com/javascript/langchain-mistralai/ChatMistralAI)。

## 概述

### 集成详情

| 类                                                                                               | 包                                                                            | 可序列化 | [Python 支持](https://python.langchain.com/docs/integrations/chat/mistralai) |                                                  下载量                                                 |                                                 版本                                                |
| :---------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- | :--: | :------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------: |
| [`ChatMistralAI`](https://reference.langchain.com/javascript/langchain-mistralai/ChatMistralAI) | [`@langchain/mistralai`](https://www.npmjs.com/package/@langchain/mistralai) |   ❌  |                                      ✅                                     | ![NPM - Downloads](https://img.shields.io/npm/dm/@langchain/mistralai?style=flat-square\&label=%20&) | ![NPM - Version](https://img.shields.io/npm/v/@langchain/mistralai?style=flat-square\&label=%20&) |

### 模型特性

下表标题中的链接提供了如何使用特定功能的指南。

| [工具调用](/oss/javascript/langchain/tools) | [结构化输出](/oss/javascript/langchain/structured-output) | [图像输入](/oss/javascript/langchain/messages#multimodal) | 音频输入 | 视频输入 | [令牌级流式传输](/oss/javascript/langchain/streaming/) | [令牌使用量](/oss/javascript/langchain/models#token-usage) | [对数概率](/oss/javascript/langchain/models#log-probabilities) |
| :-------------------------------------: | :--------------------------------------------------: | :---------------------------------------------------: | :--: | :--: | :---------------------------------------------: | :---------------------------------------------------: | :--------------------------------------------------------: |
|                    ✅                    |                           ✅                          |                           ✅                           |   ❌  |   ❌  |                        ✅                        |                           ✅                           |                              ❌                             |

## 设置

要访问 Mistral AI 模型，您需要创建一个 Mistral AI 账户，获取 API 密钥，并安装 `@langchain/mistralai` 集成包。

### 凭证

访问 [Mistral 控制台](https://console.mistral.ai/) 注册并生成 API 密钥。完成后，设置 `MISTRAL_API_KEY` 环境变量：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export MISTRAL_API_KEY="your-api-key"
```

如果您希望自动追踪模型调用，还可以通过取消注释以下行来设置 [LangSmith](/langsmith/home) API 密钥：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
```

### 安装

LangChain ChatMistralAI 集成位于 `@langchain/mistralai` 包中：

<CodeGroup>
  ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  npm install @langchain/mistralai @langchain/core
  ```

  ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/mistralai @langchain/core
  ```

  ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pnpm add @langchain/mistralai @langchain/core
  ```
</CodeGroup>

## 实例化

现在我们可以实例化模型对象并生成聊天补全：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatMistralAI } from "@langchain/mistralai"

const llm = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    // 其他参数...
})
```

## 调用

向 Mistral 发送聊天消息时，需要遵循以下要求：

* 第一条消息 **不能** 是助手（ai）消息。
* 消息 **必须** 在用户和助手（ai）消息之间交替。
* 消息 **不能** 以助手（ai）或系统消息结尾。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const aiMsg = await llm.invoke([
    [
        "system",
        "你是一个将英语翻译成法语的助手。请翻译用户的句子。",
    ],
    ["human", "I love programming."],
])
aiMsg
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
AIMessage {
  "content": "J'adore la programmation.",
  "additional_kwargs": {},
  "response_metadata": {
    "tokenUsage": {
      "completionTokens": 9,
      "promptTokens": 27,
      "totalTokens": 36
    },
    "finish_reason": "stop"
  },
  "tool_calls": [],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 27,
    "output_tokens": 9,
    "total_tokens": 36
  }
}
```

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
console.log(aiMsg.content)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
J'adore la programmation.
```

## 工具调用

Mistral 的 API 支持其部分模型的[工具调用](/oss/javascript/langchain/tools)。您可以在[此页面](https://docs.mistral.ai/capabilities/function_calling/)查看哪些模型支持工具调用。

以下示例演示了如何使用它：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatMistralAI } from "@langchain/mistralai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import * as z from "zod";
import { tool } from "@langchain/core/tools";

const calculatorSchema = z.object({
  operation: z
    .enum(["add", "subtract", "multiply", "divide"])
    .describe("要执行的操作类型。"),
  number1: z.number().describe("要操作的第一个数字。"),
  number2: z.number().describe("要操作的第二个数字。"),
});

const calculatorTool = tool((input) => {
  return JSON.stringify(input);
}, {
  name: "calculator",
  description: "一个简单的计算器工具",
  schema: calculatorSchema,
});

// 将工具绑定到模型
const modelWithTool = new ChatMistralAI({
  model: "mistral-large-latest",
}).bindTools([calculatorTool]);


const calcToolPrompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "你是一个总是需要使用计算器的助手。",
  ],
  ["human", "{input}"],
]);

// 将提示、模型和输出解析器链接在一起
const chainWithCalcTool = calcToolPrompt.pipe(modelWithTool);

const calcToolRes = await chainWithCalcTool.invoke({
  input: "2 + 2 等于多少？",
});
console.log(calcToolRes.tool_calls);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[
  {
    name: 'calculator',
    args: { operation: 'add', number1: 2, number2: 2 },
    type: 'tool_call',
    id: 'DD9diCL1W'
  }
]
```

## 钩子

Mistral AI 支持三个事件的自定义钩子：beforeRequest、requestError 和 response。每种钩子类型的函数签名示例如下：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const beforeRequestHook = (req: Request): Request | void | Promise<Request | void> => {
    // 在 Mistral 处理请求之前运行的代码
};

const requestErrorHook = (err: unknown, req: Request): void | Promise<void> => {
    // 当 Mistral 处理请求时发生错误时运行的代码
};

const responseHook = (res: Response, req: Request): void | Promise<void> => {
    // 在 Mistral 发送成功响应之前运行的代码
};
```

要将这些钩子添加到聊天模型中，可以将它们作为参数传递，它们会自动添加：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatMistralAI } from "@langchain/mistralai"

const modelWithHooks = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    beforeRequestHooks: [ beforeRequestHook ],
    requestErrorHooks: [ requestErrorHook ],
    responseHooks: [ responseHook ],
    // 其他参数...
});
```

或者在实例化后手动分配和添加它们：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatMistralAI } from "@langchain/mistralai"

const model = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    // 其他参数...
});

model.beforeRequestHooks = [ ...model.beforeRequestHooks, beforeRequestHook ];
model.requestErrorHooks = [ ...model.requestErrorHooks, requestErrorHook ];
model.responseHooks = [ ...model.responseHooks, responseHook ];

model.addAllHooksToHttpClient();
```

`addAllHooksToHttpClient` 方法会清除所有当前添加的钩子，然后分配整个更新后的钩子列表，以避免钩子重复。

可以逐个移除钩子，也可以一次性清除模型中的所有钩子。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
model.removeHookFromHttpClient(beforeRequestHook);

model.removeAllHooksFromHttpClient();
```

***

## API 参考

有关 `ChatMistralAI` 所有功能和配置的详细文档，请参阅 [API 参考](https://reference.langchain.com/javascript/langchain-mistralai/ChatMistralAI)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\javascript\integrations\chat\mistral.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
