Chroma

本節將引導您設定 Chroma VectorStore 以儲存文件嵌入並執行相似性搜尋。

Chroma 是開源嵌入式資料庫。它為您提供了儲存文件嵌入、內容和元資料以及透過這些嵌入進行搜尋(包括元資料過濾)的工具。

先決條件

  1. 訪問 ChromaDB。相容 Chroma Cloud,或 附錄中設定本地 ChromaDB 展示瞭如何使用 Docker 容器在本地設定資料庫。

    • 對於 Chroma Cloud:您需要從 Chroma Cloud 儀表板獲取 API 金鑰、租戶名稱和資料庫名稱。

    • 對於本地 ChromaDB:除了啟動容器外,無需額外配置。

  2. EmbeddingModel 例項用於計算文件嵌入。有幾個選項可用。

    • 如果需要,需要 EmbeddingModel 的 API 金鑰來生成由 ChromaVectorStore 儲存的嵌入。

啟動時,如果尚未配置,ChromaVectorStore 會建立所需的集合。

自動配置

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

Spring AI 為 Chroma Vector Store 提供了 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到您的專案 Maven pom.xml 檔案中:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-chroma</artifactId>
</dependency>

或新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-chroma'
}
請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建檔案中。
請參閱Artifact Repositories(工件倉庫)部分,將 Maven Central 和/或 Snapshot Repositories 新增到您的構建檔案中。

向量儲存實現可以為您初始化所需的模式,但您必須透過在相應的建構函式中指定 initializeSchema 布林值或在 application.properties 檔案中設定 ...initialize-schema=true 來選擇啟用。

這是一個重大更改!在早期版本的 Spring AI 中,此模式初始化是預設發生的。

此外,您還需要配置一個 EmbeddingModel bean。有關更多資訊,請參閱 EmbeddingModel 部分。

這是一個所需 bean 的示例:

@Bean
public EmbeddingModel embeddingModel() {
    // Can be any other EmbeddingModel implementation.
    return new OpenAiEmbeddingModel(OpenAiApi.builder().apiKey(System.getenv("OPENAI_API_KEY")).build());
}

要連線到 Chroma,您需要提供例項的訪問詳細資訊。可以透過 Spring Boot 的 application.properties 提供一個簡單的配置,

# Chroma Vector Store connection properties
spring.ai.vectorstore.chroma.client.host=<your Chroma instance host>  // for Chroma Cloud: api.trychroma.com
spring.ai.vectorstore.chroma.client.port=<your Chroma instance port> // for Chroma Cloud: 443
spring.ai.vectorstore.chroma.client.key-token=<your access token (if configure)> // for Chroma Cloud: use the API key
spring.ai.vectorstore.chroma.client.username=<your username (if configure)>
spring.ai.vectorstore.chroma.client.password=<your password (if configure)>

# Chroma Vector Store tenant and database properties (required for Chroma Cloud)
spring.ai.vectorstore.chroma.tenant-name=<your tenant name> // default: SpringAiTenant
spring.ai.vectorstore.chroma.database-name=<your database name> // default: SpringAiDatabase

# Chroma Vector Store collection properties
spring.ai.vectorstore.chroma.initialize-schema=<true or false>
spring.ai.vectorstore.chroma.collection-name=<your collection name>

# Chroma Vector Store configuration properties

# OpenAI API key if the OpenAI auto-configuration is used.
spring.ai.openai.api.key=<OpenAI Api-key>

請查看向量儲存的配置引數列表,以瞭解預設值和配置選項。

現在您可以在應用程式中自動裝配 Chroma Vector Store 並使用它了

@Autowired VectorStore vectorStore;

// ...

List <Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    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("meta2", "meta2")));

// Add the documents
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置屬性

您可以在 Spring Boot 配置中使用以下屬性來定製向量儲存。

財產 描述 預設值

spring.ai.vectorstore.chroma.client.host

伺服器連線主機

https://

spring.ai.vectorstore.chroma.client.port

伺服器連線埠

8000

spring.ai.vectorstore.chroma.client.key-token

訪問令牌(如果已配置)

-

spring.ai.vectorstore.chroma.client.username

訪問使用者名稱(如果已配置)

-

spring.ai.vectorstore.chroma.client.password

訪問密碼(如果已配置)

-

spring.ai.vectorstore.chroma.tenant-name

租戶(Chroma Cloud 必需)

SpringAiTenant

spring.ai.vectorstore.chroma.database-name

資料庫名稱(Chroma Cloud 必需)

SpringAiDatabase

spring.ai.vectorstore.chroma.collection-name

集合名稱

SpringAiCollection

spring.ai.vectorstore.chroma.initialize-schema

是否初始化所需模式(如果不存在則建立租戶/資料庫/集合)

對於使用 靜態 API 令牌身份驗證 保護的 ChromaDB,請使用 ChromaApi#withKeyToken(<您的令牌憑據>) 方法設定您的憑據。請檢視 ChromaWhereIT 獲取示例。

對於使用 基本身份驗證 保護的 ChromaDB,請使用 ChromaApi#withBasicAuth(<您的使用者>, <您的密碼>) 方法設定您的憑據。請檢視 BasicAuthChromaWhereIT 獲取示例。

Chroma Cloud 配置

對於 Chroma Cloud,您需要提供 Chroma Cloud 例項的租戶和資料庫名稱。以下是配置示例:

# Chroma Cloud connection
spring.ai.vectorstore.chroma.client.host=api.trychroma.com
spring.ai.vectorstore.chroma.client.port=443
spring.ai.vectorstore.chroma.client.key-token=<your-chroma-cloud-api-key>

# Chroma Cloud tenant and database (required)
spring.ai.vectorstore.chroma.tenant-name=<your-tenant-id>
spring.ai.vectorstore.chroma.database-name=<your-database-name>

# Collection configuration
spring.ai.vectorstore.chroma.collection-name=my-collection
spring.ai.vectorstore.chroma.initialize-schema=true

對於 Chroma Cloud: - 主機應為 api.trychroma.com - 埠應為 443 (HTTPS) - 您必須透過 key-token 提供您的 API 金鑰 - 租戶和資料庫名稱必須與您的 Chroma Cloud 配置匹配 - 設定 initialize-schema=true 以便在集合不存在時自動建立(它不會重新建立現有的租戶/資料庫)

元資料過濾

您也可以利用 ChromaVector 儲存的通用、可移植的元資料過濾器

例如,您可以使用文字表示式語言

vectorStore.similaritySearch(
                    SearchRequest.builder()
                            .query("The World")
                            .topK(TOP_K)
                            .similarityThreshold(SIMILARITY_THRESHOLD)
                            .filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());

或透過 Filter.Expression DSL 以程式設計方式實現

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
                    .query("The World")
                    .topK(TOP_K)
                    .similarityThreshold(SIMILARITY_THRESHOLD)
                    .filterExpression(b.and(
                            b.in("john", "jill"),
                            b.eq("article_type", "blog")).build()).build());
這些(可移植的)過濾器表示式會自動轉換為 Chroma 專有的 where 過濾器表示式

例如,這個可移植的過濾器表示式

author in ['john', 'jill'] && article_type == 'blog'

轉換為專有的 Chroma 格式

{"$and":[
	{"author": {"$in": ["john", "jill"]}},
	{"article_type":{"$eq":"blog"}}]
}

手動配置

如果您更喜歡手動配置 Chroma Vector Store,可以透過在 Spring Boot 應用程式中建立 ChromaVectorStore bean 來實現。

將這些依賴項新增到您的專案: * Chroma VectorStore。

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-chroma-store</artifactId>
</dependency>
  • OpenAI:計算嵌入所需。您可以使用任何其他嵌入模型實現。

<dependency>
 <groupId>org.springframework.ai</groupId>
 <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建檔案中。

示例程式碼

使用適當的 ChromaDB 授權配置建立一個 RestClient.Builder 例項,並用它來建立一個 ChromaApi 例項。

@Bean
public RestClient.Builder builder() {
    return RestClient.builder().requestFactory(new SimpleClientHttpRequestFactory());
}


@Bean
public ChromaApi chromaApi(RestClient.Builder restClientBuilder) {
   String chromaUrl = "https://:8000";
   ChromaApi chromaApi = new ChromaApi(chromaUrl, restClientBuilder);
   return chromaApi;
}

透過將 Spring Boot OpenAI 啟動器新增到您的專案中,與 OpenAI 的嵌入功能整合。這為您提供了一個嵌入客戶端的實現。

@Bean
public VectorStore chromaVectorStore(EmbeddingModel embeddingModel, ChromaApi chromaApi) {
 return ChromaVectorStore.builder(chromaApi, embeddingModel)
    .tenantName("your-tenant-name") // default: SpringAiTenant
    .databaseName("your-database-name") // default: SpringAiDatabase
    .collectionName("TestCollection")
    .initializeSchema(true)
    .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("meta1", "meta1")),
 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("meta2", "meta2")));

將文件新增到您的向量儲存中

vectorStore.add(documents);

最後,檢索與查詢相似的文件

List<Document> results = vectorStore.similaritySearch("Spring");

如果一切順利,您應該會檢索到包含文字“Spring AI rocks!!”的文件。

在本地執行 Chroma

docker run -it --rm --name chroma -p 8000:8000 ghcr.io/chroma-core/chroma:1.0.0

localhost:8000/api/v1 啟動一個 Chroma 儲存

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