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 介面暴露。