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.

Prerequisites

你需要使用 MistralAI 创建一个 API 才能访问 Mistral AI 语言模型。在 MistralAI registration page 创建一个帐户,并在 API Keys page 上生成令牌。Spring AI 项目定义了一个名为 spring.ai.mistralai.api-key 的配置属性,你应将其设置为从 console.mistral.ai 获得的 API Key 的值。导出环境变量是一种设置该配置属性的方法:

You will need to create an API with MistralAI to access Mistral AI language models. Create an account at MistralAI registration page and generate the token on the API Keys page. 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. Exporting an environment variable is one way to set that configuration property:

export SPRING_AI_MISTRALAI_API_KEY=<INSERT KEY HERE>

Add Repositories and BOM

Spring AI 工件发布在 Spring 里程碑和快照存储库中。请参考 Repositories 部分将这些存储库添加到你的构建系统。

Spring AI artifacts are published in Spring Milestone and Snapshot repositories. Refer to the 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 为 MistralAI 聊天客户端提供 Spring Boot 自动配置。若要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件:

Spring AI provides Spring Boot auto-configuration for the MistralAI 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-mistral-ai-spring-boot-starter</artifactId>
</dependency>

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

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-mistral-ai-spring-boot-starter'
}
  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 client.

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

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.mistralai.chat 是允许你配置 MistralAI 的聊天客户端实现的属性前缀。

The prefix spring.ai.mistralai.chat is the property prefix that lets you configure the chat client implementation for MistralAI.

Property Description Default

spring.ai.mistralai.chat.enabled

Enable MistralAI chat client.

true

spring.ai.mistralai.chat.base-url

Optional overrides the spring.ai.mistralai.base-url to provide chat specific url

-

spring.ai.mistralai.chat.api-key

Optional overrides the spring.ai.mistralai.api-key to provide chat specific api-key

-

spring.ai.mistralai.chat.options.model

This is the MistralAI Chat model to use

open-mistral-7b, open-mixtral-8x7b, mistral-small-latest, mistral-medium-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

Up to 4 sequences where the API will stop generating further tokens.

-

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

MistralAI Tool Function Callbacks to register with the ChatClient.

-

你可以重写通用 spring.ai.mistralai.base-urlspring.ai.mistralai.api-key 以供 ChatClientEmbeddingClient 实现。如果设置 spring.ai.mistralai.chat.base-urlspring.ai.mistralai.chat.api-key 属性,则这些属性优先于通用属性。如果你希望对不同的模型和不同的模型端点使用不同的 MistralAI 帐户,这会非常有用。

You can override the common spring.ai.mistralai.base-url and spring.ai.mistralai.api-key for the ChatClient and EmbeddingClient 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 MistralAI accounts for different models and different model endpoints.

带有 spring.ai.mistralai.chat.options 前缀的所有属性都可以通过将特定请求 Chat Options 添加到 Prompt 调用在运行时进行覆盖。

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

Chat Options

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

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

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

On start-up, the default options can be configured with the MistralAiChatClient(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 = chatClient.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        MistralAiChatOptions.builder()
            .withModel(MistralAiApi.ChatModel.LARGE.getValue())
            .withTemperature(0.5f)
        .build()
    ));

除了特定 MistralAiChatOptions 的模型之外,您还可以使用使用 ChatOptionsBuilder#builder() 创建的可移植 ChatOptions 实例。

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

Sample Controller (Auto-configuration)

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

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

src/main/resources 目录下添加一个 application.properties 文件,以启用和配置 OpenAI Chat 客户端:

Add a application.properties file, under the src/main/resources directory, to enable and configure the OpenAi Chat client:

spring.ai.mistralai.api-key=YOUR_API_KEY
spring.ai.mistralai.chat.options.model=mistral-medium
spring.ai.mistralai.chat.options.temperature=0.7

使用您的 OpenAI 凭据替换 api-key

replace the api-key with your OpenAI credentials.

这将创建一个 MistralAiChatClient 实现,你可以将其注入到你的类中。以下是一个简单的 @Controller 类的示例,该类使用聊天客户端进行文本生成。

This will create a MistralAiChatClient implementation that you can inject into your class. Here is an example of a simple @Controller class that uses the chat client for text generations.

@RestController
public class ChatController {

    private final MistralAiChatClient chatClient;

    @Autowired
    public ChatController(MistralAiChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", chatClient.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 chatClient.stream(prompt);
    }
}

Manual Configuration

MistralAiChatClient实现`ChatClient`和`StreamingChatClient`,并且使用Low-level MistralAiApi Client连接到MistralAI服务。

The MistralAiChatClient implements the ChatClient and StreamingChatClient and uses the Low-level MistralAiApi Client to connect to the MistralAI service.

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

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

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

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

or to your Gradle build.gradle build file.

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

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

接下来,创建一个 MistralAiChatClient 并用它进行文本生成:

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

var mistralAiApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY"));

var chatClient = new MistralAiChatClient(mistralAiApi, MistralAiChatOptions.builder()
                .withModel(MistralAiApi.ChatModel.LARGE.getValue())
                .withTemperature(0.4f)
                .withMaxToken(200)
                .build());

ChatResponse response = chatClient.call(
    new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = chatClient.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 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 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 = mistralAiApi.chatCompletionEntity(
    new ChatCompletionRequest(List.of(chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8f, false));

// Streaming request
Flux<ChatCompletionChunk> streamResponse = mistralAiApi.chatCompletionStream(
        new ChatCompletionRequest(List.of(chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8f, true));

有关详细信息,请遵循 MistralAiApi.java的 JavaDoc。

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

MistralAiApi Samples