Azure AI 服务
本节将引导您设置 AzureVectorStore
,以存储文档嵌入并使用 Azure AI Search Service 执行相似性搜索。
Azure AI Search 是一个多功能的云托管信息检索系统,是微软更大的 AI 平台的一部分。除了其他功能外,它还允许用户使用基于向量的存储和检索来查询信息。
先决条件
-
Azure 订阅:你需要一个 Azure 订阅 来使用任何 Azure 服务。
-
Azure AI Search 服务:创建一个 AI Search 服务。服务创建完成后,从
Settings
下的Keys
部分获取管理员 apiKey,并从Overview
部分下的Url
字段中获取端点。 -
(可选)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 的早期版本中,此模式初始化是默认进行的。
或者,你也可以手动创建索引。
要设置 AzureVectorStore,你需要从上述先决条件中检索到的设置以及你的索引名称:
-
Azure AI Search 端点
-
Azure AI Search 密钥
-
(可选)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 Open AI 实现替换为任何支持 Embeddings 接口的有效 OpenAI 实现。例如,你可以使用 Spring AI 的 Open AI 或 TransformersEmbedding
实现来替代 Azure 实现。
依赖项
将以下依赖项添加到您的项目中:
1. 选择一个 Embeddings 接口实现。你可以从以下选项中选择:
- OpenAI Embedding
- Azure AI Embedding
- Local Sentence Transformers Embedding
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-transformers-spring-boot-starter</artifactId>
</dependency>
2. Azure (AI Search) 向量存储
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-azure-store</artifactId>
</dependency>
请参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。
配置属性
你可以在 Spring Boot 配置中使用以下属性来自定义 Azure vector store。
属性 | 默认值 |
---|---|
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();
}
您必须在过滤表达式中明确列出所有使用的元数据字段名称和类型。上面的列表注册了可过滤的元数据字段:类型为 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
访问 Native Client
Azure Vector Store 实现通过 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
接口暴露。