OpenAI Embeddings

Spring AI 支持 OpenAI 的文本嵌入模型。OpenAI 的文本嵌入衡量了文本字符串之间的相关性。嵌入是一个浮点数向量(列表)。两个向量之间的距离衡量了它们的相关性。距离小表明相关性高,距离大表明相关性低。

Spring AI supports the OpenAI’s text embeddings models. OpenAI’s text embeddings measure the relatedness of text strings. An embedding is a vector (list) of floating point numbers. The distance between two vectors measures their relatedness. Small distances suggest high relatedness and large distances suggest low relatedness.

Prerequisites

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

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

open.bigmodel.cn 创建账户并在 API密钥 上生成令牌。

Create an account at OpenAI signup page and generate the token on the API Keys page.

Spring AI 项目定义了一个名为 spring.ai.openai.api-key 的配置属性,您应该将其设置为从 openai.com 获取的 API 密钥 的值。

The Spring AI project defines a configuration property named spring.ai.openai.api-key that you should set to the value of the API Key obtained from openai.com.

你可以在` application.properties `文件中设置此配置属性:

You can set this configuration property in your application.properties file:

spring.ai.openai.api-key=<your-openai-api-key>

为了在处理API密钥等敏感信息时增强安全性,你可以使用Spring表达式语言(SpEL)引用环境变量:

For enhanced security when handling sensitive information like API keys, you can use Spring Expression Language (SpEL) to reference an environment variable:

# In application.yml
spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
# In your environment or .env file
export OPENAI_API_KEY=<your-openai-api-key>

你也可以在应用程序代码中以编程方式设置此配置:

You can also set this configuration programmatically in your application code:

// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("OPENAI_API_KEY");

Add Repositories and BOM

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

Spring AI artifacts are published in Maven Central and Spring Snapshot repositories. Refer to the Artifact 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 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information.

Spring AI 为 OpenAI 嵌入模型提供了 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您的项目的 Maven pom.xml 文件中:

Spring AI provides Spring Boot auto-configuration for the OpenAI Embedding Model. To enable it add the following dependency to your project’s Maven pom.xml file:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

或添加到 Gradle build.gradle 构建文件中。

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
  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.openai.embedding.retry 前缀用作属性前缀,允许您配置 OpenAI 嵌入模型的重试机制。

The prefix spring.ai.retry is used as the property prefix that lets you configure the retry mechanism for the OpenAI Embedding model.

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

spring.ai.retry.on-http-codes

List of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException).

empty

Connection Properties

spring.ai.openai 前缀用作可让你连接到 Open AI 的属性前缀。

The prefix spring.ai.openai is used as the property prefix that lets you connect to OpenAI.

Property Description Default

spring.ai.openai.base-url

The URL to connect to

https://api.openai.com

spring.ai.openai.api-key

The API Key

-

spring.ai.openai.organization-id

Optionally you can specify which organization used for an API request.

-

spring.ai.openai.project-id

Optionally, you can specify which project is used for an API request.

-

对于属于多个组织(或通过其旧版用户 API 密钥访问其项目)的用户,您可以选择指定用于 API 请求的组织和项目。这些 API 请求的使用将计为指定组织和项目的使用。

For users that belong to multiple organizations (or are accessing their projects through their legacy user API key), optionally, you can specify which organization and project is used for an API request. Usage from these API requests will count as usage for the specified organization and project.

Configuration Properties

嵌入自动配置的启用和禁用现在通过前缀为 spring.ai.azure.openai.embedding 的顶级属性进行配置。

Enabling and disabling of the embedding auto-configurations are now configured via top level properties with the prefix spring.ai.model.embedding.

要启用,spring.ai.model.embedding=openai(默认已启用)

To enable, spring.ai.model.embedding=openai (It is enabled by default)

要禁用嵌入自动配置,请将 spring.ai.model.embedding 设置为 none(或任何与 openai 不匹配的值)。

To disable, spring.ai.model.embedding=none (or any value which doesn’t match openai)

此更改旨在允许配置多个模型。

This change is done to allow configuration of multiple models.

前缀 ` spring.ai.openai.embedding ` 是用于配置 OpenAI ` EmbeddingModel ` 实现的属性前缀。

The prefix spring.ai.openai.embedding is property prefix that configures the EmbeddingModel implementation for OpenAI.

Property Description Default

spring.ai.openai.embedding.enabled (Required and no longer valid)

Enable OpenAI embedding model.

true

spring.ai.model.embedding

Enable OpenAI embedding model.

openai

spring.ai.openai.embedding.base-url

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

-

spring.ai.openai.embedding.embeddings-path

The path to append to the base-url

/v1/embeddings

spring.ai.openai.embedding.api-key

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

-

spring.ai.openai.embedding.organization-id

Optionally you can specify which organization used for an API request.

-

spring.ai.openai.embedding.project-id

Optionally, you can specify which project is used for an API request.

-

spring.ai.openai.embedding.metadata-mode

Document content extraction mode.

EMBED

spring.ai.openai.embedding.options.model

The model to use

text-embedding-ada-002 (other options: text-embedding-3-large, text-embedding-3-small)

spring.ai.openai.embedding.options.encodingFormat

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

-

spring.ai.openai.embedding.options.user

A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.

-

spring.ai.openai.embedding.options.dimensions

The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.

-

您可以为 ` ChatModel ` 和 ` EmbeddingModel ` 实现覆盖通用的 ` spring.ai.openai.base-url ` 和 ` spring.ai.openai.api-key 。如果设置了 ` `spring.ai.openai.embedding.base-url ` 和 ` spring.ai.openai.embedding.api-key ` 属性,它们将优先于通用属性。同样,如果设置了 ` spring.ai.openai.chat.base-url ` 和 ` spring.ai.openai.chat.api-key ` 属性,它们将优先于通用属性。这在您想为不同模型和不同模型端点使用不同的 OpenAI 帐户时很有用。

You can override the common spring.ai.openai.base-url and spring.ai.openai.api-key for the ChatModel and EmbeddingModel implementations. The spring.ai.openai.embedding.base-url and spring.ai.openai.embedding.api-key properties if set take precedence over the common properties. Similarly, the spring.ai.openai.chat.base-url and spring.ai.openai.chat.api-key properties if set take precedence over the common properties. This is useful if you want to use different OpenAI accounts for different models and different model endpoints.

所有前缀为 spring.ai.openai.embedding.options 的属性可以通过在 EmbeddingRequest 调用中添加一个请求特定的 Runtime Options 来在运行时覆盖。

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

Runtime Options

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

The OpenAiEmbeddingOptions.java provides the OpenAI configurations, such as the model to use and etc.

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

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

在启动时,使用 ` OpenAiEmbeddingModel ` 构造函数设置用于所有嵌入请求的默认选项。在运行时,您可以使用 ` OpenAiEmbeddingOptions ` 实例作为 ` EmbeddingRequest ` 的一部分来覆盖默认选项。

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

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

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

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

Sample Controller

这将创建一个 EmbeddingModel 实现,您可以将其注入到您的类中。这是一个使用 EmbeddingModel 实现的简单 @Controller 类的示例。

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

spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.embedding.options.model=text-embedding-ada-002
@RestController
public class EmbeddingController {

    private final EmbeddingModel embeddingModel;

    @Autowired
    public EmbeddingController(EmbeddingModel embeddingModel) {
        this.embeddingModel = embeddingModel;
    }

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

Manual Configuration

如果您不使用 Spring Boot,可以手动配置 OpenAI 嵌入模型。为此,请将 ` spring-ai-openai ` 依赖项添加到您项目的 Maven ` pom.xml ` 文件中:

If you are not using Spring Boot, you can manually configure the OpenAI Embedding Model. For this add the spring-ai-openai dependency to your project’s Maven pom.xml file:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai</artifactId>
</dependency>

或添加到 Gradle build.gradle 构建文件中。

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai'
}
  1. 参见 Dependency Management 部分,将 Spring AI BOM 添加到你的构建文件中。

Refer to the Dependency Management section to add the Spring AI BOM to your build file.

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

The spring-ai-openai dependency provides access also to the OpenAiChatModel. For more information about the OpenAiChatModel refer to the OpenAI Chat Client section.

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

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

var openAiApi = OpenAiApi.builder()
                .apiKey(System.getenv("OPENAI_API_KEY"))
                .build();

var embeddingModel = new OpenAiEmbeddingModel(
		this.openAiApi,
        MetadataMode.EMBED,
        OpenAiEmbeddingOptions.builder()
                .model("text-embedding-ada-002")
                .user("user-6")
                .build(),
        RetryUtils.DEFAULT_RETRY_TEMPLATE);

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

` OpenAiEmbeddingOptions ` 提供嵌入请求的配置信息。api 和选项类提供 ` builder() ` 以方便创建选项。

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