Embeddings: """ input: list of strings to embed return: list of lists of floats (one vector per string) """ embeddings = [] for text in input: # Replace with your actual embedding logic vector = self._embed_text(text) embeddings.append(vector) return embeddings def _embed_text(self, text: str) -> List[float]: # Example: fixed-dim hash-based mock (not for production) import hashlib h = hashlib.md5(text.encode()).digest() return [b / 255.0 for b in h] # 16-dim mock vector # Use your custom function exactly like a built-in one client = chromadb.Client() custom_ef = MyCustomEmbeddingFunction() collection = client.create_collection( name="custom_embed", embedding_function=custom_ef, ) collection.add( documents=["Test document one", "Test document two"], ids=["c1", "c2"], ) results = collection.query( query_texts=["test"], n_results=1, ) print(results["ids"]) # [["c1"]] or [["c2"]] When to write a custom embedding function: Your company uses a proprietary or self-hosted embedding model You need to embed data from a provider not in ChromaDB's built-in list You want to add preprocessing (text cleaning, chunking, domain adaptation) before embedding Testing — inject a deterministic mock that returns predictable vectors __call__(self, input: Documents) -> Embeddings — a callable that takes a list of strings and returns a list of float lists"> Embeddings: """ input: list of strings to embed return: list of lists of floats (one vector per string) """ embeddings = [] for text in input: # Replace with your actual embedding logic vector = self._embed_text(text) embeddings.append(vector) return embeddings def _embed_text(self, text: str) -> List[float]: # Example: fixed-dim hash-based mock (not for production) import hashlib h = hashlib.md5(text.encode()).digest() return [b / 255.0 for b in h] # 16-dim mock vector # Use your custom function exactly like a built-in one client = chromadb.Client() custom_ef = MyCustomEmbeddingFunction() collection = client.create_collection( name="custom_embed", embedding_function=custom_ef, ) collection.add( documents=["Test document one", "Test document two"], ids=["c1", "c2"], ) results = collection.query( query_texts=["test"], n_results=1, ) print(results["ids"]) # [["c1"]] or [["c2"]] When to write a custom embedding function: Your company uses a proprietary or self-hosted embedding model You need to embed data from a provider not in ChromaDB's built-in list You want to add preprocessing (text cleaning, chunking, domain adaptation) before embedding Testing — inject a deterministic mock that returns predictable vectors __call__(self, input: Documents) -> Embeddings — a callable that takes a list of strings and returns a list of float lists" />

Prev Next

Database / ChromaDB Interview Questions

How do you create a custom embedding function for ChromaDB?

ChromaDB defines a simple protocol for embedding functions: a class with a __call__ method that accepts a list of strings and returns a list of embedding vectors. Implementing this interface lets you plug in any model — a local transformer, a third-party API, or even a mock for testing.

import chromadb
from chromadb import Documents, EmbeddingFunction, Embeddings
from typing import List

# Custom embedding function — must implement __call__
class MyCustomEmbeddingFunction(EmbeddingFunction):
    """Wraps any embedding model in ChromaDB's interface."""

    def __init__(self, model_name: str = "my-model"):
        # Load your model here
        self.model_name = model_name
        # self.model = load_model(model_name)

    def __call__(self, input: Documents) -> Embeddings:
        """
        input:  list of strings to embed
        return: list of lists of floats (one vector per string)
        """
        embeddings = []
        for text in input:
            # Replace with your actual embedding logic
            vector = self._embed_text(text)
            embeddings.append(vector)
        return embeddings

    def _embed_text(self, text: str) -> List[float]:
        # Example: fixed-dim hash-based mock (not for production)
        import hashlib
        h = hashlib.md5(text.encode()).digest()
        return [b / 255.0 for b in h]  # 16-dim mock vector


# Use your custom function exactly like a built-in one
client = chromadb.Client()
custom_ef = MyCustomEmbeddingFunction()

collection = client.create_collection(
    name="custom_embed",
    embedding_function=custom_ef,
)
collection.add(
    documents=["Test document one", "Test document two"],
    ids=["c1", "c2"],
)
results = collection.query(
    query_texts=["test"],
    n_results=1,
)
print(results["ids"])  # [["c1"]] or [["c2"]]

When to write a custom embedding function:

  • Your company uses a proprietary or self-hosted embedding model
  • You need to embed data from a provider not in ChromaDB's built-in list
  • You want to add preprocessing (text cleaning, chunking, domain adaptation) before embedding
  • Testing — inject a deterministic mock that returns predictable vectors
Why might you create a custom embedding function for testing ChromaDB code?
What is the minimum interface a custom ChromaDB embedding function must implement?

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