此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

Mistral AI 聊天

Spring AI 支持来自 Mistral AI 的各种 AI 语言模型。您可以与 Mistral AI 语言模型进行交互,并基于 Mistral 模型创建一个多语言对话助手。spring-doc.cadn.net.cn

Mistral AI 提供了一个与 OpenAI API 兼容的端点。 请查阅 OpenAI API 兼容性 部分,了解如何使用 Spring AI OpenAI 整合来与 Mistral 端点进行交互。

前置条件

您需要使用Mistral AI创建一个API以访问Mistral AI语言模型。spring-doc.cadn.net.cn

Mistral AI 注册页面创建账号,并在API密钥页面生成Tokens。spring-doc.cadn.net.cn

The Spring AI项目定义了一个配置属性名为spring.ai.mistralai.api-key,你应该将其设置为从console.mistral.ai获得的API Key的值。spring-doc.cadn.net.cn

您可以在您的application.properties文件中设置此配置属性:spring-doc.cadn.net.cn

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

处理敏感信息(如API密钥)时,为了增强安全性,您可以使用Spring表达式语言(SpEL)引用自定义环境变量:spring-doc.cadn.net.cn

# 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>

您也可以在应用程序代码中通过编程方式设置此配置:spring-doc.cadn.net.cn

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

添加仓库和BOM

Spring AI 构件发布在 Maven 中央仓库和 Spring Snapshot 仓库中。 请参阅 构件仓库 部分,将这些仓库添加到您的构建系统中。spring-doc.cadn.net.cn

为了帮助进行依赖管理,Spring AI 提供了一个 BOM(物料清单),以确保整个项目中使用的是相同的 Spring AI 版本。请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建系统中。spring-doc.cadn.net.cn

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

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

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-mistral-ai'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。

聊天属性

重试属性

spring.ai.retry 前缀用作属性前缀,允许您配置 Mistral AI 聊天模型的重试机制。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.retry.max-attemptsspring-doc.cadn.net.cn

最大重试尝试次数。spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

spring.ai.retry.backoff.initial-intervalspring-doc.cadn.net.cn

指数退避策略的初始睡眠时长。spring-doc.cadn.net.cn

2 秒。spring-doc.cadn.net.cn

spring.ai.retry.backoff.multiplierspring-doc.cadn.net.cn

重试间隔倍数。spring-doc.cadn.net.cn

5spring-doc.cadn.net.cn

spring.ai.retry.backoff.max-intervalspring-doc.cadn.net.cn

最大退避持续时间。spring-doc.cadn.net.cn

3 min.spring-doc.cadn.net.cn

spring.ai.retry.on-client-errorsspring-doc.cadn.net.cn

如果为假,则抛出一个NonTransientAiException,并且不尝试重试4xx客户端错误代码spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.retry.exclude-on-http-codesspring-doc.cadn.net.cn

不应当触发重试的HTTP状态码列表(例如,抛出NonTransientAiException)。spring-doc.cadn.net.cn

<p>空内容</p>spring-doc.cadn.net.cn

spring.ai.retry.on-http-codesspring-doc.cadn.net.cn

应触发重试的HTTP状态码列表(例如,抛出TransientAiException)。spring-doc.cadn.net.cn

<p>空内容</p>spring-doc.cadn.net.cn

连接属性

使用前缀spring.ai.mistralai作为属性前缀,以便连接到OpenAI。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.mistralai.base-urlspring-doc.cadn.net.cn

连接的URLspring-doc.cadn.net.cn

api.mistral.aispring-doc.cadn.net.cn

spring.ai.mistralai.api-keyspring-doc.cadn.net.cn

API密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

配置属性

现在通过带有前缀spring.ai.model.chat的顶级属性来配置聊天自动配置的启用和禁用。spring-doc.cadn.net.cn

要启用,请设置:spring.ai.model.chat=mistral(默认已启用)spring-doc.cadn.net.cn

要禁用,请设置 spring.ai.model.chat=none(或任何与 mistral 不匹配的值)spring-doc.cadn.net.cn

此更改是为了允许配置多个模型。spring-doc.cadn.net.cn

spring.ai.mistralai.chat 前缀是属性前缀,允许你配置与 Mistral AI 实现的聊天模型相关的设置。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.mistralai.chat.enabled (已移除且不再有效)spring-doc.cadn.net.cn

启用Mistral AI聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.chatspring-doc.cadn.net.cn

启用Mistral AI聊天模型。spring-doc.cadn.net.cn

mistralspring-doc.cadn.net.cn

spring.ai.mistralai.chat.base-urlspring-doc.cadn.net.cn

可选覆盖对于spring.ai.mistralai.base-url属性以提供聊天特定的URL。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.api-keyspring-doc.cadn.net.cn

可选覆盖用于提供针对聊天的具体API密钥的spring.ai.mistralai.api-keyspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.modelspring-doc.cadn.net.cn

这便是要使用的Mistral AI聊天模型spring-doc.cadn.net.cn

open-mistral-7b, open-mixtral-8x7b, open-mixtral-8x22b, mistral-small-latest, mistral-large-latestspring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.temperaturespring-doc.cadn.net.cn

使用以控制生成完成体的似乎创造力的采样温度。较高值会使输出更具随机性,而较低值会使结果更加集中和确定。不建议在同一完成体请求中修改temperaturetop_p,因为这两个设置之间的交互难以预测。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.maxTokensspring-doc.cadn.net.cn

生成聊天补全时的最大token数。输入token和生成token的总长度受限于模型的上下文长度。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.safePromptspring-doc.cadn.net.cn

表示是否在所有会话之前注入安全提示。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.randomSeedspring-doc.cadn.net.cn

此功能处于测试版。如指定,我们的系统将尽力进行确定性采样,这意味着使用相同的种子和参数重复请求应返回相同的结果。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.stopspring-doc.cadn.net.cn

如果检测到此标记,请停止生成。或者,在提供数组时,如果检测到以下标记之一,请停止。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.topPspring-doc.cadn.net.cn

在温度采样之外,还有一种称为核采样的方法,模型会考虑具有 top_p 概率质量的标记结果。所以 0.1 表示只有前 10% 的概率质量的标记被考虑进去。我们通常建议修改这个值或 temperature 中的一个,但不会同时修改两者。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.responseFormatspring-doc.cadn.net.cn

指定模型必须输出的格式的对象。设置为{ "type": "json_object" }启用JSON模式,保证模型生成的消息是有效的JSON。设置为{ "type": "json_schema" }并提供一个方案可以启用原生结构化输出,保证模型将匹配您提供的JSON方案。有关更多详情,请参阅结构化输出部分。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.toolsspring-doc.cadn.net.cn

模型可能调用的工具列表。目前,仅支持函数作为工具。使用此选项提供模型可以生成JSON输入的函数列表。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.toolChoicespring-doc.cadn.net.cn

控制模型调用哪个(如果有的话)函数。none表示模型不会调用任何函数,而是生成一条消息。auto表示模型可以选择生成一条消息或调用一个函数。{"type: "function", "function": {"name": "my_function"}}通过指定特定的函数来强制模型调用该函数。none当没有提供函数时是默认值。auto当提供了函数时是默认值。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.tool-namesspring-doc.cadn.net.cn

使用名称标识的工具列表,以在单个提示请求中启用功能调用。具有这些名称的工具必须存在于ToolCallback注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.tool-callbacksspring-doc.cadn.net.cn

使用回调注册与ChatModel相关的工具。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.mistralai.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为假,Spring AI 将不会内部处理工具调用,而是将它们代理给客户端。然后需要由客户端负责处理这些工具调用、将其分派到适当的函数,并返回结果。如果为真(默认值),Spring AI 将会内部处理这些函数调用。仅适用于支持功能调用的聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

您可以在 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调用添加请求特定的运行时选项来覆盖。

运行时选项

The MistralAiChatOptions.java 提供了模型配置,例如使用的模型、温度、频率惩罚等。spring-doc.cadn.net.cn

启动时,可以使用MistralAiChatModel(api, options)构造函数或spring.ai.mistralai.chat.options.*属性来配置默认选项。spring-doc.cadn.net.cn

在运行时,您可以通过向Prompt调用添加新的、针对请求的选项来覆盖默认选项。 例如,要为特定请求覆盖默认模型和温度设置:spring-doc.cadn.net.cn

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()
    ));
此外,除了针对特定模型的外,您还可以使用一个通用的实例,该实例通过创建。

函数调用

您可以使用MistralAiChatModel注册自定义的Java函数,并使Mistral AI模型智能地选择输出一个包含调用一个或多个已注册函数所需参数的JSON对象。 这是一种强大的技术,可以将LLM能力与外部工具和API连接起来。 要了解有关工具调用的更多信息,请继续阅读。spring-doc.cadn.net.cn

结构化输出

Mistral AI 支持通过 JSON Schema 原生生成结构化输出,确保模型生成的响应严格符合您规定的结构。 此功能适用于 Mistral Small 及其后续版本的模型。spring-doc.cadn.net.cn

使用 ChatClient 与原生结构化输出

使用结构化输出最简单的方式是通过高级API ChatClient 和顾问 ENABLE_NATIVE_STRUCTURED_OUTPUTspring-doc.cadn.net.cn

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模式 - 配置模型以使用原生结构化输出 - 将响应解析为您指定的类型spring-doc.cadn.net.cn

直接使用ResponseFormat

使用 ResponseFormat 类可以获得更多控制,请参考 MistralAiChatOptions:spring-doc.cadn.net.cn

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

`0` 类提供了几个工厂方法:spring-doc.cadn.net.cn

JSON模式 vs 结构化输出

Mistral AI 支持两种与 JSON 相关的模式:spring-doc.cadn.net.cn

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

有关结构化输出的更多信息,请参阅结构化输出转换器文档。spring-doc.cadn.net.cn

多模态

多模态是指模型同时理解和处理来自各种来源的信息的能力,包括文本、图像、音频和其他数据格式。 Mistral AI 支持文本和视觉模态。spring-doc.cadn.net.cn

视觉

Mistral AI模型提供视觉多模态支持的包括pixtral-large-latest。 参见视觉指南以获取更多信息。spring-doc.cadn.net.cn

The Mistral AI 用户消息API 可以将 base64 编码的图片列表或图片URL与消息一同发送。 Spring AI 的 Message 接口通过引入 Media 类型,促进了多模态AI模型的应用。 该类型包含了消息中媒体附件的数据和详细信息,并使用了 Spring 的 org.springframework.util.MimeType 和一个 org.springframework.core.io.Resource 来处理原始的媒体数据。spring-doc.cadn.net.cn

以下是从MistralAiChatModelIT.java中摘取的一个代码示例,展示了用户文本与图片的融合。spring-doc.cadn.net.cn

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

or the image URL equivalent:spring-doc.cadn.net.cn

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图像:spring-doc.cadn.net.cn

Multimodal Test Image

<p> along with the text message &quot;请解释你在图片上看到了什么?&quot;, 并生成类似这样的响应:</p>spring-doc.cadn.net.cn

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 KEYspring-doc.cadn.net.cn

检查MistralWithOpenAiChatModelIT.java测试用例,了解如何使用Spring AI OpenAI框架中的Mistral。spring-doc.cadn.net.cn

样例控制器(自动配置)

创建一个新的Spring Boot项目,并在pom(或gradle)依赖中添加spring-ai-starter-model-mistral-aispring-doc.cadn.net.cn

src/main/resources目录下添加一个名为application.properties的文件以启用并配置Mistral AI聊天模型:spring-doc.cadn.net.cn

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类示例。spring-doc.cadn.net.cn

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

手动配置

The MistralAiChatModel 实现了 ChatModelStreamingChatModel,并使用了 低级 MistralAiApi 客户端 连接到 Mistral AI 服务。spring-doc.cadn.net.cn

将如下的spring-ai-mistral-ai依赖添加到项目中Maven的pom.xml文件中:spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-mistral-ai'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。

接下来,创建一个MistralAiChatModel 并用于文本生成:spring-doc.cadn.net.cn

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 是一个流畅式选项构建器。spring-doc.cadn.net.cn

低级MistralAiApi客户端

The MistralAiApi 提供的是一个轻量级的 Java 客户端用于访问 Mistral AI APIspring-doc.cadn.net.cn

这里是一个简单的示例,展示了如何通过编程方式使用API:spring-doc.cadn.net.cn

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以获取更多信息。spring-doc.cadn.net.cn

MistralAiApi 示例

Mistral AI OCR

Spring AI 支持与 Mistral AI 集成的光学字符识别(OCR)。这使得您可以从文档中提取文本和图像数据。spring-doc.cadn.net.cn

前置条件

您需要使用 Mistral AI 创建一个 API 以访问 Mistral AI 语言模型。 在 Mistral AI 注册页面 创建账户,并在 API 密钥页面生成 token。spring-doc.cadn.net.cn

添加依赖项

要使用Mistral AI OCR API,您需要将spring-ai-mistral-ai依赖项添加到您的项目中。spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

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

低级MistralOcrApi客户端

The MistralOcrApi 提供了一个轻量级的Java客户端用于访问 Mistral AI OCR APIspring-doc.cadn.net.cn

这里是一个简单的示例,展示了如何通过编程方式使用API:spring-doc.cadn.net.cn

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以获取更多信息。spring-doc.cadn.net.cn

MistralOcrApi 示例