跳到主要内容
版本:2.0.1

Mistral AI Chat

QWen 3.8 中英对照 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 页面生成令牌。

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 Expression Language (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 仓库中。请参见 Artifact Repositories 部分,以将这些仓库添加到您的构建系统中。

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

自动配置​

备注

Spring AI 自动配置及 starter 模块的 artifact 名称发生了重大变更。请参阅 升级说明 以获取更多信息。

Spring AI 为 Mistral AI Chat Client 提供了 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,则抛出 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 Key-

配置属性​

备注

现在,聊天自动配置的启用和禁用通过前缀为 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 聊天模型。true
spring.ai.model.chat启用 Mistral AI 聊天模型。mistral
spring.ai.mistralai.chat.base-url用于提供聊天特定 URL 的 spring.ai.mistralai.base-url 属性的可选覆盖项。-
spring.ai.mistralai.chat.api-key用于提供聊天特定 API Key 的 spring.ai.mistralai.api-key 的可选覆盖项。-
spring.ai.mistralai.chat.model这是要使用的 Mistral AI 聊天模型。open-mistral-7b、open-mixtral-8x7b、open-mixtral-8x22b、mistral-small-latest、mistral-large-latest
spring.ai.mistralai.chat.temperature用于控制生成补全内容创意程度的采样温度。较高的值会使输出更随机,而较低的值会使结果更集中且更具确定性。不建议对同一个补全请求同时修改 temperature 和 top_p,因为这两个设置的相互作用难以预测。0.8
spring.ai.mistralai.chat.max-tokens在聊天补全中生成的最大 token 数量。输入 token 和生成 token 的总长度受模型上下文长度的限制。-
spring.ai.mistralai.chat.safe-prompt指示是否在所有对话之前注入安全提示。false
spring.ai.mistralai.chat.random-seed此功能处于 Beta 状态。如果指定,系统将尽力确定性地采样,使得具有相同种子和参数的重复请求应返回相同的结果。-
spring.ai.mistralai.chat.stop如果检测到该 token,则停止生成。或者在提供数组时,如果检测到这些 token 之一,则停止生成。-
spring.ai.mistralai.chat.top-p一种替代温度采样的方法,称为核采样(nucleus sampling),其中模型考虑具有 top_p 概率质量的 token 的结果。例如,0.1 表示只考虑构成前 10% 概率质量的 token。我们通常建议调整此项或 temperature,但不要同时调整两者。-
spring.ai.mistralai.chat.response-format一个指定模型必须输出的格式的对象。设置为 { "type": "json_object" } 可启用 JSON 模式,保证模型生成的消息是有效的 JSON。设置为 { "type": "json_schema" } 并提供 schema 可启用原生结构化输出,保证模型匹配您提供的 JSON schema。有关更多详细信息,请参阅 Structured Output 部分。-
spring.ai.mistralai.chat.reasoning-effort控制可调整推理模型的推理努力程度。有效值包括 high 或 none。-
spring.ai.mistralai.chat.tools模型可能调用的工具列表。目前,仅支持函数作为工具。使用此功能提供模型可能为其生成 JSON 输入的函数列表。-
spring.ai.mistralai.chat.tool-choice控制模型调用哪个(如果有)函数。none 表示模型不调用函数,而是生成消息。auto 表示模型可以在生成消息或调用函数之间进行选择。通过 {"type: "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。当不存在函数时,默认为 none。如果存在函数,默认为 auto。-
spring.ai.mistralai.chat.tool-callbacks注册到 ChatModel 的工具回调。-
备注

对于 ChatModel 和 EmbeddingModel 实现,您可以覆盖通用的 spring.ai.mistralai.base-url 和 spring.ai.mistralai.api-key。如果设置了 spring.ai.mistralai.chat.base-url 和 spring.ai.mistralai.chat.api-key 属性,则它们优先于通用属性。如果您希望针对不同的模型和不同的模型端点使用不同的 Mistral AI 账户,这将非常有用。

提示

所有以 spring.ai.mistralai.chat 为前缀的属性,都可以在运行时通过在 Prompt 调用中添加特定的 Runtime Options 来覆盖。

运行时选项​

MistralAiChatOptions.java 提供了模型配置,例如要使用的模型、temperature、frequency penalty 等。

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

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

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

除了特定于模型的 MistralAiChatOptions,你还可以使用通过 ChatOptions#builder() 创建的便携式 ChatOptions 实例。

工具调用​

MistralAiChatModel 支持工具调用。该模型可以请求执行工具,但不会自行运行工具 —— Spring AI 负责处理执行。

对于大多数应用程序,请使用 ChatClient 与自动注册的 ToolCallingAdvisor 配合使用——参见 工具调用。对于需要自行驱动循环的低层控制场景,参见 ChatModel 工具调用。

结构化输出​

Mistral AI 通过 JSON Schema 支持原生的结构化输出,确保模型生成的响应严格符合您指定的结构。该功能适用于 Mistral Small 及后续模型。

使用 ChatClient 配合原生结构化输出​

使用 ChatClient 高级 API 和 ENABLE_NATIVE_STRUCTURED_OUTPUT 顾问是结构化输出的最简单方法:

record ActorsFilms(String actor, List<String> movies) {}

ActorsFilms actorsFilms = ChatClient.create(chatModel).prompt()
.advisors(AdvisorParams.ENABLE_NATIVE_STRUCTURED_OUTPUT)
.user("Generate the filmography of 5 movies for Tom Hanks.")
.call()
.entity(ActorsFilms.class);

该方法自动完成以下操作: - 根据您的 Java 类生成 JSON schema - 配置模型以使用原生结构化输出 - 将响应解析为您指定的类型

直接使用 ResponseFormat​

如需更多控制,你可以使用 ResponseFormat 类和 MistralAiChatOptions:

record MovieRecommendation(String title, String director, int year, String plotSummary) {}

var options = MistralAiChatOptions.builder()
.model(MistralAiApi.ChatModel.MISTRAL_SMALL.getValue())
.responseFormat(ResponseFormat.jsonSchema(MovieRecommendation.class))
.build();

ChatResponse response = chatModel.call(
new Prompt("Recommend a classic science fiction movie.", options));

ResponseFormat 类提供了多个工厂方法:

  • ResponseFormat.text() - 返回纯文本输出(默认)

  • ResponseFormat.jsonObject() - 返回有效的 JSON(不强制应用模式)

  • ResponseFormat.jsonSchema(Class<?>) - 从 Java 类生成模式

  • ResponseFormat.jsonSchema(String) - 使用 JSON 模式字符串

  • ResponseFormat.jsonSchema(Map) - 使用 JSON 模式 Map

JSON 模式 vs 结构化输出​

Mistral AI 支持两种与 JSON 相关的模式:

  • JSON 模式 (json_object):保证输出为有效的 JSON,但不强制特定的结构

  • 结构化输出 (json_schema):保证输出符合您的 JSON Schema

// JSON Mode - any valid JSON
var jsonMode = MistralAiChatOptions.builder()
.responseFormat(ResponseFormat.jsonObject())
.build();

// Structured Output - specific schema enforced
var structuredOutput = MistralAiChatOptions.builder()
.responseFormat(ResponseFormat.jsonSchema(MyClass.class))
.build();

有关结构化输出的更多信息,请参阅 结构化输出 文档。

推理模型​

Mistral 提供了两种推理方式:

  • 可调整:在 Mistral Small 4 和 Mistral Medium 3.5 上可用,通过 reasoning_effort 参数进行设置。允许模型以不同程度的深度进行思考。

  • 原生支持:适用于 Magistral 模型系列。这些模型始终会生成推理轨迹,专为深度推理任务而设计。

推理努力​

你可以通过 MistralAiChatOptions 中的 reasoningEffort 属性来配置推理投入程度。这允许你调整模型在生成响应前用于推理的计算量。

var options = MistralAiChatOptions.builder()
.model(MistralAiApi.ChatModel.MISTRAL_SMALL.getValue()) // Or any adjustable reasoning model
.reasoningEffort(MistralAiApi.ChatCompletionRequest.ReasoningEffort.HIGH)
.build();

ChatResponse response = chatModel.call(
new Prompt("Solve this complex math problem...", options));

Reasoning Content​

Mistral 推理模型暴露其内部思维链和引用。Spring AI 将这些从 API 响应映射到消息元数据。

您可以从 AssistantMessage 中访问以下元数据键:

  • reference_content: 用于追踪和引用的唯一键,将模型响应链接到其源文档。

  • thinking_content: 模型得出最终答案所使用的逐步推理过程(仅推理模型可访问)。

  • reference_thinking_content: 用于追踪和引用的唯一键,将模型的推理步骤链接到其源文档(可能仅推理模型可访问)。

ChatResponse response = chatModel.call(new Prompt("Solve this complex math problem..."));

AssistantMessage message = response.getResult().getOutput();

// Access the thinking content from metadata
String thinking = (String) message.getMetadata().get(MistralAiChatModel.THINKING_CONTENT_METADATA);
if (thinking != null && !thinking.isEmpty()) {
System.out.println("Model's thinking process:");
System.out.println(thinking);
}

多模态​

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

愿景​

Mistral AI 模型提供视觉多模态支持。更多信息请参考 Vision 指南。

Mistral AI 的 User Message API 允许在消息中包含 base64 编码的图像列表或图像 URL。Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 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.MISTRAL_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.MISTRAL_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/v1,并选择一个 Mistral 模型:spring.ai.openai.chat.model=mistral-small-latest,同时设置 Mistral AI API 密钥:spring.ai.openai.chat.api-key=<YOUR MISTRAL API KEY>。

有关在 Spring AI OpenAI 中使用 Mistral 的示例,请查看 MistralWithOpenAiChatModelIT.java 测试。

示例控制器(自动配置)​

创建 一个新的 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.model=mistral-small-latest
spring.ai.mistralai.chat.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 实现了 ChatModel 和 StreamingChatModel 接口,并使用 Low-level MistralAiApi Client 连接到 Mistral AI 服务。

在项目的 Maven pom.xml 文件中添加 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'
}
提示

请参考 依赖管理 部分,将 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.MISTRAL_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 是一个流式(fluent)选项构建器。

低层 MistralAiApi 客户端​

MistralAiApi 是用于 Mistral 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.MISTRAL_LARGE.getValue(), 0.8, false));

// Streaming request
Flux<ChatCompletionChunk> streamResponse = this.mistralAiApi.chatCompletionStream(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), MistralAiApi.ChatModel.MISTRAL_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 Keys 页面 生成令牌。

添加依赖​

要使用 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 客户端​

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

这里是一个简单的示例,展示了如何通过编程方式使用该 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 示例​