Chroma

本节将带你了解如何设置Chroma VectorStore,以存储文档嵌入并进行相似性搜索。spring-doc.cadn.net.cn

Chroma 是开源的嵌入数据库。它为你提供了存储文档嵌入、内容和元数据的工具,并能搜索这些嵌入,包括元数据过滤。spring-doc.cadn.net.cn

前提条件

  1. 访问ChromaDB。兼容Chroma Cloud,或者在附录中设置本地ChromaDB,说明如何用Docker容器本地搭建数据库。spring-doc.cadn.net.cn

  2. 嵌入模型实例用于计算文档嵌入。有几种选择:spring-doc.cadn.net.cn

启动时,色矢量存储如果尚未配置,则创建所需的集合。spring-doc.cadn.net.cn

自动配置

春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Chroma 向量商店提供了 Spring Boot 自动配置。要启用此功能,请在项目的 Maven 中添加以下依赖项pom.xml文件:spring-doc.cadn.net.cn

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

或者去你的Gradlebuild.gradle构建文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-chroma'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。
请参阅“遗物仓库”部分,将Maven Central和/或快照仓库添加到你的构建文件中。

向量存储实现可以帮你初始化所需的模式,但你必须通过指定初始化模式在适当的构造函数中进行布尔值,或通过设置…​initialize-schema=trueapplication.properties文件。spring-doc.cadn.net.cn

这是一个颠覆性的变革!在早期版本的 Spring AI 中,这种模式初始化是默认的。

此外,你还需要一个配置嵌入模型豆。 更多信息请参阅嵌入模型部分。spring-doc.cadn.net.cn

这里是所需豆子的一个例子:spring-doc.cadn.net.cn

@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 提供一个简单的配置,spring-doc.cadn.net.cn

# 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>

请查看矢量存储的配置参数列表,了解默认值和配置选项。spring-doc.cadn.net.cn

现在你可以在应用中自动接线Chroma Vector Store并使用它spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

属性 描述 默认值

spring.ai.vectorstore.chroma.client.hostspring-doc.cadn.net.cn

服务器连接主机spring-doc.cadn.net.cn

http://localhostspring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.client.portspring-doc.cadn.net.cn

服务器连接端口spring-doc.cadn.net.cn

8000spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.client.key标记spring-doc.cadn.net.cn

访问Tokens(如果配置过)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.client.usernamespring-doc.cadn.net.cn

访问用户名(如果已配置)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.client.password.spring-doc.cadn.net.cn

访问密码(如果已配置)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.tenant-namespring-doc.cadn.net.cn

租户(Chroma Cloud必备)spring-doc.cadn.net.cn

Spring租客spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.database-namespring-doc.cadn.net.cn

数据库名称(Chroma Cloud 需要)spring-doc.cadn.net.cn

SpringAi数据库spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.collection-namespring-doc.cadn.net.cn

收藏名称spring-doc.cadn.net.cn

春季收藏spring-doc.cadn.net.cn

spring.ai.vectorstore.chroma.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式(如果不存在,创建租户/数据库/集合)spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

对于采用静态APITokens认证保护的ChromaDB,请使用ChromaApi#withKeyToken(<你的Tokens凭证>)设置你的凭证的方法。检查ChromaWhereIT举个例子。spring-doc.cadn.net.cn

对于使用 Basic 认证保护的 ChromaDB,可以使用ChromaApi#withBasicAuth(<你的用户>,<你的密码>)设置你的凭证的方法。检查BasicAuthChromaWhereIT举个例子。spring-doc.cadn.net.cn

Chroma Cloud 配置

对于Chroma Cloud,你需要提供Chroma Cloud实例中的租户名和数据库名称。这里有一个示例配置:spring-doc.cadn.net.cn

# 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)- 您必须通过以下方式提供您的API密钥密钥Tokens- 租户和数据库名称必须与你的Chroma Cloud配置一致 -设置initialize-schema=true如果集合不存在,它会自动创建(它不会重建现有租户/数据库)spring-doc.cadn.net.cn

元数据过滤

你也可以利用通用的、便携式的元数据过滤器和ChromaVector存储。spring-doc.cadn.net.cn

例如,你可以使用以下文本表达式语言:spring-doc.cadn.net.cn

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

或者程序化地使用滤波。表达DSL:spring-doc.cadn.net.cn

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哪里 过滤表达

例如,这个可移植的Filter表达式:spring-doc.cadn.net.cn

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

转换为专有的Chroma格式spring-doc.cadn.net.cn

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

手动配置

如果你更喜欢手动配置Chroma矢量存储,可以通过创建一个色矢量存储在你的Spring Boot应用中加入豆子。spring-doc.cadn.net.cn

将这些依赖添加到你的项目中:* Chroma VectorStore。spring-doc.cadn.net.cn

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-chroma-store</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.ai</groupId>
 <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。

示例代码

创建一个RestClient.Builder实例中带有适当的ChromaDB授权配置,并用它来创建色素API实例:spring-doc.cadn.net.cn

@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 客户端的实现:spring-doc.cadn.net.cn

@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();
}

在你的主代码中,创建一些文档:spring-doc.cadn.net.cn

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")));

将文档添加到你的矢量存储中:spring-doc.cadn.net.cn

vectorStore.add(documents);

最后,检索类似查询的文档:spring-doc.cadn.net.cn

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

如果一切顺利,你应该取回包含“春季AI超棒!!”文字的文档。spring-doc.cadn.net.cn

本地运行Chroma

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