Mistral AI 是一个平台,提供其强大的 开源模型.
这将帮助您开始使用 Mistral 聊天模型。有关所有 ChatMistralAI 功能和配置的详细文档,请参阅 API 参考.
概述
集成详情
| 类 | 包 | 可序列化 | PY 支持 | 下载量 | 版本 |
|---|---|---|---|---|---|
ChatMistralAI | @langchain/mistralai | ❌ | ✅ | !NPM - 下载量 | !NPM - 版本 |
模型特性
请参阅下表标题中的链接,了解如何使用特定功能。
| 工具调用 | 结构化输出 | 图像输入 | 音频输入 | 视频输入 | 令牌级流式处理 | 令牌使用量 | 对数概率 |
|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ |
设置
要访问 Mistral AI 模型,您需要创建一个 Mistral AI 账户,获取 API 密钥,并安装 @langchain/mistralai 集成包。
凭证
访问 Mistral 控制台 注册并生成 API 密钥。完成此操作后,设置 MISTRAL_API_KEY 环境变量:
如果您想获取模型调用的自动追踪,您还可以设置您的 LangSmith API 密钥,方法是取消注释以下内容:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
安装
LangChain ChatMistralAI 集成位于 @langchain/mistralai package:
npm install @langchain/mistralai @langchain/core
yarn add @langchain/mistralai @langchain/core
pnpm add @langchain/mistralai @langchain/core
实例化
现在我们可以实例化模型对象并生成聊天补全:
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.
工具调用
Mistral 的 API 支持 工具调用 用于其部分模型。您可以在此查看哪些模型支持工具调用 的详细说明.
以下示例演示了如何使用它:
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 => {
// 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
};
要向聊天模型添加这些钩子,可以将它们作为参数传入,它们会自动被添加:
const modelWithHooks = new ChatMistralAI({
model: "mistral-large-latest",
temperature: 0,
maxRetries: 2,
beforeRequestHooks: [ beforeRequestHook ],
requestErrorHooks: [ requestErrorHook ],
responseHooks: [ responseHook ],
// other params...
});
或者在实例化后手动分配和添加它们:
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 参考.