Database / ChromaDB Interview Questions
How do you use the OpenAI embedding function with ChromaDB?
ChromaDB has a built-in OpenAIEmbeddingFunction that calls the OpenAI Embeddings API. This gives higher-quality embeddings than the default local model, at the cost of API latency and usage fees. Use text-embedding-3-small for a balance of quality and cost, or text-embedding-3-large for maximum quality.
import chromadb
from chromadb.utils import embedding_functions
import os
client = chromadb.PersistentClient(path="./chroma_openai")
# Built-in OpenAI embedding function
ef_openai = embedding_functions.OpenAIEmbeddingFunction(
api_key=os.environ["OPENAI_API_KEY"],
model_name="text-embedding-3-small", # 1536-dim, fast and cheap
# model_name="text-embedding-3-large", # 3072-dim, highest quality
# model_name="text-embedding-ada-002", # legacy, 1536-dim
)
collection = client.get_or_create_collection(
name="openai_docs",
embedding_function=ef_openai,
metadata={"hnsw:space": "cosine"},
)
# Usage is identical to the default embedding function
collection.add(
documents=[
"FastAPI is a modern Python web framework for building APIs.",
"ChromaDB stores embeddings for semantic search.",
],
ids=["d1", "d2"],
)
# ChromaDB calls OpenAI API automatically on add() and query()
results = collection.query(
query_texts=["vector database for retrieval"],
n_results=1,
)
print(results["documents"]) # [["ChromaDB stores embeddings..."]]| Model | Dimensions | Cost | Notes |
|---|---|---|---|
| text-embedding-3-small | 1536 | ~$0.02/1M tokens | Best value — recommended default |
| text-embedding-3-large | 3072 | ~$0.13/1M tokens | Highest quality |
| text-embedding-ada-002 | 1536 | ~$0.10/1M tokens | Legacy, superseded by v3 |
Important consistency rule: you must use the exact same embedding model for both storing and querying. If you embed documents with text-embedding-3-small, all queries must also use text-embedding-3-small. Mixing models produces meaningless similarity scores.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
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...
