Mistral AI

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

Spring AI 支持 Mistral AI 的多种 AI 语言模型。你可以通过 Mistral 语言模型构建多语言对话助手。

Mistral AI 提供兼容 OpenAI API 的终端点。请参阅 OpenAI API 兼容性 章节,了解如何使用 Spring AI 的 OpenAI 集成与 Mistral 端点交互。

先决条件

你需要创建 Mistral AI API Key 才能访问其语言模型。

Mistral AI 注册页面 创建账户,并在 API 密钥页面 生成访问令牌。

Spring AI 项目定义了名为 spring.ai.mistralai.api-key 的配置属性,需将其设置为从 Mistral控制台 获取的 API Key 值。

你可以在 application.properties 文件中设置该配置属性:

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

为增强处理敏感信息(如 API Key)时的安全性,可使用 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");

添加仓库和 BOM

Spring AI 组件已发布在 Maven 中央仓库和 Spring Snapshot 仓库。请参阅 Artifact 仓库 章节将这些仓库添加到你的构建系统。

为简化依赖管理,Spring AI 提供 BOM 以确保整个项目使用统一版本的 Spring AI。请参阅 依赖管理 章节将 Spring AI BOM 添加到你的构建系统。

自动配置

Spring AI 自动配置和 Starter 模块的构件名称已发生重大变更。更多信息请参阅 升级说明

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 sec.

spring.ai.retry.backoff.multiplier

退避间隔乘数。

5

spring.ai.retry.backoff.max-interval

最大退避时长。

3 min.

spring.ai.retry.on-client-errors

若为 false,则抛出 NonTransientAiException,且不对 4xx 客户端错误代码尝试重试。

false

spring.ai.retry.exclude-on-http-codes

不应触发重试的 HTTP 状态码列表(例如用于抛出 NonTransientAiException)。

empty

spring.ai.retry.on-http-codes

应触发重试的 HTTP 状态码列表(例如用于抛出 TransientAiException)。

empty

连接属性

前缀 spring.ai.mistralai 用于配置连接 OpenAI 的属性参数。

属性 说明 默认值

spring.ai.mistralai.base-url

要连接到的 URL

api.mistral.ai

spring.ai.mistralai.api-key

API 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

可选覆盖 spring.ai.mistralai.base-url 属性以提供聊天专用 URL。

-

spring.ai.mistralai.chat.api-key

可选覆盖 spring.ai.mistralai.api-key 以提供聊天专用的 API Key。

-

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

聊天补全中生成的最大 Token 数量。输入 Token 和生成 Token 的总长度受模型上下文长度限制。

-

spring.ai.mistralai.chat.options.safePrompt

指示是否在所有对话前注入安全提示。

false

spring.ai.mistralai.chat.options.randomSeed

该功能处于 Beta 阶段。若指定种子值,系统将尽力确保确定性采样——相同种子和参数的重复请求应返回相同结果。

-

spring.ai.mistralai.chat.options.stop

检测到此 Token 时停止生成。若提供数组,则检测到任一 Token 即停止。

-

spring.ai.mistralai.chat.options.topP

温度采样的替代方案——核采样(nucleus sampling),模型仅考虑累计概率达到 top_p 阈值的 token 候选集。例如 0.1 表示仅考虑概率质量排名前 10% 的 Token。通常建议仅调整此参数或 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

mistralai.base-url` 和 spring.ai.mistralai.api-key 配置。若设置了 spring.ai.mistralai.chat.base-urlspring.ai.mistralai.chat.api-key 属性,它们将优先于通用属性生效。此特性适用于需要为不同模型使用不同 Mistral AI 账户及端点的场景。
所有以 spring.ai.mistralai.chat.options 为前缀的属性,均可通过在 Prompt 调用中添加请求特定的 运行时选项 进行覆盖。

运行时选项

MistralAiChatOptions.java 提供模型配置参数,包括使用的模型名称、温度值(temperature)、频率惩罚系数(frequency penalty)等。

在启动时,默认选项可通过 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 外,你还可以使用通过 ChatOptionsBuilder#builder() 创建的通用 ChatOptions 实例。

函数调用

你可向 MistralAiChatModel 注册自定义 Java 函数,使 Mistral AI 模型能智能输出包含参数的 JSON 对象来调用一个或多个注册函数。该技术能有效连接大语言模型能力与外部工具及 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?” 后,生成的响应类似这样:

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 AI 平台:

  • 设置 OpenAI base URL:spring.ai.openai.chat.base-url=https://api.mistral.ai

  • 选择Mistral模型:spring.ai.openai.chat.options.model=mistral-small-latest

  • 配置 Mistral API Key:spring.ai.openai.chat.api-key=<你的MISTRAL API密钥>

查看 MistralWithOpenAiChatModelIT.java 测试类,获取通过 Spring AI OpenAI 集成使用 Mistral 的示例。

示例 Controller (自动配置)

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

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 实现 ChatModelStreamingChatModel 接口,并通过 低级 MistralAiApi 客户端 连接 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."));

// Or with streaming responses
Flux<ChatResponse> response = this.chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

MistralAiChatOptions 提供聊天请求的配置信息。MistralAiChatOptions.Builder 是一个 Fluent 式的选项构建器。

低级 MistralAiApi 客户端

MistralAiApiMistral 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.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 示例