跳到主要内容

Mistral AI 聊天

Deepseek 3.2 中英对照 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 密钥页面生成令牌。

Spring AI 项目定义了一个名为 spring.ai.mistralai.api-key 的配置属性,您应将其设置为从 console.mistral.ai 获取的 API Key 的值。

你可以在 application.properties 文件中设置此配置属性:

spring.ai.mistralai.api-key=<your-mistralai-api-key>

为了在处理敏感信息(如API密钥)时提升安全性,您可以使用Spring表达式语言(SpEL)来引用自定义环境变量:

# In application.yml
spring:
ai:
mistralai:
api-key: ${MISTRALAI_API_KEY}
# In your environment or .env file
export MISTRALAI_API_KEY=<your-mistralai-api-key>

您也可以在应用程序代码中通过编程方式设置此配置:

// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("MISTRALAI_API_KEY");

添加仓库和物料清单(BOM)

Spring AI 制品已发布至 Maven Central 和 Spring Snapshot 仓库。请参阅 制品仓库 章节,将这些仓库添加到您的构建系统中。

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

自动配置

备注

Spring AI 的自动配置和 starter 模块的 artifact 名称有重大变更。更多信息请参阅升级说明

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

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

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

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

请参考 依赖管理 部分,将 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,对于 4xx 客户端错误码,则抛出 NonTransientAiException 且不尝试重试。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.model.chat 的顶级属性进行配置。

启用方式:spring.ai.model.chat=mistral(默认已启用)

禁用方式:spring.ai.model.chat=none(或任何不匹配 mistral 的值)

此项变更是为了支持配置多个模型。

前缀 spring.ai.mistralai.chat 是用于配置 Mistral AI 聊天模型实现的属性前缀。

属性描述默认
spring.ai.mistralai.chat.enabled(已移除且不再有效)启用 Mistral AI 聊天模型。正确
spring.ai.model.chat启用 Mistral AI 聊天模型。米斯特拉尔
spring.ai.mistralai.chat.base-urlspring.ai.mistralai.base-url 属性的可选覆盖,用于提供聊天专用的 URL。-
spring.ai.mistralai.chat.api-keyspring.ai.mistralai.api-key 的可选覆盖项,用于提供特定于聊天的 API 密钥。-
spring.ai.mistralai.chat.options.model这是Mistral AI Chat模型的使用说明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聊天完成中生成的最大令牌数。输入令牌和生成令牌的总长度受模型上下文长度的限制。-
spring.ai.mistralai.chat.options.safePrompt指示是否在所有对话前注入安全提示。false
spring.ai.mistralai.chat.options.randomSeed此功能处于测试阶段。如果指定了种子,我们的系统将尽力进行确定性采样,使得使用相同种子和参数的重复请求应返回相同的结果。-
spring.ai.mistralai.chat.options.stop如果检测到此令牌,则停止生成。或者当提供数组时,如果检测到这些令牌之一。-
spring.ai.mistralai.chat.options.topP作为温度采样的替代方案,还有一种称为核心采样的方法,即模型仅考虑概率质量累计达到 top_p 阈值的候选词元。例如设置为 0.1 时,仅会考虑构成概率质量前 10% 的词元。我们通常建议调整此参数或 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.tool-names工具列表,以其名称标识,用于在单个提示请求中启用函数调用。这些名称对应的工具必须存在于ToolCallback注册表中。-
spring.ai.mistralai.chat.options.tool-callbacks要注册到 ChatModel 中的工具回调。-
spring.ai.mistralai.chat.options.internal-tool-execution-enabled如果为 false,Spring AI 将不会在内部处理工具调用,而是将其代理给客户端。此时客户端需负责处理工具调用、将其分派至相应函数并返回结果。如果为 true(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。true
备注

你可以为 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 提供了模型的配置选项,例如使用的模型、温度参数、频率惩罚等。

启动时,可通过 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()
));
提示

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

函数调用

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

多模态

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

愿景

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

Mistral AI 的用户消息 API 能够在消息中整合一组 base64 编码的图像或图像 URL。Spring AI 的消息接口通过引入媒体类型,为多模态 AI 模型提供了便利。此类型包含了消息中媒体附件的数据和详细信息,它利用 Spring 的 org.springframework.util.MimeType 和一个用于原始媒体数据的 org.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()));

或图像URL的等价形式:

var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG,
URI.create("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()));
提示

你也可以传入多张图片。

该示例展示了一个以 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=<YOUR MISTRAL API KEY>

请查看 MistralWithOpenAiChatModelIT.java 测试以获取在 Spring AI OpenAI 上使用 Mistral 的示例。

示例控制器(自动配置)

创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-mistral-ai 添加到你的 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
提示

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);
}
}

手动配置

MistralAiChatModel 实现了 ChatModelStreamingChatModel,并使用 MistralAiApi 低级客户端 连接到 Mistral AI 服务。

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

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

或将其添加到您的 Gradle build.gradle 构建文件中。

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

:::提示
请参考依赖管理章节,将 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."));

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

低级 MistralAiApi 客户端

MistralAiApiMistral AI API 提供了一个轻量级的 Java 客户端。

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

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));

有关更多信息,请参阅 MistralAiApi.java 的 JavaDoc。

MistralAiApi 示例

Mistral AI OCR

Spring AI 支持通过 Mistral AI 进行光学字符识别(OCR)。这使您能够从文档中提取文本和图像数据。

先决条件

您需要创建一个Mistral AI API来访问Mistral AI语言模型。请在Mistral AI注册页面创建账户,并在API密钥页面生成令牌。

添加依赖项

要使用 Mistral AI OCR API,您需要在项目中添加 spring-ai-mistral-ai 依赖。

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

或将其添加到您的 Gradle build.gradle 构建文件中。

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

低级 MistralOcrApi 客户端

MistralOcrApiMistral AI OCR API 提供了一个轻量级的 Java 客户端。

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

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

String documentUrl = "https://arxiv.org/pdf/2201.04234";
MistralOcrApi.OCRRequest request = new MistralOcrApi.OCRRequest(
MistralOcrApi.OCRModel.MISTRAL_OCR_LATEST.getValue(), "test_id",
new MistralOcrApi.OCRRequest.DocumentURLChunk(documentUrl), List.of(0, 1, 2), true, 5, 50);

ResponseEntity<MistralOcrApi.OCRResponse> response = mistralAiApi.ocr(request);

有关更多信息,请参考 MistralOcrApi.java 的 JavaDoc。

MistralOcrApi 示例