Azure AI 服務

本節將引導您設定 AzureVectorStore,以使用 Azure AI 搜尋服務儲存文件嵌入並執行相似性搜尋。

Azure AI 搜尋 是微軟大型 AI 平臺的一部分,是一種多功能雲託管資訊檢索系統。除其他功能外,它允許使用者使用基於向量的儲存和檢索來查詢資訊。

先決條件

  1. Azure 訂閱:您需要一個 Azure 訂閱 才能使用任何 Azure 服務。

  2. Azure AI 搜尋服務:建立一個 AI 搜尋服務。服務建立後,從 Settings 部分的 Keys 中獲取管理員 apiKey,並從 Overview 部分的 Url 欄位中檢索端點。

  3. (可選)Azure OpenAI 服務:建立一個 Azure OpenAI 服務注意: 您可能需要填寫單獨的表格才能獲得 Azure Open AI 服務的訪問許可權。服務建立後,從 Resource Management 部分的 Keys and Endpoint 中獲取端點和 apiKey。

配置

在啟動時,如果您已選擇透過在建構函式中將相關 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)

您可以用任何支援 Embeddings 介面的有效 OpenAI 實現替換 Azure Open AI 實現。例如,您可以使用 Spring AI 的 Open AI 或 TransformersEmbedding 實現來代替 Azure 實現進行嵌入。

依賴關係

Spring AI 自動配置、啟動模組的工件名稱發生了重大變化。請參閱 升級說明 以獲取更多資訊。

將這些依賴項新增到您的專案中

1. 選擇一個嵌入介面實現。您可以選擇

  • OpenAI 嵌入

  • Azure AI 嵌入

  • 本地 Sentence Transformers 嵌入

<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

spring.ai.vectorstore.azure.initialize-schema

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 Vector Store 實現透過 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
}

原生客戶端允許您訪問 VectorStore 介面可能未公開的 Azure 搜尋特定功能和操作。

© . This site is unofficial and not affiliated with VMware.