Mistral AI Chat

Spring AI 支持 Mistral AI 中的各种 AI 语言模型。您可以与 Mistral AI 语言模型交互,并根据 Mistral 模型基于多语言对话助理。

Spring AI supports the various AI language models from Mistral AI. You can interact with Mistral AI language models and create a multilingual conversational assistant based on Mistral models.

Mistral AI 也提供一个与 OpenAI API 兼容的端点。查看 OpenAI API compatibility 部分,了解如何使用 Spring AI OpenAI 集成与 Mistral 端点通信。

Mistral AI offers an OpenAI API-compatible endpoint as well. Check the _openai_api_compatibility section to learn how to use the Spring AI OpenAI integration to talk to a Mistral endpoint.

Prerequisites

您需要使用 Mistral AI 创建一个 API 才能访问 Mistral AI 语言模型。

You will need to create an API with Mistral AI to access Mistral AI language models.

Mistral AI registration page 创建一个帐户并在 API Keys page 上生成令牌。

Create an account at Mistral AI registration page and generate the token on the API Keys page.

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

The Spring AI project defines a configuration property named spring.ai.mistralai.api-key that you should set to the value of the API Key obtained from console.mistral.ai.

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

You can set this configuration property in your application.properties file:

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

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

For enhanced security when handling sensitive information like API keys, you can use Spring Expression Language (SpEL) to reference a custom environment variable:

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

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

You can also set this configuration programmatically in your application code:

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

Add Repositories and BOM

Spring AI 工件发布在 Maven Central 和 Spring Snapshot 存储库中。请参阅“添加 Spring AI 仓库”部分,将这些仓库添加到您的构建系统。

Spring AI artifacts are published in Maven Central and Spring Snapshot repositories. Refer to the Artifact Repositories section to add these repositories to your build system.

为了帮助进行依赖项管理,Spring AI 提供了一个 BOM(物料清单)以确保在整个项目中使用一致版本的 Spring AI。有关将 Spring AI BOM 添加到你的构建系统的说明,请参阅 Dependency Management 部分。

To help with dependency management, Spring AI provides a BOM (bill of materials) to ensure that a consistent version of Spring AI is used throughout the entire project. Refer to the Dependency Management section to add the Spring AI BOM to your build system.

Auto-configuration

Spring AI 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information.

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

Spring AI provides Spring Boot auto-configuration for the Mistral AI Chat Client. To enable it add the following dependency to your project’s Maven pom.xml file:

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

或添加到 Gradle build.gradle 构建文件中。

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-mistral-ai'
}
  1. 参见 Dependency Management 部分,将 Spring AI BOM 添加到你的构建文件中。

Refer to the Dependency Management section to add the Spring AI BOM to your build file.

Chat Properties

Retry Properties

前缀 spring.ai.retry 用作属性前缀,可让您配置 Mistral AI 聊天模型的重试机制。

The prefix spring.ai.retry is used as the property prefix that lets you configure the retry mechanism for the Mistral AI chat model.

Property Description Default

spring.ai.retry.max-attempts

Maximum number of retry attempts.

10

spring.ai.retry.backoff.initial-interval

Initial sleep duration for the exponential backoff policy.

2 sec.

spring.ai.retry.backoff.multiplier

Backoff interval multiplier.

5

spring.ai.retry.backoff.max-interval

Maximum backoff duration.

3 min.

spring.ai.retry.on-client-errors

If false, throw a NonTransientAiException, and do not attempt retry for 4xx client error codes

false

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

List of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException).

empty

spring.ai.retry.on-http-codes

List of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException).

empty

Connection Properties

前缀 spring.ai.mistralai 用作属性前缀,使你可以连接到 OpenAI。

The prefix spring.ai.mistralai is used as the property prefix that lets you connect to OpenAI.

Property Description Default

spring.ai.mistralai.base-url

The URL to connect to

[role="bare"]https://api.mistral.ai

spring.ai.mistralai.api-key

The API Key

-

Configuration Properties

聊天自动配置的启用和禁用现在通过前缀为 spring.ai.model.chat 的顶级属性进行配置。

Enabling and disabling of the chat auto-configurations are now configured via top level properties with the prefix spring.ai.model.chat.

要启用,请设置 spring.ai.model.chat=mistral(默认已启用)

To enable, spring.ai.model.chat=mistral (It is enabled by default)

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

To disable, spring.ai.model.chat=none (or any value which doesn’t match mistral)

此更改旨在允许配置多个模型。

This change is done to allow configuration of multiple models.

前缀 spring.ai.mistralai.chat 是属性前缀,可让您配置 Mistral AI 的聊天模型实现。

The prefix spring.ai.mistralai.chat is the property prefix that lets you configure the chat model implementation for Mistral AI.

Property Description Default

spring.ai.mistralai.chat.enabled (Removed and no longer valid)

Enable Mistral AI chat model.

true

spring.ai.model.chat

Enable Mistral AI chat model.

mistral

spring.ai.mistralai.chat.base-url

Optional override for the spring.ai.mistralai.base-url property to provide chat-specific URL.

-

spring.ai.mistralai.chat.api-key

Optional override for the spring.ai.mistralai.api-key to provide chat-specific API Key.

-

spring.ai.mistralai.chat.options.model

This is the Mistral AI Chat model to use

open-mistral-7b, open-mixtral-8x7b, open-mixtral-8x22b, mistral-small-latest, mistral-large-latest

spring.ai.mistralai.chat.options.temperature

The sampling temperature to use that controls the apparent creativity of generated completions. Higher values will make output more random while lower values will make results more focused and deterministic. It is not recommended to modify temperature and top_p for the same completions request as the interaction of these two settings is difficult to predict.

0.8

spring.ai.mistralai.chat.options.maxTokens

The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model’s context length.

-

spring.ai.mistralai.chat.options.safePrompt

Indicates whether to inject a security prompt before all conversations.

false

spring.ai.mistralai.chat.options.randomSeed

This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result.

-

spring.ai.mistralai.chat.options.stop

Stop generation if this token is detected. Or if one of these tokens is detected when providing an array.

-

spring.ai.mistralai.chat.options.topP

An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both.

-

spring.ai.mistralai.chat.options.responseFormat

An object specifying the format that the model must output. Setting to { "type": "json_object" } enables JSON mode, which guarantees the message the model generates is valid JSON.

-

spring.ai.mistralai.chat.options.tools

A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for.

-

spring.ai.mistralai.chat.options.toolChoice

Controls which (if any) function is called by the model. none means the model will not call a function and instead generates a message. auto means the model can pick between generating a message or calling a function. Specifying a particular function via {"type: "function", "function": {"name": "my_function"}} forces the model to call that function. none is the default when no functions are present. auto is the default if functions are present.

-

spring.ai.mistralai.chat.options.functions

List of functions, identified by their names, to enable for function calling in a single prompt requests. Functions with those names must exist in the functionCallbacks registry.

-

spring.ai.mistralai.chat.options.functionCallbacks

Mistral AI Tool Function Callbacks to register with the ChatModel.

-

spring.ai.mistralai.chat.options.proxy-tool-calls

If true, the Spring AI will not handle the function calls internally, but will proxy them to the client. Then is the client’s responsibility to handle the function calls, dispatch them to the appropriate function, and return the results. If false (the default), the Spring AI will handle the function calls internally. Applicable only for chat models with function calling support

false

您可以为 ChatModelEmbeddingModel 实现覆盖通用的 spring.ai.mistralai.base-urlspring.ai.mistralai.api-key 。如果设置了 spring.ai.mistralai.chat.base-urlspring.ai.mistralai.chat.api-key 属性,它们将优先于通用属性。如果您希望为不同的模型和不同的模型端点使用不同的 Mistral AI 账户,这将非常有用。

You can override the common spring.ai.mistralai.base-url and spring.ai.mistralai.api-key for the ChatModel and EmbeddingModel implementations. The spring.ai.mistralai.chat.base-url and spring.ai.mistralai.chat.api-key properties, if set, take precedence over the common properties. This is useful if you want to use different Mistral AI accounts for different models and different model endpoints.

所有以 spring.ai.mistralai.chat.options 为前缀的属性都可以在运行时通过向 Prompt 调用添加请求特定的 Runtime Options 来覆盖。

All properties prefixed with spring.ai.mistralai.chat.options can be overridden at runtime by adding request-specific Runtime Options to the Prompt call.

Runtime Options

MistralAiChatOptions.java 提供了模型配置,例如要使用的模型、温度、频率惩罚等。

The MistralAiChatOptions.java provides model configurations, such as the model to use, the temperature, the frequency penalty, etc.

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

On start-up, the default options can be configured with the MistralAiChatModel(api, options) constructor or the spring.ai.mistralai.chat.options.* properties.

在运行时,你可以通过向 Prompt 调用添加新的、请求特定的选项来覆盖默认选项。例如,要覆盖特定请求的默认模型和温度:

At run-time, you can override the default options by adding new, request-specific options to the Prompt call. For example, to override the default model and temperature for a specific request:

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 实例。

In addition to the model specific MistralAiChatOptions you can use a portable ChatOptions instance, created with ChatOptionsBuilder#builder().

Function Calling

您可以使用 MistralAiChatModel 注册自定义 Java 函数,并让 Mistral AI 模型智能地选择输出一个 JSON 对象,其中包含调用一个或多个已注册函数的参数。这是一种将 LLM 功能与外部工具和 API 连接起来的强大技术。阅读更多关于 Tool Calling 的信息。

You can register custom Java functions with the MistralAiChatModel and have the Mistral AI model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions. This is a powerful technique to connect the LLM capabilities with external tools and APIs. Read more about Tool Calling.

Multimodal

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

Multimodality refers to a model’s ability to simultaneously understand and process information from various sources, including text, images, audio, and other data formats. Mistral AI supports text and vision modalities.

Vision

提供视觉多模态支持的 Mistral AI 模型包括 pixtral-large-latest 。有关更多信息,请参阅 Vision 指南。

Mistral AI models that offer vision multimodal support include pixtral-large-latest. Refer to the Vision guide for more information.

Mistral AI User Message API 可以在消息中包含 base64 编码的图像列表或图像 URL。Spring AI 的 Message 接口通过引入 Media 类型来促进多模态 AI 模型。此类型包含有关消息中媒体附件的数据和详细信息,它利用 Spring 的 org.springframework.util.MimeType 和用于原始媒体数据的 org.springframework.core.io.Resource

The Mistral AI User Message API can incorporate a list of base64-encoded images or image urls with the message. Spring AI’s Message interface facilitates multimodal AI models by introducing the Media type. This type encompasses data and details regarding media attachments in messages, utilizing Spring’s org.springframework.util.MimeType and a org.springframework.core.io.Resource for the raw media data.

下面是摘自 MistralAiChatModelIT.java 的代码示例,展示了用户文本与图像的融合。

Below is a code example excerpted from MistralAiChatModelIT.java, illustrating the fusion of user text with an image.

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:

or the image URL equivalent:

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

您也可以传递多张图像。

You can pass multiple images as well.

该示例展示了一个模型将 multimodal.test.png 图像作为输入:

The example shows a model taking as an input the multimodal.test.png image:

multimodal.test

以及文本消息“解释一下你在这张图片上看到了什么?”,并生成如下响应:

along with the text message "Explain what do you see on this picture?", and generating a response like this:

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 Compatibility

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 KEY

Mistral is OpenAI API-compatible and you can use the Spring AI OpenAI client to talk to Mistrial. For this, you need to configure the OpenAI base URL to the Mistral AI platform: spring.ai.openai.chat.base-url=https://api.mistral.ai, and select a Mistral model: spring.ai.openai.chat.options.model=mistral-small-latest and set the Mistral AI API key: spring.ai.openai.chat.api-key=<YOUR MISTRAL API KEY.

查看 MistralWithOpenAiChatModelIT.java 测试,了解通过 Spring AI OpenAI 使用 Mistral 的示例。

Check the MistralWithOpenAiChatModelIT.java tests for examples of using Mistral over Spring AI OpenAI.

Sample Controller (Auto-configuration)

Create 一个新的 Spring Boot 项目,并将 spring-ai-starter-model-mistral-ai 添加到您的 pom(或 gradle)依赖项中。

Create a new Spring Boot project and add the spring-ai-starter-model-mistral-ai to your pom (or gradle) dependencies.

src/main/resources 目录下添加一个 application.properties 文件,以启用和配置 Mistral AI 聊天模型:

Add a application.properties file under the src/main/resources directory to enable and configure the Mistral AI chat model:

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 凭据。

Replace the api-key with your Mistral AI credentials.

这将创建一个您可以注入到您的类中的 MistralAiChatModel 实现。这是一个使用聊天模型进行文本生成的简单 @RestController 类的示例。

This will create a MistralAiChatModel implementation that you can inject into your classes. Here is an example of a simple @RestController class that uses the chat model for text generations.

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

Manual Configuration

MistralAiChatModel 实现了 ChatModelStreamingChatModel ,并使用 Low-level MistralAiApi Client 连接到 Mistral AI 服务。

The MistralAiChatModel implements the ChatModel and StreamingChatModel and uses the Low-level MistralAiApi Client to connect to the Mistral AI service.

spring-ai-mistral-ai 依赖项添加到您的项目的 Maven pom.xml 文件中:

Add the spring-ai-mistral-ai dependency to your project’s Maven pom.xml file:

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

或添加到 Gradle build.gradle 构建文件中。

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-mistral-ai'
}
  1. 参见 Dependency Management 部分,将 Spring AI BOM 添加到你的构建文件中。

Refer to the Dependency Management section to add the Spring AI BOM to your build file.

接下来,创建一个 MistralAiChatModel 并将其用于文本生成:

Next, create a MistralAiChatModel and use it for text generations:

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 是一个流畅的选项构建器。

The MistralAiChatOptions provides the configuration information for the chat requests. The MistralAiChatOptions.Builder is a fluent options-builder.

Low-level MistralAiApi Client

MistralAiApi提供了一个用于 Mistral AI API的轻量级 Java 客户端。

The MistralAiApi provides is lightweight Java client for Mistral AI API.

这是一个简单的代码片段,展示了如何以编程方式使用 API:

Here is a simple snippet showing how to use the API programmatically:

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。

Follow the MistralAiApi.java's JavaDoc for further information.

MistralAiApi Samples