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

添加存储库和 BOM

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

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

自动配置

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,并且不尝试重试 4xx 客户端错误代码

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.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 Key。

-

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

指示是否在所有对话之前注入安全提示。

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

您可以为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之外,您还可以使用可移植的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.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.org.cn/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

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

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实现了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客户端

MistralAiApiMistral 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 示例

Mistral AI OCR

Spring AI支持Mistral AI的光学字符识别(OCR)。这允许您从文档中提取文本和图像数据。

先决条件

您需要使用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客户端

MistralOcrApiMistral 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 示例

© . This site is unofficial and not affiliated with VMware.