跳到主要内容

Mistral AI 聊天

DeepSeek V3 中英对照 Mistral AI Mistral AI Chat

Spring AI 支持来自 Mistral AI 的各种 AI 语言模型。你可以与 Mistral AI 语言模型进行交互,并基于 Mistral 模型创建一个多语言对话助手。

提示

Mistral AI 也提供了一个与 OpenAI API 兼容的端点。查看 OpenAI API 兼容性 部分,了解如何使用 Spring AI OpenAI 集成与 Mistral 端点进行通信。

先决条件

你需要创建一个与 Mistral AI 的 API 来访问 Mistral AI 的语言模型。请在 Mistral AI 注册页面 创建一个账户,并在 API Keys 页面 生成 token。Spring AI 项目定义了一个名为 spring.ai.mistralai.api-key 的配置属性,你应该将其设置为从 console.mistral.ai 获取的 API Key 的值。导出环境变量是设置该配置属性的一种方式:

export SPRING_AI_MISTRALAI_API_KEY=<INSERT KEY HERE>
shell

添加仓库和 BOM

Spring AI 构件已发布在 Maven Central 和 Spring Snapshot 仓库中。请参考 仓库 部分,将这些仓库添加到您的构建系统中。

为了帮助进行依赖管理,Spring AI 提供了一个 BOM(物料清单)以确保在整个项目中使用一致版本的 Spring AI。请参考 依赖管理 部分,将 Spring AI BOM 添加到你的构建系统中。

自动配置

Spring AI 提供了针对 Mistral AI 聊天客户端的 Spring Boot 自动配置。要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中:

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mistral-ai-spring-boot-starter</artifactId>
</dependency>
xml

或者到你的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-mistral-ai-spring-boot-starter'
}
groovy

:::提示
请参考依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。
:::

聊天属性

重试属性

前缀 spring.ai.retry 用作属性前缀,允许你为 Mistral AI 聊天模型配置重试机制。

属性描述默认值
spring.ai.retry.max-attempts最大重试次数。10
spring.ai.retry.backoff.initial-interval指数退避策略的初始休眠时间。2 秒
spring.ai.retry.backoff.multiplier退避间隔乘数。5
spring.ai.retry.backoff.max-interval最大退避时间。3 分钟
spring.ai.retry.on-client-errors如果为 false,抛出 NonTransientAiException,并且不对 4xx 客户端错误代码进行重试。false
spring.ai.retry.exclude-on-http-codes不应触发重试的 HTTP 状态码列表(例如,抛出 NonTransientAiException)。
spring.ai.retry.on-http-codes应触发重试的 HTTP 状态码列表(例如,抛出 TransientAiException)。

连接属性

前缀 spring.ai.mistralai 用作属性前缀,允许你连接到 OpenAI。

属性描述默认值
spring.ai.mistralai.base-url连接的 URLapi.mistral.ai
spring.ai.mistralai.api-keyAPI 密钥-

配置属性

前缀 spring.ai.mistralai.chat 是一个属性前缀,允许你为 Mistral AI 配置聊天模型实现。

属性描述默认值
spring.ai.mistralai.chat.enabled启用 Mistral AI 聊天模型。true
spring.ai.mistralai.chat.base-url可选覆盖 spring.ai.mistralai.base-url 属性,以提供特定于聊天的 URL。-
spring.ai.mistralai.chat.api-key可选覆盖 spring.ai.mistralai.api-key,以提供特定于聊天的 API 密钥。-
spring.ai.mistralai.chat.options.model这是要使用的 Mistral AI 聊天模型open-mistral-7b, open-mixtral-8x7b, open-mixtral-8x22b, mistral-small-latest, mistral-large-latest
spring.ai.mistralai.chat.options.temperature用于控制生成完成项的明显创造性的采样温度。较高的值将使输出更加随机,而较低的值将使结果更加集中和确定性。不建议在同一完成请求中同时修改 temperaturetop_p,因为这两个设置的交互难以预测。0.8
spring.ai.mistralai.chat.options.maxTokens在聊天完成中生成的最大 token 数。输入 token 和生成 token 的总长度受模型上下文长度的限制。-
spring.ai.mistralai.chat.options.safePrompt指示是否在所有对话之前注入安全提示。false
spring.ai.mistralai.chat.options.randomSeed此功能处于 Beta 阶段。如果指定,我们的系统将尽最大努力进行确定性采样,以便使用相同种子和参数的重复请求应返回相同的结果。-
spring.ai.mistralai.chat.options.stop如果检测到此 token,则停止生成。或者在提供数组时检测到其中一个 token 时停止生成。-
spring.ai.mistralai.chat.options.topP一种替代温度采样的方法,称为核心采样,其中模型考虑具有 top_p 概率质量的 token 结果。因此,0.1 意味着只考虑构成前 10% 概率质量的 token。我们通常建议修改此值或 temperature,但不要同时修改两者。-
spring.ai.mistralai.chat.options.responseFormat指定模型必须输出的格式的对象。设置为 { "type": "json_object" } 启用 JSON 模式,该模式保证模型生成的消息是有效的 JSON。-
spring.ai.mistralai.chat.options.tools模型可以调用的工具列表。目前,仅支持函数作为工具。使用此选项提供模型可以生成 JSON 输入的函数列表。-
spring.ai.mistralai.chat.options.toolChoice控制模型调用哪个(如果有)函数。none 表示模型不会调用函数,而是生成消息。auto 表示模型可以选择生成消息或调用函数。通过 {"type: "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。none 是未提供函数时的默认值。auto 是提供函数时的默认值。-
spring.ai.mistralai.chat.options.functions函数名称列表,用于在单个提示请求中启用函数调用。具有这些名称的函数必须存在于 functionCallbacks 注册表中。-
spring.ai.mistralai.chat.options.functionCallbacks要注册到 ChatModel 的 Mistral AI 工具函数回调。-
spring.ai.mistralai.chat.options.proxy-tool-calls如果为 true,Spring AI 不会在内部处理函数调用,而是将其代理给客户端。然后由客户端负责处理函数调用,将其分派给适当的函数并返回结果。如果为 false(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型false
备注

你可以为 ChatModelEmbeddingModel 实现覆盖通用的 spring.ai.mistralai.base-urlspring.ai.mistralai.api-key。如果设置了 spring.ai.mistralai.chat.base-urlspring.ai.mistralai.chat.api-key 属性,它们将优先于通用属性。这在你想为不同模型和不同模型端点使用不同的 Mistral AI 账户时非常有用。

提示

所有以 spring.ai.mistralai.chat.options 为前缀的属性都可以在运行时通过向 Prompt 调用添加请求特定的运行时选项来覆盖。

运行时选项

MistralAiChatOptions.java 提供了模型配置,例如要使用的模型、温度(temperature)、频率惩罚(frequency penalty)等。

在启动时,默认选项可以通过 MistralAiChatModel(api, options) 构造函数或 spring.ai.mistralai.chat.options.* 属性进行配置。

在运行时,你可以通过在 Prompt 调用中添加新的、特定于请求的选项来覆盖默认选项。例如,要为特定请求覆盖默认模型和温度参数:

ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
MistralAiChatOptions.builder()
.model(MistralAiApi.ChatModel.LARGE.getValue())
.temperature(0.5)
.build()
));
java
提示

除了特定于模型的 MistralAiChatOptions,你还可以使用一个可移植的 ChatOptions 实例,该实例通过 ChatOptionsBuilder#builder() 创建。

函数调用

你可以向 MistralAiChatModel 注册自定义的 Java 函数,并让 Mistral AI 模型智能地选择输出一个包含参数的 JSON 对象,以调用一个或多个已注册的函数。这是一种将大语言模型(LLM)能力与外部工具和 API 连接起来的强大技术。了解更多关于 Mistral AI 函数调用 的信息。

多模态

多模态(Multimodality)指的是模型能够同时理解和处理来自多种来源的信息,包括文本、图像、音频和其他数据格式。Mistral AI 支持文本和视觉模态。

愿景

提供视觉多模态支持的 Mistral AI 模型包括 pixtral-large-latest。更多信息请参考 Vision 指南。

Mistral AI 的 用户消息 API 可以将一组 base64 编码的图像或图像 URL 与消息结合使用。Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 AI 模型。该类型包含了消息中媒体附件的数据和详细信息,并使用了 Spring 的 org.springframework.util.MimeTypeorg.springframework.core.io.Resource 来处理原始媒体数据。

以下是摘自 MistralAiChatModelIT.java 的代码示例,展示了用户文本与图像的融合。

var imageResource = new ClassPathResource("/multimodal.test.png");

var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG, this.imageResource));

ChatResponse response = chatModel.call(new Prompt(this.userMessage,
ChatOptions.builder().model(MistralAiApi.ChatModel.PIXTRAL_LARGE.getValue()).build()));
java

或图像 URL 等价于:

var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG,
"https://docs.spring.io/spring-ai/reference/_images/multimodal.test.png"));

ChatResponse response = chatModel.call(new Prompt(this.userMessage,
ChatOptions.builder().model(MistralAiApi.ChatModel.PIXTRAL_LARGE.getValue()).build()));
java
提示

你也可以传递多张图片。

该示例展示了一个模型将 multimodal.test.png 图像作为输入:

多模态测试图像

伴随着文本消息“解释一下你在这张图片上看到了什么?”,并生成如下响应:

This is an image of a fruit bowl with a simple design. The bowl is made of metal with curved wire edges that
create an open structure, allowing the fruit to be visible from all angles. Inside the bowl, there are two
yellow bananas resting on top of what appears to be a red apple. The bananas are slightly overripe, as
indicated by the brown spots on their peels. The bowl has a metal ring at the top, likely to serve as a handle
for carrying. The bowl is placed on a flat surface with a neutral-colored background that provides a clear
view of the fruit inside.

OpenAI API 兼容性

Mistral 与 OpenAI API 兼容,你可以使用 Spring AI OpenAI 客户端与 Mistral 进行交互。为此,你需要将 OpenAI 的基础 URL 配置为 Mistral AI 平台:spring.ai.openai.chat.base-url=https://api.mistral.ai,并选择一个 Mistral 模型:spring.ai.openai.chat.options.model=mistral-small-latest,然后设置 Mistral AI API 密钥:spring.ai.openai.chat.api-key=<你的 Mistral API 密钥>

查看 MistralWithOpenAiChatModelIT.java 测试,了解如何在 Spring AI OpenAI 上使用 Mistral 的示例。

示例控制器(自动配置)

创建 一个新的 Spring Boot 项目,并将 spring-ai-mistral-ai-spring-boot-starter 添加到你的 pom(或 gradle)依赖中。

src/main/resources 目录下添加一个 application.properties 文件,以启用并配置 Mistral AI 聊天模型:

spring.ai.mistralai.api-key=YOUR_API_KEY
spring.ai.mistralai.chat.options.model=mistral-small
spring.ai.mistralai.chat.options.temperature=0.7
application.properties
提示

api-key 替换为你的 Mistral AI 凭证。

这将创建一个 MistralAiChatModel 实现,你可以将其注入到你的类中。以下是一个简单的 @RestController 类的示例,它使用聊天模型进行文本生成。

@RestController
public class ChatController {

private final MistralAiChatModel chatModel;

@Autowired
public ChatController(MistralAiChatModel chatModel) {
this.chatModel = chatModel;
}

@GetMapping("/ai/generate")
public Map<String,String> generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return Map.of("generation", this.chatModel.call(message));
}

@GetMapping("/ai/generateStream")
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
var prompt = new Prompt(new UserMessage(message));
return this.chatModel.stream(prompt);
}
}
java

手动配置

MistralAiChatModel 实现了 ChatModelStreamingChatModel 接口,并使用 Low-level MistralAiApi Client 连接到 Mistral AI 服务。

spring-ai-mistral-ai 依赖添加到你的项目 Maven pom.xml 文件中:

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mistral-ai</artifactId>
</dependency>
xml

或添加到你的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-mistral-ai'
}
groovy
提示

请参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。

接下来,创建一个 MistralAiChatModel 并使用它进行文本生成:

var mistralAiApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY"));

var chatModel = new MistralAiChatModel(this.mistralAiApi, MistralAiChatOptions.builder()
.model(MistralAiApi.ChatModel.LARGE.getValue())
.temperature(0.4)
.maxTokens(200)
.build());

ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = this.chatModel.stream(
new Prompt("Generate the names of 5 famous pirates."));
java

MistralAiChatOptions 提供了聊天请求的配置信息。MistralAiChatOptions.Builder 是一个流畅的选项构建器。

低级别 MistralAiApi 客户端

MistralAiApi 提供了一个轻量级的 Java 客户端,用于访问 Mistral AI API

以下是一个简单的代码片段,展示了如何以编程方式使用 API:

import requests

# 定义 API 的 URL
url = "https://api.example.com/data"

# 发送 GET 请求
response = requests.get(url)

# 检查请求是否成功
if response.status_code == 200:
# 解析 JSON 响应
data = response.json()
print(data)
else:
print(f"请求失败,状态码: {response.status_code}")
python

这个示例展示了如何使用 requests 库发送一个 GET 请求到 API,并处理返回的 JSON 数据。

MistralAiApi mistralAiApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY"));

ChatCompletionMessage chatCompletionMessage =
new ChatCompletionMessage("Hello world", Role.USER);

// Sync request
ResponseEntity<ChatCompletion> response = this.mistralAiApi.chatCompletionEntity(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8, false));

// Streaming request
Flux<ChatCompletionChunk> streamResponse = this.mistralAiApi.chatCompletionStream(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8, true));
java

请参考 MistralAiApi.java 的 JavaDoc 以获取更多信息。

MistralAiApi 示例

章节摘要