Azure OpenAI Embeddings

Azure 的 OpenAI 扩展了 OpenAI 的功能,为各种任务提供了安全的文本生成和嵌入计算模型:

Azure’s OpenAI extends the OpenAI capabilities, offering safe text generation and Embeddings computation models for various task:

  • 相似嵌入擅长捕捉两篇或多篇文章之间的语义相似性。

  • Similarity embeddings are good at capturing semantic similarity between two or more pieces of text.

  • 文本搜索嵌入有助于衡量较长的文档是否与较短的查询有关。

  • Text search embeddings help measure whether long documents are relevant to a short query.

  • 代码搜索嵌入用于嵌入代码片段和嵌入自然语言搜索查询。

  • Code search embeddings are useful for embedding code snippets and embedding natural language search queries.

Azure OpenAI 嵌入依赖于“余弦相似性”来计算文档和查询之间的相似性。

The Azure OpenAI embeddings rely on cosine similarity to compute similarity between documents and a query.

Prerequisites

Azure OpenAI客户端提供了三种连接选项:使用Azure API密钥、使用OpenAI API密钥或使用Microsoft Entra ID。

The Azure OpenAI client offers three options to connect: using an Azure API key or using an OpenAI API Key, or using Microsoft Entra ID.

Azure API Key & Endpoint

Azure Portal 上的 Azure OpenAI 服务部分中获取 Azure OpenAI endpointapi-key

Obtain your Azure OpenAI endpoint and api-key from the Azure OpenAI Service section on the Azure Portal.

Spring AI定义了两个配置属性:

Spring AI defines two configuration properties:

  1. * spring.ai.azure.openai.api-key:将其设置为从Azure获取的API密钥的值。

  2. spring.ai.azure.openai.api-key: Set this to the value of the API Key obtained from Azure.

  3. * spring.ai.azure.openai.endpoint:将其设置为在Azure中配置模型时获取的端点URL。

  4. spring.ai.azure.openai.endpoint: Set this to the endpoint URL obtained when provisioning your model in Azure.

您可以在`application.properties`或`application.yml`文件中设置这些配置属性:

You can set these configuration properties in your application.properties or application.yml file:

spring.ai.azure.openai.api-key=<your-azure-api-key>
spring.ai.azure.openai.endpoint=<your-azure-endpoint-url>

如果您更喜欢使用环境变量来存储敏感信息(如API密钥),您可以在配置中使用Spring表达式语言(SpEL):

If you prefer to use environment variables for sensitive information like API keys, you can use Spring Expression Language (SpEL) in your configuration:

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

OpenAI Key

要使用 OpenAI 服务(而非 Azure)进行身份验证,请提供一个 OpenAI API 密钥。这将自动将端点设置为 https://api.openai.com/v1

To authenticate with the OpenAI service (not Azure), provide an OpenAI API key. This will automatically set the endpoint to [role="bare"]https://api.openai.com/v1.

当使用此方法时,请将 spring.ai.openai.chat.model 属性设置为您希望使用的模型名称。

When using this approach, set the spring.ai.azure.openai.chat.options.deployment-name property to the name of the OpenAI model you wish to use.

在您的应用程序配置中:

In your application configuration:

spring.ai.azure.openai.openai-api-key=<your-azure-openai-key>
spring.ai.azure.openai.chat.options.deployment-name=<openai-model-name>

使用 SpEL 的环境变量:

Using environment variables with SpEL:

# In application.yml
spring:
  ai:
    azure:
      openai:
        openai-api-key: ${AZURE_OPENAI_API_KEY}
        chat:
          options:
            deployment-name: ${OPENAI_MODEL_NAME}
# In your environment or .env file
export AZURE_OPENAI_API_KEY=<your-openai-key>
export OPENAI_MODEL_NAME=<openai-model-name>

Microsoft Entra ID

对于使用 Microsoft Entra ID(以前称为 Azure Active Directory)进行无密钥身份验证,请设置 spring.ai.openai.api-key 配置属性,并不要设置上面提到的 api-key 属性。

For keyless authentication using Microsoft Entra ID (formerly Azure Active Directory), set only the spring.ai.azure.openai.endpoint configuration property and not the api-key property mentioned above.

仅找到端点属性,您的应用程序将评估几种不同的选项来检索凭据,并使用令牌凭据创建一个 DefaultAzureCredential 实例。

Finding only the endpoint property, your application will evaluate several different options for retrieving credentials and an OpenAIClient instance will be created using the token credentials.

不再需要创建 SpringAiAzureConfiguration bean;它已为您自动配置。

It is no longer necessary to create a TokenCredential bean; it is configured for you automatically.

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

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:

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

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

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-azure-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

前缀 spring.ai.azure.openai 是用于配置与 Azure OpenAI 连接的属性前缀。

The prefix spring.ai.azure.openai is the property prefix to configure the connection to Azure OpenAI.

Property Description Default

spring.ai.azure.openai.api-key

The Key from Azure AI OpenAI Keys and Endpoint section under Resource Management

-

spring.ai.azure.openai.endpoint

The endpoint from the Azure AI OpenAI Keys and Endpoint section under Resource Management

-

spring.ai.azure.openai.openai-api-key

(non Azure) OpenAI API key. Used to authenticate with the OpenAI service, instead of Azure OpenAI. This automatically sets the endpoint to [role="bare"]https://api.openai.com/v1. Use either api-key or openai-api-key property. With this configuration the spring.ai.azure.openai.embedding.options.deployment-name is threated as an OpenAi Model name.

-

嵌入自动配置的启用和禁用现在通过前缀为 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=azure-openai(默认启用)

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

要禁用,spring.ai.model.embedding=none(或任何与 azure-openai 不匹配的值)

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

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

This change is done to allow configuration of multiple models.

前缀 spring.ai.azure.openai.embedding 是配置 Azure OpenAI 的 EmbeddingModel 实现的属性前缀。

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

Property Description Default

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

Enable Azure OpenAI embedding model.

true

spring.ai.model.embedding

Enable Azure OpenAI embedding model.

azure-openai

spring.ai.azure.openai.embedding.metadata-mode

Document content extraction mode

EMBED

spring.ai.azure.openai.embedding.options.deployment-name

This is the value of the 'Deployment Name' as presented in the Azure AI Portal

text-embedding-ada-002

spring.ai.azure.openai.embedding.options.user

An identifier for the caller or end user of the operation. This may be used for tracking or rate-limiting purposes.

-

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

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

Runtime Options

AzureOpenAiEmbeddingOptions 提供嵌入请求的配置信息。AzureOpenAiEmbeddingOptions 提供一个生成该选项的构建器。

The AzureOpenAiEmbeddingOptions provides the configuration information for the embedding requests. The AzureOpenAiEmbeddingOptions offers a builder to create the options.

在启动时,使用 AzureOpenAiEmbeddingModel 构造函数设置所有嵌入请求的默认选项。在运行时,您可以通过将 AzureOpenAiEmbeddingOptions 实例与您的 EmbeddingRequest 请求一起传递来覆盖默认选项。

At start time use the AzureOpenAiEmbeddingModel constructor to set the default options used for all embedding requests. At run-time you can override the default options, by passing a AzureOpenAiEmbeddingOptions instance with your to the EmbeddingRequest request.

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

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"),
        AzureOpenAiEmbeddingOptions.builder()
        .model("Different-Embedding-Model-Deployment-Name")
        .build()));

Sample Code

这将创建一个 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.azure.openai.api-key=YOUR_API_KEY
spring.ai.azure.openai.endpoint=YOUR_ENDPOINT
spring.ai.azure.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 自动配置,您可以手动配置应用程序中的 AzureOpenAiEmbeddingModel 。为此,请将 spring-ai-azure-openai 依赖项添加到您项目的 Maven pom.xml 文件中:

If you prefer not to use the Spring Boot auto-configuration, you can manually configure the AzureOpenAiEmbeddingModel in your application. For this add the spring-ai-azure-openai dependency to your project’s Maven pom.xml file:

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

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

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-azure-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-azure-openai 依赖项还提供对 AzureOpenAiEmbeddingModel 的访问。有关 AzureOpenAiChatModel 的更多信息,请参阅 Azure OpenAI Embeddings 部分。

The spring-ai-azure-openai dependency also provide the access to the AzureOpenAiEmbeddingModel. For more information about the AzureOpenAiChatModel refer to the Azure OpenAI Embeddings section.

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

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

var openAIClient = OpenAIClientBuilder()
        .credential(new AzureKeyCredential(System.getenv("AZURE_OPENAI_API_KEY")))
		.endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"))
		.buildClient();

var embeddingModel = new AzureOpenAiEmbeddingModel(this.openAIClient)
    .withDefaultOptions(AzureOpenAiEmbeddingOptions.builder()
        .model("text-embedding-ada-002")
        .user("user-6")
        .build());

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

text-embedding-ada-002 实际上是 Deployment Name,如 Azure AI Portal 中所示。

the text-embedding-ada-002 is actually the Deployment Name as presented in the Azure AI Portal.