ChatMistralAI
Mistral AI 是一个为其强大的开源模型提供托管的平台。
这将帮助你开始使用 ChatMistralAI 的聊天模型。有关所有 ChatMistralAI 功能和配置的详细文档,请参阅API 参考。
概述
集成详情
| 类 | 包 | 本地 | 可序列化 | Python 支持 | 包下载量 | 最新包 |
|---|---|---|---|---|---|---|
| ChatMistralAI | @langchain/mistralai | ❌ | ❌ | ✅ | ![]() | ![]() |
模型特性
请参阅下表标题中的链接,了解如何使用特定功能的指南。
| 工具调用 | 结构化输出 | JSON 模式 | 图像输入 | 音频输入 | 视频输入 | 逐 token 流式传输 | token 使用情况 | logprobs |
|---|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ |
准备
要访问 Mistral AI 模型,你需要创建一个 Mistral AI 账户,获取 API
密钥,并安装 @langchain/mistralai 集成包。
凭证
点击此处注册 Mistral AI 并生成一个 API
密钥。完成此操作后,请设置 MISTRAL_API_KEY 环境变量:
export MISTRAL_API_KEY="your-api-key"
如果你想对模型调用进行自动追踪,也可以取消注释以下 LangSmith API 密钥的设置:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
安装
LangChain ChatMistralAI 集成位于 @langchain/mistralai 包中:
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- yarn
- pnpm
npm i @langchain/mistralai @langchain/core
yarn add @langchain/mistralai @langchain/core
pnpm add @langchain/mistralai @langchain/core
实例化
现在我们可以实例化我们的模型对象并生成聊天补全结果:
import { ChatMistralAI } from "@langchain/mistralai";
const llm = new ChatMistralAI({
model: "mistral-large-latest",
temperature: 0,
maxRetries: 2,
// other params...
});
调用
向 Mistral 发送聊天消息时,需遵循以下要求:
- 第一条消息 不能 是助手(AI)消息。
- 消息 必须 在用户和助手(AI)之间交替发送。
- 消息 不能 以助手(AI)或系统消息结尾。
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;
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
}
}
console.log(aiMsg.content);
J'adore la programmation.
链式调用
我们可以像这样将模型与提示模板链式调用:
import { ChatPromptTemplate } from "@langchain/core/prompts";
const prompt = ChatPromptTemplate.fromMessages([
[
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
],
["human", "{input}"],
]);
const chain = prompt.pipe(llm);
await chain.invoke({
input_language: "English",
output_language: "German",
input: "I love programming.",
});
AIMessage {
"content": "Ich liebe Programmieren.",
"additional_kwargs": {},
"response_metadata": {
"tokenUsage": {
"completionTokens": 7,
"promptTokens": 21,
"totalTokens": 28
},
"finish_reason": "stop"
},
"tool_calls": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 21,
"output_tokens": 7,
"total_tokens": 28
}
}
工具调用
Mistral 的 API 为其部分模型支持工具调用功能。您可以通过此页面查看哪些模型支持工具调用。
以下示例演示了如何使用该功能:
import { ChatMistralAI } from "@langchain/mistralai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { 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);
[
{
name: 'calculator',
args: { operation: 'add', number1: 2, number2: 2 },
type: 'tool_call',
id: 'DD9diCL1W'
}
]
钩子函数
Mistral AI 支持三种事件的自定义钩子函数:beforeRequest(请求前)、requestError(请求错误)和 response(响应)。每种钩子函数类型的函数签名示例如下所示:
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
};
将这些钩子添加到聊天模型中,可以通过将它们作为参数传递来自动添加:
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...
});
或者在实例化后分配并手动添加它们:
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 在分配完整的更新后的钩子列表之前,会清除所有当前已添加的钩子,以避免钩子重复。
可以逐个移除钩子,也可以一次性从模型中清除所有钩子。
model.removeHookFromHttpClient(beforeRequestHook);
model.removeAllHooksFromHttpClient();
API 参考
有关 ChatMistralAI 所有功能和配置的详细文档,请访问 API 参考:https://api.js.langchain.com/classes/langchain_mistralai.ChatMistralAI.html
Related
- Chat model conceptual guide
- Chat model how-to guides

