跳到主要内容

Chroma

DeepSeek V3 中英对照 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>
xml

或者添加到你的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-chroma-store-spring-boot-starter'
}
groovy
提示

请参考依赖管理部分,将 Spring AI BOM 添加到你的构建文件中。

提示

请参阅 Repositories 部分,以将 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(new OpenAiApi(System.getenv("SPRING_AI_OPENAI_API_KEY")));
}
java

要连接到 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>
properties

请查看向量存储的配置参数列表,以了解默认值和配置选项。

现在你可以在应用程序中自动装配 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());
java

配置属性

你可以在 Spring Boot 配置中使用以下属性来自定义向量存储(vector store)。

属性描述默认值
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是否初始化所需的架构false
备注

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

对于使用基本认证保护的 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());
java

或者通过编程方式使用 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());
java
备注

这些(可移植的)过滤表达式会自动转换为 Chroma 专有的 where 过滤表达式

例如,这个可移植的过滤表达式:

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

转换为专有的 Chroma 格式

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

手动配置

如果你更喜欢手动配置 Chroma 向量存储,你可以在你的 Spring Boot 应用程序中创建一个 ChromaVectorStore bean。

将这些依赖项添加到你的项目中:* Chroma VectorStore。

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-chroma-store</artifactId>
</dependency>
xml
  • OpenAI:用于计算嵌入(embeddings)。你可以使用任何其他嵌入模型实现。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
xml

:::提示
请参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。
:::

示例代码

创建一个具有正确 ChromaDB 授权配置的 RestClient.Builder 实例,并使用它来创建一个 ChromaApi 实例:

RestClient.Builder restClientBuilder = RestClient.builder()
.setDefaultHeaders(new HttpHeaders() {{
add("Authorization", "Bearer YOUR_CHROMADB_API_KEY");
}});

ChromaApi chromaApi = new ChromaApi(restClientBuilder.build());
java
@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;
}
java

通过将 Spring Boot OpenAI starter 添加到你的项目中,与 OpenAI 的 embeddings 集成。这将为你提供一个 Embeddings 客户端的实现:

@Bean
public VectorStore chromaVectorStore(EmbeddingModel embeddingModel, ChromaApi chromaApi) {
return ChromaVectorStore.builder(chromaApi, embeddingModel)
.collectionName("TestCollection")
.initializeSchema(true)
.build();
}
java

在你的主代码中,创建一些文档:

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

将文档添加到你的向量存储中:

vectorStore.add(documents);
java

最后,检索与查询相似的文档:

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

如果一切顺利,你应该能检索到包含文本 "Spring AI rocks!!" 的文档。

本地运行 Chroma

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

localhost:8000/api/v1 启动一个 chroma 存储