跳到主要内容
Mistral AI 是一个平台,为他们强大的开源模型提供托管。 这将帮助您开始使用 ChatMistralAI 聊天模型。有关所有 ChatMistralAI 功能和配置的详细文档,请参阅API 参考

概览

集成详情

类别本地可序列化PY 支持下载量版本
ChatMistralAI@langchain/mistralaiNPM - DownloadsNPM - Version

模型功能

有关如何使用特定功能的指南,请参阅下表标题中的链接。
工具调用结构化输出JSON 模式图像输入音频输入视频输入令牌级流式传输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 install @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.

工具调用

Mistral 的 API 支持对其部分模型进行工具调用。您可以在此页面上查看哪些模型支持工具调用。 以下示例演示了如何使用它:
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);
[
  {
    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 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.