> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/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 [对话模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。有关所有 `ChatMistralAI` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/javascript/langchain-mistralai/ChatMistralAI)。

## 概述

### 集成详情

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

### 模型功能

请查看下表标题中的链接，了解如何使用特定功能。

| [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | [结构化输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md) | [图像输入](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态) | 音频输入 | 视频输入 | [Token 级流式输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/streaming.md) | [Token 使用情况](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#token-使用) | [Logprobs](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#对数概率) |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ |

## 设置

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

### 凭证

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

```bash theme={null}
export MISTRAL_API_KEY="your-api-key"
```

如果您希望自动跟踪您的模型调用，也可以通过取消注释以下内容来设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```bash theme={null}
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
```

### 安装

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

```bash npm theme={null}
npm install @langchain/mistralai @langchain/core
```

```bash yarn theme={null}
yarn add @langchain/mistralai @langchain/core
```

```bash pnpm theme={null}
pnpm add @langchain/mistralai @langchain/core
```

## 实例化

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

```typescript theme={null}
import { ChatMistralAI } from "@langchain/mistralai"

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

## 调用

当向 mistral 发送对话消息时，需要遵循以下要求：

* 第一个消息不能是助手（AI）消息。
* 消息必须交替为用户和助手（AI）消息。
* 消息不能以助手（AI）或系统消息结尾。

```typescript theme={null}
const aiMsg = await llm.invoke([
    [
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ],
    ["human", "I love programming."],
])
aiMsg
```

```text theme={null}
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={null}
console.log(aiMsg.content)
```

```text theme={null}
J'adore la programmation.
```

## 工具调用

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

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

```typescript theme={null}
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("The type of operation to execute."),
  number1: z.number().describe("The first number to operate on."),
  number2: z.number().describe("The second number to operate on."),
});

const calculatorTool = tool((input) => {
  return JSON.stringify(input);
}, {
  name: "calculator",
  description: "A simple calculator tool",
  schema: calculatorSchema,
});

// Bind the tool to the model
const modelWithTool = new ChatMistralAI({
  model: "mistral-large-latest",
}).bindTools([calculatorTool]);


const calcToolPrompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You are a helpful assistant who always needs to use a calculator.",
  ],
  ["human", "{input}"],
]);

// Chain your prompt, model, and output parser together
const chainWithCalcTool = calcToolPrompt.pipe(modelWithTool);

const calcToolRes = await chainWithCalcTool.invoke({
  input: "What is 2 + 2?",
});
console.log(calcToolRes.tool_calls);
```

```text theme={null}
[
  {
    name: 'calculator',
    args: { operation: 'add', number1: 2, number2: 2 },
    type: 'tool_call',
    id: 'DD9diCL1W'
  }
]
```

## 钩子

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

```typescript theme={null}
const beforeRequestHook = (req: Request): Request | void | Promise<Request | void> => {
    // Code to run before a request is processed by Mistral
};

const requestErrorHook = (err: unknown, req: Request): void | Promise<void> => {
    // Code to run when an error occurs as Mistral is processing a request
};

const responseHook = (res: Response, req: Request): void | Promise<void> => {
    // Code to run before Mistral sends a successful response
};
```

要将这些钩子添加到对话模型，可以直接作为参数传递，它们将自动添加：

```typescript theme={null}
import { ChatMistralAI } from "@langchain/mistralai"

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

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

```typescript theme={null}
import { ChatMistralAI } from "@langchain/mistralai"

const model = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    // other params...
});

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

model.addAllHooksToHttpClient();
```

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

可以逐个删除钩子，或者一次清除模型中的所有钩子。

```typescript theme={null}
model.removeHookFromHttpClient(beforeRequestHook);

model.removeAllHooksFromHttpClient();
```

***

## API 参考

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

***

> 官方原文：[src/oss/javascript/integrations/chat/mistral.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/chat/mistral.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.