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 語言模型。請在 Mistral AI 註冊頁面 建立賬戶,並在 API 金鑰頁面 生成令牌。Spring AI 專案定義了一個名為 spring.ai.mistralai.api-key 的配置屬性,您應該將其設定為從 console.mistral.ai 獲取的 API Key 值。匯出環境變數是設定該配置屬性的一種方式。

export SPRING_AI_MISTRALAI_API_KEY=<INSERT KEY HERE>

新增倉庫和 BOM

Spring AI 的 artifacts 釋出在 Maven Central 和 Spring Snapshot 倉庫中。請參考倉庫部分,將這些倉庫新增到您的構建系統。

為了便於依賴管理,Spring AI 提供了一個 BOM(物料清單),以確保整個專案中使用的 Spring AI 版本一致。請參考依賴管理部分,將 Spring AI BOM 新增到您的構建系統。

自動配置

Spring AI 自動配置、starter 模組的 artifact 名稱發生了重大變化。請參考升級注意事項瞭解更多資訊。

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,則丟擲 NonTransientAiException,且不對 4xx 客戶端錯誤程式碼嘗試重試

false

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

不應觸發重試的 HTTP 狀態程式碼列表(例如,丟擲 NonTransientAiException)。

spring.ai.retry.on-http-codes

應觸發重試的 HTTP 狀態程式碼列表(例如,丟擲 TransientAiException)。

連線屬性

字首 spring.ai.mistralai 用作屬性字首,可讓您連線到 Mistral AI。

屬性 描述 預設值

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

spring.ai.mistralai.chat.options.temperature

用於控制生成補全的感知創造性的取樣溫度。值越高,輸出越隨機;值越低,結果越集中且確定。不建議在同一補全請求中同時修改 temperaturetop_p,因為這兩個設定的互動作用難以預測。

0.8

spring.ai.mistralai.chat.options.maxTokens

聊天補全中生成的最大令牌數。輸入令牌和生成令牌的總長度受模型上下文長度的限制。

-

spring.ai.mistralai.chat.options.safePrompt

指示是否在所有對話前注入安全提示。

false

spring.ai.mistralai.chat.options.randomSeed

此功能處於 Beta 階段。如果指定此項,我們的系統將盡力以確定性方式取樣,以便使用相同種子和引數的重複請求應返回相同的結果。

-

spring.ai.mistralai.chat.options.stop

如果檢測到此令牌,則停止生成。或者在提供陣列時,如果檢測到這些令牌中的一個,則停止生成。

-

spring.ai.mistralai.chat.options.topP

一種替代溫度取樣的方案,稱為核取樣 (nucleus sampling),模型考慮具有 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

您可以為 ChatModelEmbeddingModel 實現覆蓋公共的 spring.ai.mistralai.base-urlspring.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 提供了模型配置,例如要使用的模型、溫度、頻率懲罰等。

啟動時,可以使用 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 物件。這是將 LLM 能力與外部工具和 API 連線起來的強大技術。瞭解更多關於Mistral AI 函式呼叫的資訊。

多模態

多模態是指模型能夠同時理解和處理來自各種源(包括文字、影像、音訊和其他資料格式)的資訊。Mistral AI 支援文字和視覺模態。

視覺

提供視覺多模態支援的 Mistral AI 模型包括 pixtral-large-latest。有關更多資訊,請參考視覺指南。

Mistral AI 的使用者訊息 API 可以在訊息中包含 base64 編碼的影像列表或影像 URL。Spring AI 的Message 介面透過引入Media 型別,促進了多模態 AI 模型的使用。該型別包含訊息中媒體附件的資料和詳細資訊,利用 Spring 的 org.springframework.util.MimeTypeorg.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.springframework.tw/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 影像作為輸入

Multimodal Test Image

以及文字訊息“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 通訊。為此,您需要將 OpenAI 的 base 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
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 服務。

spring-ai-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 是一個流式選項構建器。

底層 MistralAiApi 客戶端

MistralAiApi 提供了一個輕量級的 Java 客戶端用於Mistral AI API

以下是一個簡單的程式碼片段,展示瞭如何以程式設計方式使用該 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 示例