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 金鑰 值。匯出環境變數是設定該組態屬性的一種方式

export SPRING_AI_MISTRALAI_API_KEY=<INSERT KEY HERE>

新增儲存庫和 BOM

Spring AI 成品發佈在 Spring Milestone 和 Snapshot 儲存庫中。請參閱 儲存庫 章節,將這些儲存庫新增至您的建置系統。

為了協助進行相依性管理,Spring AI 提供了 BOM(物料清單),以確保在整個專案中使用一致的 Spring AI 版本。請參閱 相依性管理 章節,將 Spring AI BOM 新增至您的建置系統。

自動組態

Spring AI 為 Mistral AI 聊天用戶端提供 Spring Boot 自動組態。若要啟用它,請將以下相依性新增至您的專案的 Maven pom.xml 檔案

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

或新增至您的 Gradle build.gradle 建置檔案。

dependencies {
    implementation 'org.springframework.ai:spring-ai-mistral-ai-spring-boot-starter'
}
請參閱 相依性管理 章節,將 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 用作屬性前綴,可讓您連線至 OpenAI。

屬性 描述 預設值

spring.ai.mistralai.base-url

要連線的 URL

api.mistral.ai

spring.ai.mistralai.api-key

API 金鑰

-

組態屬性

前綴 spring.ai.mistralai.chat 是屬性前綴,可讓您為 Mistral AI 組態聊天模型實作。

屬性 描述 預設值

spring.ai.mistralai.chat.enabled

啟用 Mistral AI 聊天模型。

true

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-7bopen-mixtral-8x7bopen-mixtral-8x22bmistral-small-latestmistral-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

一種替代使用溫度的取樣方法,稱為核心取樣,其中模型會考量具有 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()
            .withModel(MistralAiApi.ChatModel.LARGE.getValue())
            .withTemperature(0.5)
        .build()
    ));
除了模型特定的 MistralAiChatOptions 之外,您還可以使用可移植的 ChatOptions 實例,使用 ChatOptionsBuilder#builder() 建立。

函數呼叫

您可以向 MistralAiChatModel 註冊自訂 Java 函數,並讓 Mistral AI 模型智慧地選擇輸出包含引數的 JSON 物件,以呼叫一個或多個已註冊的函數。這是一種將 LLM 功能與外部工具和 API 連接的強大技術。請閱讀 Mistral AI 函數呼叫 以深入了解。

OpenAI API 相容性

Mistral 與 OpenAI API 相容,您可以使用 Spring AI OpenAI 用戶端來與 Mistrial 通訊。為此,您需要將 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

請查看 MistralWithOpenAiChatModelIT.java 測試,以取得透過 Spring AI OpenAI 使用 Mistral 的範例。

範例控制器 (自動組態)

建立 新的 Spring Boot 專案,並將 spring-ai-mistral-ai-spring-boot-starter 新增至您的 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()
                .withModel(MistralAiApi.ChatModel.LARGE.getValue())
                .withTemperature(0.4)
                .withMaxTokens(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 提供用於 Mistral 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 範例