> ## 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.

# MistralAI 集成

> 使用 LangChain JavaScript 与 MistralAI LLM 集成。

> [!WARNING]
>
> 您当前所在的页面正在记录 Mistral 模型作为文本完成模型的使用方法。Mistral 上提供的许多流行模型是 [对话完成模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。
>
> 您可能需要查找 [这个页面](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/chat/mistral.md)。

> [!TIP]
>
> **想要在本地运行 Mistral 的模型？查看我们的 [Ollama 集成](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/ollama.md)。**

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

这将帮助您使用 LangChain 开始使用 MistralAI 完成模型（LLM）。有关 `MistralAI` 功能和配置选项的详细文档，请参考 [API 参考](https://reference.langchain.com/javascript/langchain-mistralai/MistralAI)。

## 概述

### 集成详情

| 类 | 包 | 本地 | 可序列化 | PY 支持 | 下载 | 版本 |
| :- | :- | :-: | :-: | :-: | :-: | :-: |
| [`MistralAI`](https://reference.langchain.com/javascript/langchain-mistralai/MistralAI) | [`@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&) |

## 设置

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

### 凭证

前往 [console.mistral.ai](https://console.mistral.ai/) 注册 MistralAI 并生成 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 MistralAI 集成位于 `@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 { MistralAI } from "@langchain/mistralai"

const llm = new MistralAI({
  model: "codestral-latest",
  temperature: 0,
  maxTokens: undefined,
  maxRetries: 2,
  // other params...
})
```

## 调用

```typescript theme={null}
const inputText = "MistralAI is an AI company that "

const completion = await llm.invoke(inputText)
completion
```

```text theme={null}
 has developed Mistral 7B, a large language model (LLM) that is open-source and available for commercial use. Mistral 7B is a 7 billion parameter model that is trained on a diverse and high-quality dataset, and it has been fine-tuned to perform well on a variety of tasks, including text generation, question answering, and code interpretation.

MistralAI has made Mistral 7B available under a permissive license, allowing anyone to use the model for commercial purposes without having to pay any fees. This has made Mistral 7B a popular choice for businesses and organizations that want to leverage the power of large language models without incurring high costs.

Mistral 7B has been trained on a diverse and high-quality dataset, which has enabled it to perform well on a variety of tasks. It has been fine-tuned to generate coherent and contextually relevant text, and it has been shown to be capable of answering complex questions and interpreting code.

Mistral 7B is also a highly efficient model, capable of processing text at a fast pace. This makes it well-suited for applications that require real-time responses, such as chatbots and virtual assistants.

Overall, Mistral 7B is a powerful and versatile large language model that is open-source and available for commercial use. Its ability to perform well on a variety of tasks, its efficiency, and its permissive license make it a popular choice for businesses and organizations that want to leverage the power of large language models.
```

## 钩子

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 { MistralAI } from "@langchain/mistralai"

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

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

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

const model = new MistralAI({
    model: "codestral-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 参考

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

***

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


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