mcpField
C
chroma

chroma

github.com/kalarislabsデータ・データベース7746 回インストール4 日前に更新
リポジトリ

chroma について

Chromaは、LLMアプリケーション向けのオープンソース埋め込みデータベースで、RAGやセマンティック検索に利用できます。メタデータ付き文書の保存、類似検索、ローカル永続化、サーバーモードに対応します。

主な機能

  1. 01埋め込みコレクションと文書の保存
  2. 02メタデータフィルター付き類似検索
  3. 03ローカル永続ストレージ
  4. 04設定可能な埋め込み関数
  5. 05クライアント接続用のサーバーモード

活用シーン

  1. 01RAGアプリケーションの構築
  2. 02文書のセマンティック検索
  3. 03メタデータ付き埋め込み文書の保存と検索

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill chroma

インストール後、Claude Code で/chromaを入力して読み込まれたか確認します。

同梱ファイルreferences/integration.md

詳細

Chroma - オープンソースの埋め込みデータベース

メモリを備えた LLM アプリケーションを構築するための、AI ネイティブなデータベースです。

Chroma を使用する場面

次のような場合に Chroma を使用します。

  • RAG(検索拡張生成)アプリケーションを構築する場合
  • ローカルまたはセルフホスト可能なベクトルデータベースが必要な場合
  • オープンソースのソリューション(Apache 2.0)を利用したい場合
  • ノートブックでプロトタイプを作成する場合
  • ドキュメントを対象にセマンティック検索を行う場合
  • メタデータとともに埋め込みを保存する場合

指標:

  • 1,900+ forks
  • v1.3.3(安定版、毎週リリース)
  • Apache 2.0 ライセンス

代わりに次の選択肢を使用します。

  • Pinecone:マネージドクラウド、自動スケーリング
  • FAISS:類似度検索専用、メタデータなし
  • Weaviate:本番環境向けの ML ネイティブデータベース
  • Qdrant:高性能、Rust ベース

クイックスタート

インストール
# Python
pip install chromadb

# JavaScript/TypeScript
npm install chromadb @chroma-core/default-embed
基本的な使い方(Python)
import chromadb

# Create client
client = chromadb.Client()

# Create collection
collection = client.create_collection(name="my_collection")

# Add documents
collection.add(
    documents=["This is document 1", "This is document 2"],
    metadatas=[{"source": "doc1"}, {"source": "doc2"}],
    ids=["id1", "id2"]
)

# Query
results = collection.query(
    query_texts=["document about topic"],
    n_results=2
)

print(results)

主な操作

1. コレクションの作成
# Simple collection
collection = client.create_collection("my_docs")

# With custom embedding function
from chromadb.utils import embedding_functions

openai_ef = embedding_functions.OpenAIEmbeddingFunction(
    api_key="your-key",
    model_name="text-embedding-3-small"
)

collection = client.create_collection(
    name="my_docs",
    embedding_function=openai_ef
)

# Get existing collection
collection = client.get_collection("my_docs")

# Delete collection
client.delete_collection("my_docs")
2. ドキュメントの追加
# Add with auto-generated IDs
collection.add(
    documents=["Doc 1", "Doc 2", "Doc 3"],
    metadatas=[
        {"source": "web", "category": "tutorial"},
        {"source": "pdf", "page": 5},
        {"source": "api", "timestamp": "2025-01-01"}
    ],
    ids=["id1", "id2", "id3"]
)

# Add with custom embeddings
collection.add(
    embeddings=[[0.1, 0.2, ...], [0.3, 0.4, ...]],
    documents=["Doc 1", "Doc 2"],
    ids=["id1", "id2"]
)
3. クエリ(類似度検索)
# Basic query
results = collection.query(
    query_texts=["machine learning tutorial"],
    n_results=5
)

# Query with filters
results = collection.query(
    query_texts=["Python programming"],
    n_results=3,
    where={"source": "web"}
)

# Query with metadata filters
results = collection.query(
    query_texts=["advanced topics"],
    where={
        "$and": [
            {"category": "tutorial"},
            {"difficulty": {"$gte": 3}}
        ]
    }
)

# Access results
print(results["documents"])      # List of matching documents
print(results["metadatas"])      # Metadata for each doc
print(results["distances"])      # Similarity scores
print(results["ids"])            # Document IDs
4. ドキュメントの取得
# Get by IDs
docs = collection.get(
    ids=["id1", "id2"]
)

# Get with filters
docs = collection.get(
    where={"category": "tutorial"},
    limit=10
)

# Get all documents
docs = collection.get()
5. ドキュメントの更新
# Update document content
collection.update(
    ids=["id1"],
    documents=["Updated content"],
    metadatas=[{"source": "updated"}]
)
6. ドキュメントの削除
# Delete by IDs
collection.delete(ids=["id1", "id2"])

# Delete with filter
collection.delete(
    where={"source": "outdated"}
)

永続ストレージ

# Persist to disk
client = chromadb.PersistentClient(path="./chroma_db")

collection = client.create_collection("my_docs")
collection.add(documents=["Doc 1"], ids=["id1"])

# Data persisted automatically
# Reload later with same path
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_collection("my_docs")

埋め込み関数

デフォルト(Sentence Transformers)
# Uses sentence-transformers by default
collection = client.create_collection("my_docs")
# Default model: all-MiniLM-L6-v2
OpenAI
from chromadb.utils import embedding_functions

openai_ef = embedding_functions.OpenAIEmbeddingFunction(
    api_key="your-key",
    model_name="text-embedding-3-small"
)

collection = client.create_collection(
    name="openai_docs",
    embedding_function=openai_ef
)
HuggingFace
huggingface_ef = embedding_functions.HuggingFaceEmbeddingFunction(
    api_key="your-key",
    model_name="sentence-transformers/all-mpnet-base-v2"
)

collection = client.create_collection(
    name="hf_docs",
    embedding_function=huggingface_ef
)
カスタム埋め込み関数
from chromadb import Documents, EmbeddingFunction, Embeddings

class MyEmbeddingFunction(EmbeddingFunction):
    def __call__(self, input: Documents) -> Embeddings:
        # Your embedding logic
        return embeddings

my_ef = MyEmbeddingFunction()
collection = client.create_collection(
    name="custom_docs",
    embedding_function=my_ef
)

メタデータのフィルタリング

# Exact match
results = collection.query(
    query_texts=["query"],
    where={"category": "tutorial"}
)

# Comparison operators
results = collection.query(
    query_texts=["query"],
    where={"page": {"$gt": 10}}  # $gt, $gte, $lt, $lte, $ne
)

# Logical operators
results = collection.query(
    query_texts=["query"],
    where={
        "$and": [
            {"category": "tutorial"},
            {"difficulty": {"$lte": 3}}
        ]
    }  # Also: $or
)

# Contains
results = collection.query(
    query_texts=["query"],
    where={"tags": {"$in": ["python", "ml"]}}
)

LangChain との統合

from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter

# Split documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000)
docs = text_splitter.split_documents(documents)

# Create Chroma vector store
vectorstore = Chroma.from_documents(
    documents=docs,
    embedding=OpenAIEmbeddings(),
    persist_directory="./chroma_db"
)

# Query
results = vectorstore.similarity_search("machine learning", k=3)

# As retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})

LlamaIndex との統合

from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import VectorStoreIndex, StorageContext
import chromadb

# Initialize Chroma
db = chromadb.PersistentClient(path="./chroma_db")
collection = db.get_or_create_collection("my_collection")

# Create vector store
vector_store = ChromaVectorStore(chroma_collection=collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

# Create index
index = VectorStoreIndex.from_documents(
    documents,
    storage_context=storage_context
)

# Query
query_engine = index.as_query_engine()
response = query_engine.query("What is machine learning?")

サーバーモード

# Run Chroma server
# Terminal: chroma run --path ./chroma_db --port 8000

# Connect to server
import chromadb
from chromadb.config import Settings

client = chromadb.HttpClient(
    host="localhost",
    port=8000,
    settings=Settings(anonymized_telemetry=False)
)

# Use as normal
collection = client.get_or_create_collection("my_docs")

ベストプラクティス

  1. 永続クライアントを使用する - 再起動時にデータが失われないようにします
  2. メタデータを追加する - フィルタリングと追跡が可能になります
  3. 操作をバッチ処理する - 複数のドキュメントを一度に追加します
  4. 適切な埋め込みモデルを選ぶ - 速度と品質のバランスを取ります
  5. フィルターを使用する - 検索範囲を絞り込みます
  6. 一意の ID を使用する - 重複を避けます
  7. 定期的にバックアップする - chroma_db ディレクトリをコピーします
  8. コレクションのサイズを監視する - 必要に応じてスケールアップします
  9. 埋め込み関数をテストする - 品質を確認します
  10. 本番環境ではサーバーモードを使用する - 複数ユーザーでの利用に適しています

パフォーマンス

操作レイテンシ備考
100 件のドキュメントを追加~1-3s埋め込み処理を含む
クエリ(上位 10 件)~50-200msコレクションのサイズによって異なります
メタデータフィルター~10-50ms適切なインデックスがあれば高速

リソース

エージェントの作業手順

  1. 環境を確認します。 コーパス、埋め込みモデル、ベクトルストアのバージョンと、インデックスの保存先を確認します。
  2. 入力を明確にします。 データまたはユーザーから、形式、識別子、パラメーターを確認します。結果を左右する値は推測せず、質問してください。
  3. まず小規模に実行します。 小さなサブセットをインデックス化し、既知の質問と該当箇所の組み合わせで検索をテストします。
  4. 上記の手順と参考資料を使用して、タスク全体を実行します。
  5. 結果を検証します。 ラベル付きデータセットで recall@k を測定し、回答が取得した該当箇所のみを引用していることを確認します。
  6. 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確定の事項を伝えます。
このような場合対応
検索結果に無関係なチャンクが含まれるチャンク分割を見直す、BM25/ハイブリッド検索を追加する、または生成モデルを変更する前に再ランキングします。
この手順に記載された関数、フラグ、またはエンドポイントがインストール済みのバージョンにないインストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認し、適宜調整してユーザーに伝えます。API を捏造してはいけません。
必須の入力、識別子、またはパラメーターが曖昧ユーザーに質問するか、実行前に前提を明示します。

誠実性に関するルール

  • 結果、パラメーター、識別子、引用、統計を決して捏造してはいけません。実行または検証できないことがあれば、明確に伝えます。
  • 回答は取得したテキストに基づく必要があります。コーパスに回答が含まれていない場合は、その旨を伝えます。
  • ここに記載されているバージョン固有の情報は古くなっている可能性があります。インストール済みバージョンの公式ドキュメントで確認してください。
  • 費用が発生する、共有 GPU またはクラウドのクォータを消費する、個人データまたは患者データを扱う、または元に戻せない操作を行う前には、ユーザーに確認します。

関連スキル

  • llamaindex:RAG を使った LLM アプリケーション構築用のデータフレームワーク。
  • langchain:エージェント、チェーン、RAG を使った LLM 搭載アプリケーション構築用のフレームワーク。
  • qdrant-vector-search:RAG とセマンティック検索向けの高性能なベクトル類似検索エンジン。

コメント