|
此版本仍在开发中,尚未被视为稳定版。为了获取最新的快照版本,请使用Spring AI 1.1.3! |
Azure AI 服务
本节将引导你设置 AzureVectorStore 以存储文档嵌入并使用 Azure AI 搜索服务执行相似性搜索。
Azure AI Search 是一个多功能的云托管信息检索系统,是 Microsoft 更大 AI 平台的一部分。除了其他功能外,它还允许用户使用基于向量的存储和检索来查询信息。
配置
在启动时,如果您已在构造函数中将相关的 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 密钥
你可以将这些值作为操作系统环境变量提供。
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 或 |
依赖项
|
There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。 |
将这些依赖项添加到您的项目中:
1. 选择一个嵌入接口实现。您可以选择以下选项:
-
OpenAI Embedding
-
Azure AI Embedding
-
Local 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 向量存储。
| 属性 | 默认值 |
|---|---|
|
|
|
|
|
false |
|
false |
|
spring_ai_azure_vector_store |
|
4 |
|
0.0 |
|
内容 |
|
嵌入 |
|
元数据 |
示例代码
要在应用程序中配置 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();
}
|
您必须显式列出过滤表达式中使用的任何元数据键的所有元数据字段名称和类型。上面的列表注册了可过滤的元数据字段: 如果可筛选的元数据字段增加了新条目,您必须(重新)上传/更新包含此元数据的文档。 |
在你的主代码中,创建一些文档:
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向量存储库在Azure人工智能搜索索引中使用以下字段名称:
-
content- 对于文档文本 -
embedding- 用于向量嵌入 -
0 - 对于文档元数据
然而,在与现有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
| 当使用带有自定义字段名称的现有索引时,将0设置为启用时,以防止Spring AI尝试创建带有默认模式的新的索引。 |
配置方式:使用 builder API
除了使用配置文件中的默认字段名外,你还可以通过 builder API 程序atically 配置自定义的字段名:例如,你可以定义一个自定义字段名为 {name}。builder 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();
}
}
然后你可以像 usual 使用向量存储:
// 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()));
Creating New Index with Custom Field Names(创建带有自定义字段名称的新索引)
你可以通过设置“0”来创建一个新的索引,使用自定义字段名称:
@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 搜索索引,从一开始就允许您建立自己的命名惯例。
访问原生客户端
微软云向量存储的实现提供了一个访问底层的 native 蓝牙搜索客户端(SearchClient)的方法(getNativeClient()):
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
}
The native client gives you access to Azure Search-specific features and operations that might not be exposed through the VectorStore interface.