Azure AI 服务

本节将指导您如何设置 AzureVectorStore,以使用 Azure AI 搜索服务存储文档 Embedding 并执行相似度搜索。

Azure AI 搜索 是一种通用的云托管信息检索系统,是微软大型 AI 平台的一部分。除其他功能外,它允许用户使用基于向量的存储和检索方式查询信息。

先决条件

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

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

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

配置

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

这是一个破坏性更改!在早期版本的 Spring AI 中,默认会进行此 schema 初始化。

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

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

  • Azure AI 搜索端点

  • Azure AI 搜索密钥

  • (可选)Azure OpenAI API 端点

  • (可选)Azure OpenAI API 密钥

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

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 OpenAI 实现替换为支持 Embeddings 接口的任何有效 OpenAI 实现。例如,您可以使用 Spring AI 的 OpenAI 或 TransformersEmbedding 实现来进行 embeddings,而不是使用 Azure 实现。

依赖项

Spring AI 自动配置、starter 模块的 artifact 名称发生了重大变化。请参阅 升级说明 以了解更多信息。

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

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

  • OpenAI Embedding

  • Azure AI Embedding

  • 本地 Sentence Transformers Embedding

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

原生客户端使您能够访问 Azure 搜索特有的功能和操作,这些功能和操作可能不会通过 VectorStore 接口暴露。