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语言模型。

在https://auth.mistral.ai/ui/registration[Mistral AI注册页面]创建账户,并在https://console.mistral.ai/api-keys/[API密钥页面]生成令牌。

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

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

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

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

# 在application.yml中
spring:
  ai:
    mistralai:
      api-key: ${MISTRALAI_API_KEY}
# 在您的环境或.env文件中
export MISTRALAI_API_KEY=<your-mistralai-api-key>

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

// 从安全源或环境变量中获取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自动配置、starter模块的构件名称发生了重大变化。 请参阅https://docs.spring.io/spring-ai/reference/upgrade-notes.html[升级说明]了解更多信息。

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

要连接的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-7bopen-mixtral-8x7bopen-mixtral-8x22bmistral-small-latestmistral-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

此功能处于测试阶段。如果指定,我们的系统将尽最大努力进行确定性采样,使得具有相同种子和参数的重复请求应该返回相同的结果。

-

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外,您还可以使用可移植的https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java[ChatOptions]实例,使用https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/main/java/org/springframework/ai/chat/prompt/ChatOptionsBuilder.java[ChatOptionsBuilder#builder()]创建。

函数调用

您可以在`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客户端与Mistrial通信。 为此,您需要将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

提示:用您的Mistral AI凭据替换`api-key`。

这将创建一个`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服务。

在项目的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.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));

请参阅https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-mistral-ai/src/main/java/org/springframework/ai/mistralai/api/MistralAiApi.java[MistralAiApi.java]的JavaDoc获取更多信息。

MistralAiApi示例

  • MistralAiApiIT.java测试提供了一些关于如何使用轻量级库的一般示例。

  • PaymentStatusFunctionCallingIT.java测试展示了如何使用低级API调用工具函数。 基于https://docs.mistral.ai/guides/function-calling/[Mistral AI函数调用]教程。