Chroma
本节将引导您完成Chroma VectorStore的设置,用于存储文档嵌入并执行相似性搜索。
Chroma 是一个开源的嵌入向量数据库。它为您提供了存储文档嵌入向量、内容及元数据的工具,并支持对这些嵌入向量(包括元数据过滤)进行搜索。
先决条件
-
访问 ChromaDB。兼容 Chroma Cloud,或者附录中的 [设置本地 ChromaDB](#run Chroma Locally) 说明了如何使用 Docker 容器在本地设置数据库。
-
对于 Chroma Cloud:你需要从 Chroma Cloud 仪表板获取你的 API 密钥、租户名称和数据库名称。
-
对于本地 ChromaDB:除了启动容器外,无需额外的配置。
-
-
EmbeddingModel实例,用于计算文档嵌入向量。有以下几种可选方案:- 如果需要,用于生成
ChromaVectorStore所存储的嵌入向量的 EmbeddingModel 的 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> // 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 向量存储并使用它
@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 | 是否初始化必需的架构 (如果租户/数据库/集合不存在,则创建它们) | false |
若 ChromaDB 启用了静态 API 令牌认证,请使用 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 向量存储,可以在 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 = "http://localhost:8000";
ChromaApi chromaApi = new ChromaApi(chromaUrl, restClientBuilder);
return chromaApi;
}
通过向您的项目中添加Spring Boot OpenAI启动器,集成OpenAI的嵌入功能。这将为您提供Embeddings客户端的实现:
@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
启动一个 Chroma 存储服务,地址为 localhost:8000/api/v1。