ChatMistralAI
Mistral AI 是一个为其强大的 开源模型 提供托管的平台。
这将帮助您开始使用 ChatMistralAI 聊天模型。有关所有 ChatMistralAI 功能和配置的详细文档,请访问 API 参考。
概述
集成细节
类 | 包 | 本地 | 可序列化 | PY 支持 | 包下载量 | 包最新版本 |
---|---|---|---|---|---|---|
ChatMistralAI | @langchain/mistralai | ❌ | ❌ | ✅ | ![]() | ![]() |
模型特性
请参阅下表标题中的链接,以获取有关如何使用特定功能的指南。
工具调用 | 结构化输出 | JSON 模式 | 图像输入 | 音频输入 | 视频输入 | 令牌级流式传输 | 令牌使用量 | 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 和 reponse。以下是每个钩子类型的功能签名的示例
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