跳到主要内容
版本:2.0.1

Azure AI Service

QWen 3.8 中英对照 Azure AI Service

本节将指导您配置 AzureVectorStore,以使用 Azure AI Search Service 存储文档嵌入并执行相似性搜索。

Azure AI Search 是一个功能强大的云托管信息检索系统,是微软更大规模 AI 平台的一部分。除了其他特性外,它支持用户通过基于向量的存储和检索来查询信息。

前置要求​

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

  2. Azure AI Search 服务:创建一个 AI Search 服务。服务创建完成后,在 Settings 部分的 Keys 节中获取管理员 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 Search 服务实例中创建一个新的索引。

备注

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

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

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

  • Azure AI Search Endpoint

  • Azure AI Search Key

  • (可选) Azure OpenAI API Endpoint

  • (可选) Azure OpenAI API Key

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

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 的自动配置以及 starter 模块的 artifact 名称发生了重大变更。请参阅升级说明以获取更多信息。

在你的项目中添加以下依赖:

1. 选择一个 Embeddings 接口实现。您可以从以下选项中进行选择:​

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

2. Azure(AI Search)向量存储​

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

请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件中。

配置属性​

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

属性默认值
spring.ai.vectorstore.azure.url
spring.ai.vectorstore.azure.api-key
spring.ai.vectorstore.azure.use-keyless-authfalse
spring.ai.vectorstore.azure.initialize-schemafalse
spring.ai.vectorstore.azure.index-namespring_ai_azure_vector_store
spring.ai.vectorstore.azure.default-top-k4
spring.ai.vectorstore.azure.default-similarity-threshold0.0
spring.ai.vectorstore.azure.content-field-namecontent
spring.ai.vectorstore.azure.embedding-field-nameembedding
spring.ai.vectorstore.azure.metadata-field-namemetadata

示例代码​

要在应用程序中配置 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();
}
备注

您必须在过滤表达式中显式列出所有元数据字段名称和类型。上述列表注册了可过滤的元数据字段:类型为 TEXT 的 country、类型为 INT64 的 year,以及类型为 BOOLEAN 的 active。

如果可过滤的元数据字段扩展了新的条目,您必须(重新)上传/更新包含此元数据的文档。

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

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 Search 专有的 OData 过滤器。例如,以下可移植过滤表达式:

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

转换为以下 Azure OData 筛选表达式:

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

自定义字段名称​

默认情况下,Azure 向量存储(Azure Vector Store)在 Azure AI 搜索索引中使用以下字段名称:

  • content - 用于文档文本

  • embedding - 用于向量嵌入

  • metadata - 用于文档元数据

不过,当使用具有不同字段名称的现有 Azure AI Search 索引时,可以配置自定义字段名称以匹配您的索引架构。这样,您便能在无需修改现有索引的情况下,将 Spring AI 与它们集成。

使用场景​

当以下情况时,自定义字段名称特别有用:

  • 与现有索引集成:您的组织已经拥有 Azure AI Search 索引,并遵循既定的字段命名规范(例如,chunk_text、vector、meta_data)。

  • 遵循命名标准:您的团队遵循的命名规范与默认设置不同。

  • 从其他系统迁移:您正在从另一个向量数据库或搜索系统迁移,并希望保持一致的字段名称。

通过属性配置​

可以使用 Spring Boot 应用程序属性来配置自定义字段名称:

spring.ai.vectorstore.azure.url=${AZURE_AI_SEARCH_ENDPOINT}
spring.ai.vectorstore.azure.api-key=${AZURE_AI_SEARCH_API_KEY}
spring.ai.vectorstore.azure.index-name=my-existing-index
spring.ai.vectorstore.azure.initialize-schema=false

# Custom field names to match existing index schema
spring.ai.vectorstore.azure.content-field-name=chunk_text
spring.ai.vectorstore.azure.embedding-field-name=vector
spring.ai.vectorstore.azure.metadata-field-name=meta_data
important

当使用具有自定义字段名的现有索引时,请设置 initialize-schema=false 以防止 Spring AI 尝试使用默认架构创建新索引。

通过 Builder API 进行配置​

或者,你可以使用构建器 API 以编程方式配置自定义字段名称:

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

return AzureVectorStore.builder(searchIndexClient, embeddingModel)
.indexName("my-existing-index")
.initializeSchema(false) // Don't create schema - use existing index
// Configure custom field names to match existing index
.contentFieldName("chunk_text")
.embeddingFieldName("vector")
.metadataFieldName("meta_data")
.filterMetadataFields(List.of(
MetadataField.text("category"),
MetadataField.text("source")))
.build();
}

完整示例:处理现有索引​

下面是一个完整示例,展示如何结合使用 Spring AI 和具有自定义字段名称的现有 Azure AI Search 索引:

@Configuration
public class VectorStoreConfig {

@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();
}

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

return AzureVectorStore.builder(searchIndexClient, embeddingModel)
.indexName("production-documents-index")
.initializeSchema(false) // Use existing index
// Map to existing index field names
.contentFieldName("document_text")
.embeddingFieldName("text_vector")
.metadataFieldName("document_metadata")
// Define filterable metadata fields from existing schema
.filterMetadataFields(List.of(
MetadataField.text("department"),
MetadataField.int64("year"),
MetadataField.date("created_date")))
.defaultTopK(10)
.defaultSimilarityThreshold(0.75)
.build();
}
}

然后,您可以像往常一样使用向量存储:

// Search using the existing index with custom field names
List<Document> results = vectorStore.similaritySearch(
SearchRequest.builder()
.query("artificial intelligence")
.topK(5)
.filterExpression("department == 'Engineering' && year >= 2023")
.build());

// The results contain documents with text from the 'document_text' field
results.forEach(doc -> System.out.println(doc.getText()));

使用自定义字段名创建新索引​

还可以通过设置 initializeSchema=true 来创建具有自定义字段名的新索引:

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

return AzureVectorStore.builder(searchIndexClient, embeddingModel)
.indexName("new-custom-index")
.initializeSchema(true) // Create new index with custom field names
.contentFieldName("text_content")
.embeddingFieldName("content_vector")
.metadataFieldName("doc_metadata")
.filterMetadataFields(List.of(
MetadataField.text("category"),
MetadataField.text("author")))
.build();
}

这将创建一个包含自定义字段名称的新 Azure AI Search 索引,从而允许您从一开始就建立自己的命名规范。

访问原生客户端​

Azure 向量存储实现通过 getNativeClient() 方法提供了对底层原生 Azure Search 客户端(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 Search 的功能和操作的权限,这些功能可能未通过 VectorStore 接口公开。