获取最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

密斯特拉人工智能聊天

Spring AI 支持来自 Mistral 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

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 Central 和 Spring Snapshot 仓库中。 请参阅 工件仓库 部分,以将这些仓库添加到您的构建系统。spring-doc.cadn.net.cn

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

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。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 构建脚本文件中。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

属性 描述 默认

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 分钟。spring-doc.cadn.net.cn

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

如果为false,则抛出NonTransientAiException,且不重试客户端错误代码4xxspring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

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

不应触发重试的HTTP状态代码列表(例如,用于抛出非暂时性AI异常)。spring-doc.cadn.net.cn

emptyspring-doc.cadn.net.cn

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

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

emptyspring-doc.cadn.net.cn

连接属性

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

属性 描述 默认

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

属性 描述 默认

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

密史脱拉风spring-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

可选的覆盖,默认为spring.ai.mistralai.api-key,用于提供聊天专用的API密钥。spring-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

聊天补全时生成的最大Tokens数量。输入Tokens和生成Tokens的总长度受到模型上下文长度的限制。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

如果检测到此Tokens,则停止生成。或者,当提供一个数组时,如果检测到其中任何一个Tokens,则停止生成。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

一种替代温度采样的方法,称为核采样(nucleus sampling),在此方法中,模型仅考虑具有前top_p概率质量的Tokens的结果。因此,0.1意味着只考虑构成前10%概率质量的Tokens。我们通常建议调整此参数或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格式。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.functionsspring-doc.cadn.net.cn

函数列表,通过它们的名称来识别,以便在单个提示请求中启用函数调用。具有这些名称的函数必须存在于functionCallbacks注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

用于注册到 ChatModel 的 Mistral AI 工具函数回调。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

如果为真,Spring AI 将不会在内部处理函数调用,而是将其代理给客户端。此时,由客户端负责处理函数调用、将其分发到相应的函数并返回结果。如果为假(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

您可以覆盖通用的 spring.ai.mistralai.base-urlspring.ai.mistralai.api-key,以便为 ChatModelEmbeddingModel 实现自定义设置。 如果设置了 spring.ai.mistralai.chat.base-urlspring.ai.mistralai.chat.api-key 属性,它们将优先于通用属性。 这对于希望为不同模型及不同模型端点使用不同的Mistral AI账户的情况非常有用。
所有以spring.ai.mistralai.chat.options为前缀的属性都可以通过向Prompt调用中添加请求特定的运行时选项在运行时覆盖。

运行时选项

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

On start-up, the default options can be configured with the MistralAiChatModel(api, options) constructor or the spring.ai.mistralai.chat.options.* properties.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.LARGE.getValue())
            .temperature(0.5)
        .build()
    ));
除了模型特定的MistralAiChatOptions之外,您还可以使用可移植的ChatOptions实例,通过ChatOptions#builder()创建。

函数调用

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

多模态

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

愿景

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

Mistral AI 的 用户消息API 可以将一系列 base64 编码的图像或图像网址与消息结合。 Spring AI 的 消息 接口通过引入 媒体 类型,促进了多模态AI模型的应用。 此类型包含了关于消息中媒体附件的数据和详细信息,利用了 Spring 的 org.springframework.util.MimeTypeorg.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()));

或图像URL等效形式: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

伴随着文本信息 "解释一下你在图片中看到了什么?",并生成如下的回复: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平台:`0`,并选择一个Mistral模型:`1`,然后设置Mistral AI API密钥:`2`。spring-doc.cadn.net.cn

查看MistralWithOpenAiChatModelIT.java测试用例以获取关于如何在Spring AI OpenAI上使用Mistral的示例。spring-doc.cadn.net.cn

示例控制器(自动配置)

创建一个新的Spring Boot项目,并将spring-boot-starter-web添加到您的pom(或gradle)依赖中。spring-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);
    }
}

手动配置

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 构建脚本文件中。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.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底层客户端

以下是一个简单示例,展示了如何以编程方式使用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.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注释。spring-doc.cadn.net.cn

MistralAiApi 示例