Mistral AI Embeddings

Spring AI 支持 Mistral AI 的文本词嵌入模型。词嵌入是文本的向量表示,通过其在高维矢量空间中的位置来捕获段落的语义含义。Mistral AI 词嵌入 API 为文本提供尖端的最新词嵌入,可用于许多 NLP 任务。

Spring AI supports the Mistral AI’s text embeddings models. Embeddings are vectorial representations of text that capture the semantic meaning of paragraphs through their position in a high dimensional vector space. Mistral AI Embeddings API offers cutting-edge, state-of-the-art embeddings for text, which can be used for many NLP tasks.

Prerequisites

你需要使用 MistralAI 创建一个 API,以访问 MistralAI 词嵌入模型。

You will need to create an API with MistralAI to access MistralAI embeddings models.

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

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 Milestone 和 Snapshot 存储库中。有关将这些存储库添加到你的构建系统的说明,请参阅 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 Embedding 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.

Embedding 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 Embedding 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 用作允许你连接到 MistralAI 的属性前缀。

The prefix spring.ai.mistralai is used as the property prefix that lets you connect to MistralAI.

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.embedding 前缀是为 MistralAI 配置 EmbeddingClient 实现的属性前缀。

The prefix spring.ai.mistralai.embedding is property prefix that configures the EmbeddingClient implementation for MistralAI.

Property Description Default

spring.ai.mistralai.embedding.enabled

Enable OpenAI embedding client.

true

spring.ai.mistralai.embedding.base-url

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

-

spring.ai.mistralai.embedding.api-key

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

-

spring.ai.mistralai.embedding.metadata-mode

Document content extraction mode.

EMBED

spring.ai.mistralai.embedding.options.model

The model to use

mistral-embed

spring.ai.mistralai.embedding.options.encodingFormat

The format to return the embeddings in. Can be either float or base64.

-

您可以覆盖 ChatClientEmbeddingClient 实现的 spring.ai.mistralai.base-urlspring.ai.mistralai.api-key。如果设置了 spring.ai.mistralai.embedding.base-urlspring.ai.mistralai.embedding.api-key 属性,优先于通用属性。同样,如果设置了 spring.ai.mistralai.embedding.base-urlspring.ai.mistralai.embedding.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.embedding.base-url and spring.ai.mistralai.embedding.api-key properties if set take precedence over the common properties. Similarly, the spring.ai.mistralai.embedding.base-url and spring.ai.mistralai.embedding.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.embedding.options 的属性可以通过在 EmbeddingRequest 调用中添加一个请求特定的 Embedding Options 来在运行时覆盖。

All properties prefixed with spring.ai.mistralai.embedding.options can be overridden at runtime by adding a request specific Embedding Options to the EmbeddingRequest call.

Embedding Options

MistralAiEmbeddingOptions.java 提供 MistralAI 配置,例如使用该模型等。

The MistralAiEmbeddingOptions.java provides the MistralAI configurations, such as the model to use and etc.

还可以使用 spring.ai.mistralai.embedding.options 属性配置默认选项。

The default options can be configured using the spring.ai.mistralai.embedding.options properties as well.

在启动时,使用 MistralAiEmbeddingClient 构造函数设置用于所有嵌入式请求的默认选项。在运行时,你可以使用 EmbeddingRequest 中的 MistralAiEmbeddingOptions 实例覆盖默认选项。

At start-time use the MistralAiEmbeddingClient constructor to set the default options used for all embedding requests. At run-time you can override the default options, using a MistralAiEmbeddingOptions instance as part of your EmbeddingRequest.

例如,要覆盖特定请求的默认模型名称:

For example to override the default model name for a specific request:

EmbeddingResponse embeddingResponse = embeddingClient.call(
    new EmbeddingRequest(List.of("Hello World", "World is big and salvation is near"),
        MistralAiEmbeddingOptions.builder()
            .withModel("Different-Embedding-Model-Deployment-Name")
        .build()));

Sample Controller (Auto-configuration)

这将创建一个 EmbeddingClient 实现,你可以将其注入到你的类中。这里有一个简单的 @Controller 类的示例,它使用 EmbeddingClient 实现。

This will create a EmbeddingClient implementation that you can inject into your class. Here is an example of a simple @Controller class that uses the EmbeddingClient implementation.

spring.ai.mistralai.api-key=YOUR_API_KEY
spring.ai.mistralai.embedding.options.model=mistral-embed
@RestController
public class EmbeddingController {

    private final EmbeddingClient embeddingClient;

    @Autowired
    public EmbeddingController(EmbeddingClient embeddingClient) {
        this.embeddingClient = embeddingClient;
    }

    @GetMapping("/ai/embedding")
    public Map embed(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        var embeddingResponse = this.embeddingClient.embedForResponse(List.of(message));
        return Map.of("embedding", embeddingResponse);
    }
}

Manual Configuration

如果你没有使用 Spring Boot,你可以手动配置 OpenAI Embedding 客户端。为此,将 spring-ai-mistralai 依赖项添加到项目 Maven pom.xml 文件中:

If you are not using Spring Boot, you can manually configure the OpenAI Embedding Client. For this 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.

spring-ai-mistralai 依赖项还提供对 MistralAiChatClient 的访问。有关 MistralAiChatClient 的更多信息,请参阅 MistralAI Chat Client 部分。

The spring-ai-mistralai dependency provides access also to the MistralAiChatClient. For more information about the MistralAiChatClient refer to the MistralAI Chat Client section.

接下来,创建一个 MistralAiEmbeddingClient 实例,并使用它来计算两个输入文本之间的相似性:

Next, create an MistralAiEmbeddingClient instance and use it to compute the similarity between two input texts:

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

var embeddingClient = new MistralAiEmbeddingClient(mistralAiApi,
        MistralAiEmbeddingOptions.builder()
                .withModel("mistral-embed")
                .withEncodingFormat("float")
                .build());

EmbeddingResponse embeddingResponse = embeddingClient
        .embedForResponse(List.of("Hello World", "World is big and salvation is near"));

MistralAiEmbeddingOptions 提供了嵌入式请求的配置信息。该选项类提供了 builder() 以便于创建选项。

The MistralAiEmbeddingOptions provides the configuration information for the embedding requests. The options class offers a builder() for easy options creation.