跳到主要内容
版本:2.0.1

Chroma

QWen 3.8 中英对照 Chroma

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

Chroma 是一个开源的嵌入数据库。它提供了存储文档嵌入、内容和元数据的工具,并支持对这些嵌入进行搜索,包括基于元数据的过滤。

前提条件​

  1. 对 ChromaDB 的访问权限。兼容 Chroma Cloud,或者参见附录中的[setup local ChromaDB](#run Chroma Locally),其中介绍了如何使用 Docker 容器在本地设置数据库。

    • 对于 Chroma Cloud:你需要从 Chroma Cloud 仪表盘中获取 API 密钥、租户名称和数据库名称。
    • 对于本地 ChromaDB:除了启动容器外,无需额外配置。
  2. EmbeddingModel 实例,用于计算文档嵌入。有多种选择:

    • 如果需要,需要提供 EmbeddingModel 的 API 密钥,以生成存储在 ChromaVectorStore 中的嵌入。

启动时,如果尚未创建所需的集合,ChromaVectorStore 会自动创建该集合。

自动配置​

备注

Spring AI 自动配置及 starter 模块的构件名称发生了重大变更。更多信息请参见 升级说明。

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'
}
提示

请参阅 Dependency Management 部分,以将 Spring AI BOM 添加到您的构建文件中。

提示

请参考 Artifact Repositories 章节,将 Maven Central 和/或 Snapshot Repositories 添加到你的构建文件中。

向量存储实现可以为你初始化所需的架构(schema),但你必须通过指定相应构造函数中的 initializeSchema 布尔值,或在 application.properties 文件中设置 …​initialize-schema=true 来明确启用此功能。

备注

这是一个破坏性变更!在 Spring AI 的早期版本中,该 schema 初始化默认会执行。

此外,您还需要一个配置好的 EmbeddingModel bean。有关更多信息,请参阅 EmbeddingModel 部分。

这里是一个所需的 Bean 示例:

@Bean
public EmbeddingModel embeddingModel() {
// Can be any other EmbeddingModel implementation.
return new OpenAiEmbeddingModel(OpenAiEmbeddingOptions.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服务器连接主机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.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是否初始化所需的 schema(如果不存在则创建 tenant/database/collection)false
备注

对于使用 静态 API 令牌认证 进行保护的 ChromaDB,请使用 ChromaApi#withKeyToken(<Your Token Credentials>) 方法来设置你的凭据。可参考 ChromaWhereIT 中的示例。

对于使用 基本认证 进行保护的 ChromaDB,请使用 ChromaApi#withBasicAuth(<your user>, <your password>) 方法来设置你的凭据。可参考 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 存储时利用通用的可移植 metadata filters。

例如,您可以使用文本表达式语言:

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:计算嵌入(embeddings)所必需。您也可以使用任何其他嵌入模型实现。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
提示

请参见 依赖管理 章节,以将 Spring AI BOM 添加到你的构建文件中。

示例代码​

创建一个 RestClient.Builder 实例,配置正确的 ChromaDB 授权设置,并使用它创建 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;
}

通过向项目中添加 Spring Boot OpenAI starter 来集成 OpenAI 的 embeddings。这将为你提供 Embeddings client 的实现:

@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 存储