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 Keys頁面生成令牌。
Spring AI專案定義了一個名為spring.ai.mistralai.api-key的配置屬性,您應該將其設定為從console.mistral.ai獲得的API Key的值。
您可以在 application.properties 檔案中設定此配置屬性
spring.ai.mistralai.api-key=<your-mistralai-api-key>
為了增強處理 API 金鑰等敏感資訊時的安全性,您可以使用 Spring 表示式語言 (SpEL) 來引用自定義環境變數
# 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>
您還可以在應用程式程式碼中以程式設計方式設定此配置
// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("MISTRALAI_API_KEY");
自動配置
|
Spring AI 自動配置、啟動模組的工件名稱發生了重大變化。請參閱 升級說明 以獲取更多資訊。 |
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,並且不嘗試重試 |
假 |
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 |
|
spring.ai.mistralai.api-key |
API 金鑰 |
- |
配置屬性
|
聊天自動配置的啟用和停用現在透過以 要啟用,請設定 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.chat.api-key |
用於覆蓋 |
- |
spring.ai.mistralai.chat.options.model |
這是要使用的Mistral AI聊天模型 |
|
spring.ai.mistralai.chat.options.temperature |
用於控制生成補全的明顯創造性的取樣溫度。較高的值將使輸出更隨機,而較低的值將使結果更集中和確定性。不建議在同一補全請求中修改 |
0.8 |
spring.ai.mistralai.chat.options.maxTokens |
在聊天補全中生成的最大令牌數。輸入令牌和生成令牌的總長度受模型上下文長度的限制。 |
- |
spring.ai.mistralai.chat.options.safePrompt |
指示是否在所有對話之前注入安全提示。 |
假 |
spring.ai.mistralai.chat.options.randomSeed |
此功能處於 Beta 階段。如果指定,我們的系統將盡力確定性地取樣,以便具有相同種子和引數的重複請求應返回相同的結果。 |
- |
spring.ai.mistralai.chat.options.stop |
如果檢測到此令牌,則停止生成。或者如果提供陣列時檢測到其中一個令牌。 |
- |
spring.ai.mistralai.chat.options.topP |
溫度取樣的替代方法,稱為核心取樣,其中模型考慮具有top_p機率質量的令牌結果。因此0.1表示只考慮構成前10%機率質量的令牌。我們通常建議更改此項或 |
- |
spring.ai.mistralai.chat.options.responseFormat |
指定模型必須輸出的格式的物件。設定為 |
- |
spring.ai.mistralai.chat.options.tools |
模型可以呼叫的工具列表。目前,只支援函式作為工具。使用此項提供模型可以生成 JSON 輸入的函式列表。 |
- |
spring.ai.mistralai.chat.options.toolChoice |
控制模型呼叫哪個(如果有)函式。 |
- |
spring.ai.mistralai.chat.options.tool-names |
工具列表,透過其名稱標識,用於在單個提示請求中啟用函式呼叫。具有這些名稱的工具必須存在於 ToolCallback 登錄檔中。 |
- |
spring.ai.mistralai.chat.options.tool-callbacks |
要註冊到 ChatModel 的工具回撥。 |
- |
spring.ai.mistralai.chat.options.internal-tool-execution-enabled |
如果為 false,Spring AI 將不會在內部處理工具呼叫,而是將其代理到客戶端。然後,客戶端負責處理工具呼叫,將其分派到適當的函式,並返回結果。如果為 true(預設),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型 |
true |
您可以為ChatModel和EmbeddingModel實現覆蓋通用的spring.ai.mistralai.base-url和spring.ai.mistralai.api-key。如果設定了spring.ai.mistralai.chat.base-url和spring.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之外,您還可以使用可移植的ChatOptions例項,該例項透過ChatOptions#builder()建立。 |
函式呼叫
您可以在MistralAiChatModel中註冊自定義Java函式,並讓Mistral AI模型智慧地選擇輸出一個JSON物件,其中包含呼叫一個或多個已註冊函式的引數。這是一種將LLM功能與外部工具和API連線的強大技術。閱讀更多關於工具呼叫的資訊。
多模態
多模態是指模型同時理解和處理來自各種來源(包括文字、影像、音訊和其他資料格式)資訊的能力。Mistral AI支援文字和視覺模態。
視覺
支援視覺多模態的Mistral AI模型包括pixtral-large-latest。有關更多資訊,請參閱視覺指南。
Mistral AI 使用者訊息API可以將base64編碼的影像列表或影像URL與訊息一起包含。Spring AI的Message介面透過引入Media型別來促進多模態AI模型。該型別包含訊息中媒體附件的資料和詳細資訊,使用Spring的org.springframework.util.MimeType和org.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 影像作為輸入
以及文字訊息“解釋你在這張圖片上看到了什麼?”,並生成如下響應
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平臺: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實現了ChatModel和StreamingChatModel,並使用低階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為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 示例
-
MistralAiApiIT.java測試提供了一些使用輕量級庫的通用示例。
-
PaymentStatusFunctionCallingIT.java測試展示瞭如何使用低階API呼叫工具函式。基於Mistral AI函式呼叫教程。
先決條件
您需要使用Mistral AI建立一個API,才能訪問Mistral AI語言模型。在Mistral AI註冊頁面建立賬戶,並在API Keys頁面生成令牌。
新增依賴項
要使用Mistral AI OCR API,您需要將spring-ai-mistral-ai依賴項新增到您的專案中。
<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'
}
低階MistralOcrApi客戶端
MistralOcrApi為Mistral AI OCR API提供了一個輕量級Java客戶端。
這裡有一個簡單的程式碼片段,展示瞭如何以程式設計方式使用 API
MistralOcrApi mistralAiApi = new MistralOcrApi(System.getenv("MISTRAL_AI_API_KEY"));
String documentUrl = "https://arxiv.org/pdf/2201.04234";
MistralOcrApi.OCRRequest request = new MistralOcrApi.OCRRequest(
MistralOcrApi.OCRModel.MISTRAL_OCR_LATEST.getValue(), "test_id",
new MistralOcrApi.OCRRequest.DocumentURLChunk(documentUrl), List.of(0, 1, 2), true, 5, 50);
ResponseEntity<MistralOcrApi.OCRResponse> response = mistralAiApi.ocr(request);
有關更多資訊,請遵循MistralOcrApi.java的JavaDoc。
MistralOcrApi 示例
-
MistralOcrApiIT.java測試提供了一些使用輕量級庫的通用示例。