Mistral AI Chat
Spring AI 参考文档 - Mistral AI 聊天模型集成指南
概述
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=<您的MistralAI API密钥>
为了在处理 API 密钥等敏感信息时增强安全性,您可以使用 Spring 表达式语言 (SpEL) 来引用自定义环境变量:
# 在 application.yml 中
spring:
ai:
mistralai:
api-key: ${MISTRALAI_API_KEY}
# 在您的环境或 .env 文件中
export MISTRALAI_API_KEY=<您的MistralAI API密钥>
您也可以在应用程序代码中以编程方式设置此配置:
// 从安全源或环境变量检索 API 密钥
String apiKey = System.getenv("MISTRALAI_API_KEY");
添加存储库和 BOM
Spring AI 构件发布在 Maven Central 和 Spring Snapshot 存储库中。 请参考构件存储库部分,将这些存储库添加到您的构建系统。
为了帮助依赖管理,Spring AI 提供了 BOM(物料清单)以确保在整个项目中使用一致的 Spring AI 版本。请参考依赖管理部分,将 Spring AI BOM 添加到您的构建系统。
自动配置
注意:Spring AI 自动配置和启动模块构件名称发生了重大变化。 请参阅升级说明了解更多信息。
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,则抛出 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 | 连接的 URL | api.mistral.ai |
| spring.ai.mistralai.api-key | API 密钥 | - |
配置属性
注意:聊天自动配置的启用和禁用现在通过前缀为
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 | 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 | 使用的采样温度,控制生成完成的明显创造性。较高的值会使输出更随机,而较低的值会使结果更聚焦和确定性。不建议同时修改 temperature 和 top_p 的相同完成请求,因为这两个设置的相互作用难以预测。 | 0.8 |
| spring.ai.mistralai.chat.options.maxTokens | 在聊天完成中生成的最大令牌数。输入令牌和生成令牌的总长度受模型的上下文长度限制。 | - |
| spring.ai.mistralai.chat.options.safePrompt | 指示是否在所有对话之前注入安全提示。 | false |
| spring.ai.mistralai.chat.options.randomSeed | 此功能处于 Beta 阶段。如果指定,我们的系统将尽力进行确定性采样,使得具有相同种子和参数的重复请求应返回相同结果。 | - |
| 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.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 |
注意:您可以覆盖
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.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#builder() 创建的可移植 ChatOptions 实例。
函数调用
您可以使用 MistralAiChatModel 注册自定义 Java 函数,并让 Mistral AI 模型智能地选择输出包含调用一个或多个注册函数参数的 JSON 对象。
这是将 LLM 功能与外部工具和 API 连接的强大技术。
阅读更多关于工具调用的信息。
多模态
多模态指模型同时理解和处理来自各种来源(包括文本、图像、音频和其他数据格式)信息的能力。 Mistral AI 支持文本和视觉模态。
视觉
提供视觉多模态支持的 Mistral AI 模型包括 pixtral-large-latest。
有关更多信息,请参阅视觉指南。
Mistral AI 用户消息 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.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 图像作为输入:
以及文本消息 "Explain what do you see on this picture?",并生成如下响应:
这是一个具有简单设计的水果碗图像。碗由金属制成,具有弯曲的线材边缘,
创造出开放结构,使水果从所有角度都可见。碗内,有两个
黄色香蕉放在似乎是红苹果的东西上面。香蕉略微过熟,
正如它们皮上的棕色斑点所示。碗顶部有一个金属环,可能作为手柄
用于携带。碗放置在平坦的表面上,中性色的背景提供了对
内部水果的清晰视图。
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-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 实现了 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 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."));
// 或使用流式响应
Flux<ChatResponse> response = this.chatModel.stream(
new Prompt("Generate the names of 5 famous pirates."));
MistralAiChatOptions 为聊天请求提供配置信息。
MistralAiChatOptions.Builder 是一个流畅的选项构建器。
低级 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);
// 同步请求
ResponseEntity<ChatCompletion> response = this.mistralAiApi.chatCompletionEntity(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8, false));
// 流式请求
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 函数调用 教程。