このバージョンはまだ開発中であり、まだ安定しているとは考えられていません。最新のスナップショットバージョンについては、Spring AI 1.0.3 を使用してください。

Chroma

このセクションでは、ドキュメントの埋め込みを保存し、類似性検索を実行するための Chroma VectorStore のセットアップについて説明します。

Chroma (英語) は、オープンソースの埋め込みデータベースです。これにより、ドキュメントの埋め込み、コンテンツ、メタデータを保存し、メタデータのフィルタリングなど、それらの埋め込みを検索するためのツールが提供されます。

前提条件

  1. ChromaDB へのアクセス。Chroma クラウド (英語) と互換性があります。または、付録のローカル ChromaDB をセットアップして、 Docker コンテナーを使用してローカルに DB をセットアップする方法を示します。

    • Chroma クラウド向け: Chroma Cloud ダッシュボードから API キー、テナント名、データベース名が必要になります。

    • ローカル ChromaDB の場合: コンテナーを起動する以外に追加の構成は必要ありません。

  2. EmbeddingModel インスタンスを使用してドキュメントの埋め込みを計算します。いくつかのオプションが利用可能です:

    • 必要に応じて、EmbeddingModel が ChromaVectorStore によって保存される埋め込みを生成するための API キー。

まだプロビジョニングされていない場合、ChromaVectorStore は起動時に必要なコレクションを作成します。

自動構成

Spring AI 自動構成、スターターモジュールのアーティファクト名に大きな変更がありました。詳細については、アップグレードノートを参照してください。

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 をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。
アーティファクトリポジトリセクションを参照して、ビルドファイルに Maven Central リポジトリやスナップショットリポジトリを追加します。

ベクトルストアの実装では必要なスキーマを初期化できますが、適切なコンストラクターで 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 クラウドに必要)

SpringAiTenant

spring.ai.vectorstore.chroma.database-name

データベース名 (Chroma クラウドに必要)

SpringAiDatabase

spring.ai.vectorstore.chroma.collection-name

コレクション名

SpringAiCollection

spring.ai.vectorstore.chroma.initialize-schema

必要なスキーマを初期化するかどうか (テナント / データベース / コレクションが存在しない場合は作成します)

false

静的 API トークン認証 (英語) で保護された ChromaDB の場合は、ChromaApi#withKeyToken(<Your Token Credentials>) メソッドを使用して認証情報を設定します。例として ChromaWhereIT を確認してください。

基本認証 (英語) で保護された ChromaDB の場合は、ChromaApi#withBasicAuth(<your user>, <your password>) メソッドを使用して認証情報を設定します。例として BasicAuthChromaWhereIT を確認してください。

Chroma クラウド構成

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 クラウド向け: - ホストは api.trychroma.com である必要があります - ポートは 443 (HTTPS)である必要があります - API キーは key-token 経由で提供する必要があります - テナント名とデータベース名は Chroma クラウド構成と一致する必要があります - コレクションが存在しない場合は自動的に作成するように 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 の埋め込みと統合します。これにより、埋め込みクライアントの実装が提供されます。

@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 でクロマストアを開始します