Azure AI 服务

本节将引导您设置 AzureVectorStore,以便使用 Azure AI 搜索服务存储文档嵌入并执行相似性搜索。 Azure AI 搜索 是一个多功能的云托管信息检索系统,是微软大型 AI 平台的一部分。除了其他功能,它允许用户使用基于向量的存储和检索来查询信息。

先决条件

  1. Azure 订阅:您需要一个 Azure 订阅 才能使用任何 Azure 服务。

  2. Azure AI 搜索服务:创建一个 AI 搜索服务。服务创建后,从 Settings 下的 Keys 部分获取管理员 apiKey,并从 Overview 部分的 Url 字段中检索端点。

  3. (可选)Azure OpenAI 服务:创建一个 Azure OpenAI 服务注意: 您可能需要填写单独的表格才能获得 Azure Open AI 服务的访问权限。服务创建后,从 Resource Management 下的 Keys and Endpoint 部分获取端点和 apiKey。

配置

在启动时,如果通过在构造函数中将相关 initialize-schema boolean 属性设置为 true,或者在使用 Spring Boot 时在 application.properties 文件中设置 …​initialize-schema=true 来选择加入,AzureVectorStore 可以尝试在您的 AI 搜索服务实例中创建一个新索引。

这是一个重大更改!在 Spring AI 的早期版本中,此模式初始化是默认发生的。

或者,您可以手动创建索引。

要设置 AzureVectorStore,您需要从上述先决条件中检索到的设置以及您的索引名称:

  • Azure AI 搜索端点

  • Azure AI 搜索密钥

  • (可选)Azure OpenAI API 端点

  • (可选)Azure OpenAI API 密钥

您可以将这些值作为 OS 环境变量提供。

export AZURE_AI_SEARCH_API_KEY=<My AI Search API Key>
export AZURE_AI_SEARCH_ENDPOINT=<My AI Search Index>
export OPENAI_API_KEY=<My Azure AI API Key> (Optional)

您可以将 Azure Open AI 实现替换为任何支持 Embeddings 接口的有效 OpenAI 实现。例如,您可以使用 Spring AI 的 Open AI 或 TransformersEmbedding 实现进行嵌入,而不是 Azure 实现。

依赖项

Spring AI 自动配置、启动器模块的工件名称发生了重大变化。 请参阅 升级说明 获取更多信息。

将这些依赖项添加到您的项目中:

1. 选择一个 Embeddings 接口实现。您可以选择:

  • OpenAI 嵌入

  • Azure AI 嵌入

  • 本地 Sentence Transformers 嵌入

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

2. Azure (AI 搜索) 向量存储

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

请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。

配置属性

您可以在 Spring Boot 配置中使用以下属性来自定义 Azure 向量存储。

属性 默认值

spring.ai.vectorstore.azure.url

spring.ai.vectorstore.azure.api-key

spring.ai.vectorstore.azure.useKeylessAuth

false

spring.ai.vectorstore.azure.initialize-schema

false

spring.ai.vectorstore.azure.index-name

spring_ai_azure_vector_store

spring.ai.vectorstore.azure.default-top-k

4

spring.ai.vectorstore.azure.default-similarity-threshold

0.0

spring.ai.vectorstore.azure.embedding-property

embedding

spring.ai.vectorstore.azure.index-name

spring-ai-document-index

示例代码

要在您的应用程序中配置 Azure SearchIndexClient,您可以使用以下代码:

@Bean
public SearchIndexClient searchIndexClient() {
  return new SearchIndexClientBuilder().endpoint(System.getenv("AZURE_AI_SEARCH_ENDPOINT"))
    .credential(new AzureKeyCredential(System.getenv("AZURE_AI_SEARCH_API_KEY")))
    .buildClient();
}

要创建向量存储,您可以使用以下代码,通过注入上述示例中创建的 SearchIndexClient bean 以及 Spring AI 库提供的实现所需 Embeddings 接口的 EmbeddingModel

@Bean
public VectorStore vectorStore(SearchIndexClient searchIndexClient, EmbeddingModel embeddingModel) {

  return AzureVectorStore.builder(searchIndexClient, embeddingModel)
    .initializeSchema(true)
    // Define the metadata fields to be used
    // in the similarity search filters.
    .filterMetadataFields(List.of(MetadataField.text("country"), MetadataField.int64("year"),
            MetadataField.date("activationDate")))
    .defaultTopK(5)
    .defaultSimilarityThreshold(0.7)
    .indexName("spring-ai-document-index")
    .build();
}

您必须明确列出用于过滤表达式中任何元数据键的所有元数据字段名称和类型。上面的列表注册了可过滤的元数据字段:类型为 TEXTcountry,类型为 INT64year,以及类型为 BOOLEANactive。 如果可过滤的元数据字段扩展了新条目,则必须(重新)上传/更新带有此元数据的文档。

在您的主代码中,创建一些文档:

List<Document> documents = List.of(
	new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("country", "BG", "year", 2020)),
	new Document("The World is Big and Salvation Lurks Around the Corner"),
	new Document("You walk forward facing the past and you turn back toward the future.", Map.of("country", "NL", "year", 2023)));

将文档添加到您的向量存储中:

vectorStore.add(documents);

最后,检索与查询相似的文档:

List<Document> results = vectorStore.similaritySearch(
    SearchRequest.builder()
      .query("Spring")
      .topK(5).build());

如果一切顺利,您应该会检索到包含文本“Spring AI rocks!!”的文档。

元数据过滤

您还可以将通用的、可移植的 元数据过滤器 与 AzureVectorStore 结合使用。

例如,您可以使用文本表达式语言:

vectorStore.similaritySearch(
   SearchRequest.builder()
      .query("The World")
      .topK(TOP_K)
      .similarityThreshold(SIMILARITY_THRESHOLD)
      .filterExpression("country in ['UK', 'NL'] && year >= 2020").build());

或使用表达式 DSL 以编程方式:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(
    SearchRequest.builder()
      .query("The World")
      .topK(TOP_K)
      .similarityThreshold(SIMILARITY_THRESHOLD)
      .filterExpression(b.and(
         b.in("country", "UK", "NL"),
         b.gte("year", 2020)).build()).build());

可移植的过滤器表达式会自动转换为专有的 Azure 搜索 OData 过滤器。例如,以下可移植的过滤器表达式:

country in ['UK', 'NL'] && year >= 2020

转换为以下 Azure OData 过滤器表达式

$filter search.in(meta_country, 'UK,NL', ',') and meta_year ge 2020

访问本机客户端

Azure 向量存储实现通过 getNativeClient() 方法提供对底层本机 Azure 搜索客户端 (SearchClient) 的访问:

AzureVectorStore vectorStore = context.getBean(AzureVectorStore.class);
Optional<SearchClient> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    SearchClient client = nativeClient.get();
    // Use the native client for Azure Search-specific operations
}

本机客户端允许您访问 VectorStore 接口可能未公开的 Azure 搜索特定功能和操作。