str: # 1. Retrieve relevant chunks from ChromaDB results = collection.query( query_texts=[user_question], n_results=n_results, include=["documents", "distances"], ) context_chunks = results["documents"][0] # list of retrieved texts context = "\n\n".join( f"[{i+1}] {chunk}" for i, chunk in enumerate(context_chunks) ) # 2. Build an augmented prompt prompt = f"""Answer the question using ONLY the context below. If the answer is not in the context, say "I don't know." Context: {context} Question: {user_question} Answer:""" # 3. Generate answer with LLM openai_client = OpenAI() response = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], ) return response.choices[0].message.content print(rag_answer("What distance metrics does ChromaDB support?")) It stores and retrieves semantically relevant document chunks that are injected as context into the LLM prompt"> str: # 1. Retrieve relevant chunks from ChromaDB results = collection.query( query_texts=[user_question], n_results=n_results, include=["documents", "distances"], ) context_chunks = results["documents"][0] # list of retrieved texts context = "\n\n".join( f"[{i+1}] {chunk}" for i, chunk in enumerate(context_chunks) ) # 2. Build an augmented prompt prompt = f"""Answer the question using ONLY the context below. If the answer is not in the context, say "I don't know." Context: {context} Question: {user_question} Answer:""" # 3. Generate answer with LLM openai_client = OpenAI() response = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], ) return response.choices[0].message.content print(rag_answer("What distance metrics does ChromaDB support?")) It stores and retrieves semantically relevant document chunks that are injected as context into the LLM prompt" />

Prev Next

Database / ChromaDB Interview Questions

How do you build a basic RAG (Retrieval-Augmented Generation) pipeline with ChromaDB?

RAG combines ChromaDB's semantic retrieval with an LLM's generation ability. The pipeline has two phases: indexing (chunk documents, embed, store in ChromaDB) and retrieval (embed the user query, fetch similar chunks, inject into LLM prompt).

import chromadb
from chromadb.utils import embedding_functions
from openai import OpenAI
import os

# --- INDEXING PHASE (run once) ---
chroma_client = chromadb.PersistentClient(path="./rag_db")
ef = embedding_functions.OpenAIEmbeddingFunction(
    api_key=os.environ["OPENAI_API_KEY"],
    model_name="text-embedding-3-small",
)
collection = chroma_client.get_or_create_collection(
    "company_docs", embedding_function=ef, metadata={"hnsw:space": "cosine"}
)

# Chunk and index your knowledge base
documents = [
    "ChromaDB supports cosine, l2, and inner-product distance metrics.",
    "Persistent storage in ChromaDB uses SQLite under the hood.",
    "The default embedding model is all-MiniLM-L6-v2 with 384 dimensions.",
    "ChromaDB collections support metadata filtering with $eq, $gt, $in operators.",
]
collection.add(
    documents=documents,
    ids=[f"doc-{i}" for i in range(len(documents))],
)

# --- RETRIEVAL + GENERATION PHASE (run per query) ---
def rag_answer(user_question: str, n_results: int = 3) -> str:
    # 1. Retrieve relevant chunks from ChromaDB
    results = collection.query(
        query_texts=[user_question],
        n_results=n_results,
        include=["documents", "distances"],
    )
    context_chunks = results["documents"][0]  # list of retrieved texts
    context = "\n\n".join(
        f"[{i+1}] {chunk}" for i, chunk in enumerate(context_chunks)
    )

    # 2. Build an augmented prompt
    prompt = f"""Answer the question using ONLY the context below.
    If the answer is not in the context, say "I don't know."

    Context:
    {context}

    Question: {user_question}
    Answer:"""

    # 3. Generate answer with LLM
    openai_client = OpenAI()
    response = openai_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
    )
    return response.choices[0].message.content

print(rag_answer("What distance metrics does ChromaDB support?"))
Why is retrieval-augmented generation (RAG) preferred over fine-tuning for adding domain knowledge to an LLM?
In a RAG pipeline, what role does ChromaDB play?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

What is ChromaDB and what problem does it solve? What are embeddings and why are they central to how ChromaDB works? What distance metrics does ChromaDB support and how do you choose between them? What is a ChromaDB collection and how do you create, list, get, and delete collections? How do you add documents to a ChromaDB collection? How do you query a ChromaDB collection for similar documents? How do you retrieve, update, and delete specific documents in ChromaDB? How do you filter query results using metadata in ChromaDB? What is the difference between ChromaDB's in-memory and persistent storage modes? What is ChromaDB's default embedding function and how does it work? How do you use the OpenAI embedding function with ChromaDB? How do you use HuggingFace models as embedding functions in ChromaDB? How do you create a custom embedding function for ChromaDB? How does ChromaDB's PersistentClient store data on disk, and what are its limitations? What is the HNSW index in ChromaDB and what parameters can you tune? How do you efficiently add large numbers of documents to ChromaDB using batching? What is the where_document filter in ChromaDB and how does it differ from where? How do you control what data ChromaDB returns in query and get results using include? How do you design metadata schemas for effective filtering in ChromaDB? How do you inspect a ChromaDB collection's contents and configuration? How do you build a basic RAG (Retrieval-Augmented Generation) pipeline with ChromaDB? What are effective document chunking strategies when indexing documents into ChromaDB for RAG? How do you use ChromaDB as a vector store with LangChain? How do you implement multi-tenancy or data isolation in ChromaDB? What is embedding consistency and why is it critical in ChromaDB applications? How do you run ChromaDB as a standalone HTTP server and connect to it from multiple clients? When should you use upsert() instead of add() in ChromaDB, and what are common patterns? What are best practices for structuring ChromaDB collection metadata for production use? How does ChromaDB compare to FAISS, and when should you choose one over the other? What are common ChromaDB errors and how do you handle them in production code? How do you back up and restore a ChromaDB persistent database? How do you ensure the correct embedding function is used when reopening a persistent ChromaDB collection? How do you interpret ChromaDB query distances and convert them into meaningful relevance scores? What are ChromaDB's practical size limits and performance characteristics at scale? How do you use ChromaDB to detect and remove near-duplicate or semantically similar documents? How do you reset or clear a ChromaDB collection without deleting and recreating it? What configuration settings does ChromaDB support and how do you disable telemetry? What is a production readiness checklist for a ChromaDB-based application?
Show more question and Answers...

Integration

Comments & Discussions