Chroma

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

Chroma 是開源嵌入資料庫。它為您提供工具來儲存文件嵌入、內容和元數據,並搜尋這些嵌入,包括元數據過濾。

先決條件

  1. 存取 ChromeDB。 在本機端設定 ChromaDB 附錄說明如何使用 Docker 容器在本機端設定資料庫。

  2. EmbeddingModel 執行個體以計算文件嵌入。有多種選項可供選擇

    • 如果需要,EmbeddingModel 的 API 金鑰,以產生 ChromaVectorStore 儲存的嵌入。

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

自動設定

Spring AI 為 Chroma Vector Store 提供 Spring Boot 自動設定。若要啟用它,請將以下依賴項新增至專案的 Maven pom.xml 檔案

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

或新增至 Gradle build.gradle 建置檔案。

dependencies {
    implementation 'org.springframework.ai:spring-ai-chroma-store-spring-boot-starter'
}
請參閱依賴項管理章節,將 Spring AI BOM 新增至您的建置檔案。
請參閱儲存庫章節,將 Milestone 和/或 Snapshot 儲存庫新增至您的建置檔案。

向量儲存實作可以為您初始化必要的架構,但您必須選擇加入,方法是在適當的建構函式中指定 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(new OpenAiApi(System.getenv("SPRING_AI_OPENAI_API_KEY")));
}

若要連線到 Chroma,您需要提供您執行個體的存取詳細資訊。簡單的設定可以透過 Spring Boot 的 application.properties 提供,

# Chroma Vector Store connection properties
spring.ai.vectorstore.chroma.client.host=<your Chroma instance host>
spring.ai.vectorstore.chroma.client.port=<your Chroma instance port>
spring.ai.vectorstore.chroma.client.key-token=<your access token (if configure)>
spring.ai.vectorstore.chroma.client.username=<your username (if configure)>
spring.ai.vectorstore.chroma.client.password=<your password (if configure)>

# 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.query("Spring").withTopK(5));

設定屬性

您可以在 Spring Boot 設定中使用以下屬性來自訂向量儲存。

屬性 描述 預設值

spring.ai.vectorstore.chroma.client.host

伺服器連線主機

localhost

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.collection-name

集合名稱

SpringAiCollection

spring.ai.vectorstore.chroma.initialize-schema

是否初始化所需的架構

false

對於使用 靜態 API 權杖驗證 保護的 ChromaDB,請使用 ChromaApi#withKeyToken(<您的權杖憑證>) 方法來設定您的憑證。請查看 ChromaWhereIT 以取得範例。

對於使用 基本驗證 保護的 ChromaDB,請使用 ChromaApi#withBasicAuth(<您的使用者名稱>, <您的密碼>) 方法來設定您的憑證。請查看 BasicAuthChromaWhereIT 以取得範例。

元數據過濾

您也可以將通用的、可移植的 元數據過濾器 與 ChromaVector 儲存一起使用。

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

vectorStore.similaritySearch(
                    SearchRequest.defaults()
                            .withQuery("The World")
                            .withTopK(TOP_K)
                            .withSimilarityThreshold(SIMILARITY_THRESHOLD)
                            .withFilterExpression("author in ['john', 'jill'] && article_type == 'blog'"));

或以程式設計方式使用 Filter.Expression DSL

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.defaults()
                    .withQuery("The World")
                    .withTopK(TOP_K)
                    .withSimilarityThreshold(SIMILARITY_THRESHOLD)
                    .withFilterExpression(b.and(
                            b.in("john", "jill"),
                            b.eq("article_type", "blog")).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-openai-spring-boot-starter</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://127.0.0.1:8000";
   ChromaApi chromaApi = new ChromaApi(chromaUrl, restClientBuilder);
   return chromaApi;
}

透過將 Spring Boot OpenAI starter 新增至您的專案,與 OpenAI 的嵌入整合。這為您提供了 Embeddings 用戶端的實作

@Bean
public VectorStore chromaVectorStore(EmbeddingModel embeddingModel, ChromaApi chromaApi) {
 return new ChromaVectorStore(embeddingModel, chromaApi, "TestCollection", false);
}

在您的主要程式碼中,建立一些文件

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:0.4.15

localhost:8000/api/v1 啟動 chroma 儲存