Chroma

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

本节将引导你设置 Chroma VectorStore,以存储文档嵌入并执行相似性搜索。

Chroma 是开源嵌入式数据库。它为你提供了存储文档嵌入、内容和元数据以及搜索这些嵌入(包括元数据过滤)的工具。

先决条件

  1. 访问 ChromeDB。本地 ChromaDB 设置 附录演示了如何通过 Docker 容器在本地建立数据库。

  2. 用于计算文档向量的 EmbeddingModel 实例。可选方案包括:

    • 如需为 EmbeddingModel 生成存储在 ChromaVectorStore 中的向量,需配置 API 密钥。

启动时,若未预先配置集合,ChromaVectorStore 将自动创建所需集合。

自动配置

Spring AI 自动配置及 Starter 模块的 Artifact 名称已发生重大变更。更多信息请参阅 升级说明

Spring AI 为 Chroma 向量存储提供 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 仓库” 部分将 Maven Central 和/或 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(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>
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 向量存储并使用它:

@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

服务连接主机

http://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

是否初始化所需的 Schema

false

对于采用 静态 API 令牌认证 的 ChromaDB,使用 ChromaApi#withKeyToken(<你的令牌凭证>) 方法设置凭证。示例参考 ChromaWhereIT

对于采用 基础认证(Basic Authenticatio) 的 ChromaDB,使用 ChromaApi#withBasicAuth(<用户名>, <密码>) 方法设置凭证。示例参考 BasicAuthChromaWhereIT

元数据过滤

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 向量存储,可在 Spring Boot 应用中创建 ChromaVectorStore Bean。

将以下依赖添加至项目:

  • Chroma 向量存储

<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 = "http://localhost:8000";
   ChromaApi chromaApi = new ChromaApi(chromaUrl, restClientBuilder);
   return chromaApi;
}

集成 OpenAI 嵌入功能需在项目中添加 Spring Boot OpenAI Starter,该组件提供 Embeddings 客户端实现:

@Bean
public VectorStore chromaVectorStore(EmbeddingModel embeddingModel, ChromaApi chromaApi) {
 return ChromaVectorStore.builder(chromaApi, embeddingModel)
    .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

启动 Chroma 存储服务,访问地址为 localhost:8000/api/v1