πŸ€– AI/ML

Chroma

ChromaDB - Open Source Embedding Database

An open-source embedding (vector) database. It integrates easily with major AI frameworks such as LangChain and LlamaIndex and is widely used for building RAG systems, semantic search, and AI application development.

πŸ“– Detailed Explanation

Chroma (ChromaDB) is an AI-native open-source embedding database, a system that stores data such as text and images in vector (embedding) form and enables similarity-based search. As its slogan "The AI-native open-source embedding database" suggests, it is optimized for developing LLM-based applications and plays a key role, in particular, in building RAG (Retrieval-Augmented Generation) systems.

Chroma was developed by a startup founded in 2022 and quickly gained popularity alongside the rapid growth of LLM applications. It is provided as fully open source under the Apache 2.0 license and supports a variety of environments, from local development to production deployment. It is natively integrated with major AI frameworks such as LangChain, LlamaIndex, and Haystack, so developers can adopt it easily.

The core principle of Chroma is similarity search in a high-dimensional vector space. After text or images are converted into vectors of hundreds to thousands of dimensions through an embedding model, the most similar items are searched efficiently using metrics such as Cosine Similarity, L2 distance (Euclidean Distance), and Inner Product. It uses the HNSW (Hierarchical Navigable Small World) algorithm to provide fast search performance even on large-scale datasets.

In practice, Chroma is used for a variety of purposes. It is used in RAG systems to store document chunks and retrieve the context relevant to a question, and it is also applied to building semantic search engines, recommendation systems, duplicate detection, clustering, and more. It supports metadata filtering, so vector search can be combined with traditional filtering, and it offers flexible deployment options ranging from local in-memory mode to client-server mode and cloud hosting.

πŸ’» Code Example

This is Python code that uses Chroma to store documents and perform semantic search.

Python
# pip install chromadb openai
import chromadb
from chromadb.utils import embedding_functions

# Chroma ν΄λΌμ΄μ–ΈνŠΈ 생성 (영ꡬ μ €μž₯μ†Œ μ‚¬μš©)
client = chromadb.PersistentClient(path="./chroma_db")

# OpenAI μž„λ² λ”© ν•¨μˆ˜ μ„€μ •
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
    api_key="your-openai-api-key",
    model_name="text-embedding-3-small"  # λ˜λŠ” text-embedding-3-large
)

# μ»¬λ ‰μ…˜ 생성 λ˜λŠ” κ°€μ Έμ˜€κΈ°
collection = client.get_or_create_collection(
    name="documents",
    embedding_function=openai_ef,
    metadata={"hnsw:space": "cosine"}  # μœ μ‚¬λ„ λ©”νŠΈλ¦­ μ„€μ •
)

# λ¬Έμ„œ μΆ”κ°€
documents = [
    "인곡지λŠ₯은 μΈκ°„μ˜ ν•™μŠ΅λŠ₯λ ₯κ³Ό μΆ”λ‘ λŠ₯λ ₯을 μ»΄ν“¨ν„°λ‘œ κ΅¬ν˜„ν•˜λŠ” κΈ°μˆ μž…λ‹ˆλ‹€.",
    "λ¨Έμ‹ λŸ¬λ‹μ€ λ°μ΄ν„°λ‘œλΆ€ν„° νŒ¨ν„΄μ„ ν•™μŠ΅ν•˜μ—¬ μ˜ˆμΈ‘ν•˜λŠ” AI의 ν•˜μœ„ λΆ„μ•Όμž…λ‹ˆλ‹€.",
    "λ”₯λŸ¬λ‹μ€ 인곡 신경망을 μ‚¬μš©ν•˜μ—¬ λ³΅μž‘ν•œ νŒ¨ν„΄μ„ ν•™μŠ΅ν•˜λŠ” κΈ°λ²•μž…λ‹ˆλ‹€.",
    "μžμ—°μ–΄ 처리(NLP)λŠ” 컴퓨터가 μΈκ°„μ˜ μ–Έμ–΄λ₯Ό μ΄ν•΄ν•˜κ³  μƒμ„±ν•˜λŠ” κΈ°μˆ μž…λ‹ˆλ‹€.",
    "RAGλŠ” 검색과 생성을 κ²°ν•©ν•˜μ—¬ LLM의 응닡 ν’ˆμ§ˆμ„ λ†’μ΄λŠ” κΈ°λ²•μž…λ‹ˆλ‹€."
]

# 메타데이터와 ν•¨κ»˜ λ¬Έμ„œ μΆ”κ°€
collection.add(
    documents=documents,
    metadatas=[
        {"category": "AI", "level": "basic"},
        {"category": "ML", "level": "intermediate"},
        {"category": "DL", "level": "advanced"},
        {"category": "NLP", "level": "intermediate"},
        {"category": "RAG", "level": "advanced"}
    ],
    ids=[f"doc_{i}" for i in range(len(documents))]
)

print(f"μ»¬λ ‰μ…˜μ— {collection.count()}개의 λ¬Έμ„œκ°€ μ €μž₯λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")

# μ‹œλ§¨ν‹± 검색 μˆ˜ν–‰
def semantic_search(query: str, n_results: int = 3, filter_dict: dict = None):
    """
    μ‹œλ§¨ν‹± 검색을 μˆ˜ν–‰ν•˜λŠ” ν•¨μˆ˜

    Args:
        query: 검색 쿼리
        n_results: λ°˜ν™˜ν•  κ²°κ³Ό 수
        filter_dict: 메타데이터 ν•„ν„° (예: {"category": "AI"})

    Returns:
        검색 κ²°κ³Ό
    """
    results = collection.query(
        query_texts=[query],
        n_results=n_results,
        where=filter_dict,  # 메타데이터 필터링
        include=["documents", "metadatas", "distances"]
    )

    return results

# 검색 μ˜ˆμ‹œ 1: 일반 μ‹œλ§¨ν‹± 검색
print("\n=== 검색: '신경망과 ν•™μŠ΅' ===")
results = semantic_search("신경망과 ν•™μŠ΅")
for doc, meta, dist in zip(
    results['documents'][0],
    results['metadatas'][0],
    results['distances'][0]
):
    print(f"[μœ μ‚¬λ„: {1-dist:.4f}] {doc[:50]}... ({meta['category']})")

# 검색 μ˜ˆμ‹œ 2: 메타데이터 필터링과 ν•¨κ»˜
print("\n=== 검색: 'AI 기술' (κ³ κΈ‰ μˆ˜μ€€λ§Œ) ===")
results = semantic_search(
    "AI 기술",
    n_results=2,
    filter_dict={"level": "advanced"}
)
for doc, meta in zip(results['documents'][0], results['metadatas'][0]):
    print(f"[{meta['level']}] {doc[:50]}...")

# LangChain 톡합 μ˜ˆμ‹œ
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings

# LangChain용 Chroma λ²‘ν„°μŠ€ν† μ–΄
vectorstore = Chroma(
    collection_name="langchain_docs",
    embedding_function=OpenAIEmbeddings(),
    persist_directory="./langchain_chroma_db"
)

# λ¦¬νŠΈλ¦¬λ²„λ‘œ μ‚¬μš©
retriever = vectorstore.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 3}
)

πŸ—£οΈ How It's Said in Practice

Team Lead "We need to decide on a vector database for the RAG system. Which would be better, Chroma or Pinecone?"
Developer "For a prototype or a small-scale project, Chroma is a good choice. It's open source, can run right away locally, and its LangChain integration is simple. And it costs nothing."
Team Lead "What about using it at large scale in production?"
Developer "At large scale, managed services like Pinecone or Weaviate are more stable. But Chroma can also be deployed in server mode, and it adequately covers up to millions of documents. Let's weigh performance against cost and decide."
Interviewer "Please explain how the HNSW algorithm works in Chroma."
Candidate "HNSW uses a hierarchical graph structure. It quickly finds an approximate location in the upper layers, then descends to the lower layers and searches precisely. It can find approximate nearest neighbors at roughly O(log N) without scanning all the vectors."
Interviewer "How do you adjust the trade-off between accuracy and speed?"
Candidate "You adjust it with the ef_search parameter. The larger the value, the more nodes are explored, so accuracy goes up but speed goes down. You can also adjust the graph's connectivity with the ef_construction and M values when building the index."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Senior "You're creating a new PersistentClient on every request. That's inefficient."
Junior "Ah, so I should create the client once globally and reuse it. I'll change it to a singleton pattern."
Senior "Right. Also, collection.add() has no duplicate ID check. If you add the same document again, you get an error rather than an upsert. Check for existence with get(), or use upsert()."
Junior "I'll change it to collection.upsert(), and also adjust the batch size to prevent memory issues during bulk insertion."

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More