This version is still in development and is not considered stable yet. For the latest snapshot version, please use Spring AI 1.0.0-SNAPSHOT!spring-doc.cn

OpenAI Embeddings

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.spring-doc.cn

Prerequisites

You will need to create an API with OpenAI to access OpenAI embeddings models.spring-doc.cn

Create an account at OpenAI signup page and generate the token on the API Keys page. 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. Exporting an environment variable is one way to set that configuration property:spring-doc.cn

export SPRING_AI_OPENAI_API_KEY=<INSERT KEY HERE>

Add Repositories and BOM

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

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.spring-doc.cn

Auto-configuration

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

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

or to your Gradle build.gradle build file.spring-doc.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
Refer to the Dependency Management section to add the Spring AI BOM to your build file.

Embedding Properties

Retry Properties

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

Property Description Default

spring.ai.retry.max-attemptsspring-doc.cn

Maximum number of retry attempts.spring-doc.cn

10spring-doc.cn

spring.ai.retry.backoff.initial-intervalspring-doc.cn

Initial sleep duration for the exponential backoff policy.spring-doc.cn

2 sec.spring-doc.cn

spring.ai.retry.backoff.multiplierspring-doc.cn

Backoff interval multiplier.spring-doc.cn

5spring-doc.cn

spring.ai.retry.backoff.max-intervalspring-doc.cn

Maximum backoff duration.spring-doc.cn

3 min.spring-doc.cn

spring.ai.retry.on-client-errorsspring-doc.cn

If false, throw a NonTransientAiException, and do not attempt retry for 4xx client error codesspring-doc.cn

falsespring-doc.cn

spring.ai.retry.exclude-on-http-codesspring-doc.cn

List of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException).spring-doc.cn

emptyspring-doc.cn

spring.ai.retry.on-http-codesspring-doc.cn

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

emptyspring-doc.cn

Connection Properties

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

Property Description Default

spring.ai.openai.base-urlspring-doc.cn

The URL to connect tospring-doc.cn

https://api.openai.comspring-doc.cn

spring.ai.openai.api-keyspring-doc.cn

The API Keyspring-doc.cn

-spring-doc.cn

spring.ai.openai.organization-idspring-doc.cn

Optionally you can specify which organization used for an API request.spring-doc.cn

-spring-doc.cn

spring.ai.openai.project-idspring-doc.cn

Optionally, you can specify which project is used for an API request.spring-doc.cn

-spring-doc.cn

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

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

Property Description Default

spring.ai.openai.embedding.enabledspring-doc.cn

Enable OpenAI embedding model.spring-doc.cn

truespring-doc.cn

spring.ai.openai.embedding.base-urlspring-doc.cn

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

-spring-doc.cn

spring.ai.openai.chat.embeddings-pathspring-doc.cn

The path to append to the base-urlspring-doc.cn

/v1/embeddingsspring-doc.cn

spring.ai.openai.embedding.api-keyspring-doc.cn

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

-spring-doc.cn

spring.ai.openai.embedding.organization-idspring-doc.cn

Optionally you can specify which organization used for an API request.spring-doc.cn

-spring-doc.cn

spring.ai.openai.embedding.project-idspring-doc.cn

Optionally, you can specify which project is used for an API request.spring-doc.cn

-spring-doc.cn

spring.ai.openai.embedding.metadata-modespring-doc.cn

Document content extraction mode.spring-doc.cn

EMBEDspring-doc.cn

spring.ai.openai.embedding.options.modelspring-doc.cn

The model to usespring-doc.cn

text-embedding-ada-002 (other options: text-embedding-3-large, text-embedding-3-small)spring-doc.cn

spring.ai.openai.embedding.options.encodingFormatspring-doc.cn

The format to return the embeddings in. Can be either float or base64.spring-doc.cn

-spring-doc.cn

spring.ai.openai.embedding.options.userspring-doc.cn

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

-spring-doc.cn

spring.ai.openai.embedding.options.dimensionsspring-doc.cn

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

-spring-doc.cn

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

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

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

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.spring-doc.cn

For example to override the default model name for a specific request:spring-doc.cn

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

Sample 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-doc.cn

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

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:spring-doc.cn

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

or to your Gradle build.gradle build file.spring-doc.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai'
}
Refer to the Dependency Management section to add the Spring AI BOM to your build file.
The spring-ai-openai dependency provides access also to the OpenAiChatModel. For more information about the OpenAiChatModel refer to the OpenAI Chat Client section.

Next, create an OpenAiEmbeddingModel instance and use it to compute the similarity between two input texts:spring-doc.cn

var openAiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));

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

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

The OpenAiEmbeddingOptions provides the configuration information for the embedding requests. The options class offers a builder() for easy options creation.spring-doc.cn