密斯特拉人工智能聊天
Spring AI 支持来自 Mistral AI 的多种人工智能语言模型。您可以与 Mistral AI 语言模型进行交互,并基于 Mistral 模型创建多语言对话助手。
| Mistral AI同样提供了与OpenAI API兼容的端点。 查看OpenAI API兼容性部分,了解如何使用Spring AI OpenAI集成与Mistral端点通信。 |
前提条件
您需要使用 Mistral AI 创建一个 API 以访问 Mistral AI 语言模型。
在 Mistral AI 注册页面 创建一个帐户,并在 API 密钥页面 上生成Tokens。
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");
自动配置
|
There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。 |
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 构建脚本文件中。
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,且不重试客户端错误代码 |
false |
spring.ai.retry.exclude-on-http-codes |
不应触发重试的HTTP状态代码列表(例如,用于抛出非暂时性AI异常)。 |
empty |
spring.ai.retry.on-http-codes |
应触发重试的HTTP状态码列表(例如,用于抛出TransientAiException)。 |
empty |
连接属性
前缀 spring.ai.mistralai 用于作为属性前缀,以便您连接到OpenAI。
| 属性 | 描述 | 默认 |
|---|---|---|
spring.ai.mistralai.base-url |
要连接的URL |
|
spring.ai.mistralai.api-key |
API 密钥 |
- |
配置属性
|
启用和禁用聊天自动配置现在通过顶级属性使用前缀 要启用,请设置 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聊天模型。 |
密史脱拉风 |
spring.ai.mistralai.chat.base-url |
针对属性 |
- |
spring.ai.mistralai.chat.api-key |
可选的覆盖,默认为 |
- |
spring.ai.mistralai.chat.options.model |
这是使用的Mistral AI聊天模型 |
|
spring.ai.mistralai.chat.options.temperature |
用于控制生成内容的表面创新性的采样温度。较高的值会使输出更加随机,而较低的值会使结果更加集中和确定性。不建议在同一完成请求中修改 |
0.8 |
spring.ai.mistralai.chat.options.maxTokens |
聊天补全时生成的最大Tokens数量。输入Tokens和生成Tokens的总长度受到模型上下文长度的限制。 |
- |
spring.ai.mistralai.chat.options.safePrompt |
指示是否在所有对话前注入安全提示。 |
false |
spring.ai.mistralai.chat.options.randomSeed |
此功能处于测试阶段。如果指定了,我们的系统将尽力进行确定性采样,以便使用相同的种子和参数的重复请求应返回相同的结果。 |
- |
spring.ai.mistralai.chat.options.stop |
如果检测到此Tokens,则停止生成。或者,当提供一个数组时,如果检测到其中任何一个Tokens,则停止生成。 |
- |
spring.ai.mistralai.chat.options.topP |
一种替代温度采样的方法,称为核采样(nucleus sampling),在此方法中,模型仅考虑具有前top_p概率质量的Tokens的结果。因此,0.1意味着只考虑构成前10%概率质量的Tokens。我们通常建议调整此参数或 |
- |
spring.ai.mistralai.chat.options.responseFormat |
指定模型必须输出的格式的对象。设置为 |
- |
spring.ai.mistralai.chat.options.tools |
模型可能调用的工具列表。当前,仅支持函数作为工具。使用此功能来提供模型可能为其生成JSON输入的函数列表。 |
- |
spring.ai.mistralai.chat.options.toolChoice |
控制模型调用(如有)的函数。 |
- |
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 |
您可以覆盖通用的 spring.ai.mistralai.base-url 和 spring.ai.mistralai.api-key,以便为 ChatModel 和 EmbeddingModel 实现自定义设置。
如果设置了 spring.ai.mistralai.chat.base-url 和 spring.ai.mistralai.chat.api-key 属性,它们将优先于通用属性。
这对于希望为不同模型及不同模型端点使用不同的Mistral AI账户的情况非常有用。 |
所有以spring.ai.mistralai.chat.options为前缀的属性都可以通过向Prompt调用中添加请求特定的运行时选项在运行时覆盖。 |
运行时选项
MistralAiChatOptions.java 文件提供了模型配置,如使用的模型、温度、频率惩罚等参数。
On start-up, the default options can be configured with the MistralAiChatModel(api, options) constructor or the spring.ai.mistralai.chat.options.* properties.
在运行时,您可以通过向 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对象,以调用一个或多个已注册的函数。
这是一种将LLM功能与外部工具和API连接起来的强大技术。
了解更多关于工具调用的信息。
结构化输出
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模式 - 配置模型以使用原生结构化输出 - 将响应解析为您指定的类型
直接使用ResponseFormat
为了实现更多控制,您可以将 ResponseFormat 类与 MistralAiChatOptions 一起使用:
record MovieRecommendation(String title, String director, int year, String plotSummary) {}
var options = MistralAiChatOptions.builder()
.model(MistralAiApi.ChatModel.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模式映射
JSON模式与结构化输出
Mistral AI 支持两种与 JSON 相关的模式:
-
JSON模式 (
json_object): 保证有效的JSON输出,但不强制特定的结构 -
结构化输出 (
json_schema): 保证输出符合您的JSON模式
// 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 AI 支持文本和视觉两种模态。
愿景
提供视觉多模态支持的Mistral AI模型包括pixtral-large-latest。
更多信息请参考视觉指南。
Mistral AI 的 用户消息API 可以将一系列 base64 编码的图像或图像网址与消息结合。
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平台:`0`,并选择一个Mistral模型:`1`,然后设置Mistral AI API密钥:`2`。
查看MistralWithOpenAiChatModelIT.java测试用例以获取关于如何在Spring AI OpenAI上使用Mistral的示例。
示例控制器(自动配置)
创建一个新的Spring Boot项目,并将spring-boot-starter-web添加到您的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模型实现了ChatModel和StreamingChatModel,并使用了低级MistralAiApi客户端来连接Mistral AI服务。
将 spring-ai-mistral-ai 依赖添加到您项目的 Maven pom.xml 文件中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mistral-ai</artifactId>
</dependency>
或者添加到您的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底层客户端
MistralAiApi提供的轻量级Java客户端用于Mistral AI API。
以下是一个简单示例,展示了如何以编程方式使用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 示例
-
MistralAiApiIT.java 测试提供了一些关于如何使用轻量级库的一般示例。
-
PaymentStatusFunctionCallingIT.java 测试展示了如何使用低级API调用工具函数。 基于Mistral AI 函数调用教程。
前提条件
您需要在Mistral AI上创建一个API以访问Mistral AI语言模型。 在Mistral AI注册页面创建账户,并在API密钥页面生成Tokens。
添加依赖项
要使用Mistral AI OCR API,您需要将spring-ai-mistral-ai依赖项添加到您的项目中。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mistral-ai</artifactId>
</dependency>
或者添加到您的Gradle 构建脚本文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-mistral-ai'
}
MistralOcrApi客户端底层
MistralOcrApi 为 Mistral 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 示例
-
MistralOcrApiIT.java 测试提供了一些关于如何使用轻量级库的一般示例。