AI Workflows

Complete ChromaDB Tutorial for AI Developers

Learn how to effectively utilize ChromaDB, a local vector database, for storing high-dimensional embeddings and enabling advanced semantic search.

5 min read

ChromaDB is a local vector database designed for efficiently managing high-dimensional embeddings. Essential for tasks like semantic search, recommendation systems, and extending the capabilities of large language models (LLMs), ChromaDB offers a robust foundation for AI applications. This guide will provide an in-depth, step-by-step tutorial for developers looking to implement ChromaDB in their projects.

Overview of Vector Databases

Vector databases are specialized storage solutions for high-dimensional embeddings. These embeddings represent unstructured data like text, images, and audio as numerical vectors, making similarity searches and semantic queries possible. Popular use cases include:

  • Recommendation Systems: Suggesting content based on similarity.
  • Semantic Search: Retrieving relevant results by meaning rather than keywords.
  • LLMs and AI Applications: Providing long-term memory and context to improve LLM-generated responses.

Popular vector databases include:

  • ChromaDB (local)
  • Pinecone (managed cloud)
  • Weaviate (cloud-hosted or on-premise solution)

ChromaDB specializes as a lightweight, efficient local solution for embeddings.

Setting Up ChromaDB Locally

To get started, we need a working Python environment. We'll install necessary dependencies and configure ChromaDB.

prerequisites

  • Python 3.8 or higher
  • pip for package management
  • API key for OpenAI (for generating embeddings via OpenAI models)
  • Minimal familiarity with Python and vector database concepts

steps

  1. Install Required Packages: Install chromadb, langchain, openai, and related dependencies.
bash
   pip install chromadb langchain openai tiktoken
  1. Verify Installations: Ensure that the installed versions meet your requirements.
bash
   pip show chromadb
   # Output example:
   # Name: chromadb
   # Version: 0.3.21
  1. Set Up Environment Variables: Set your API key for OpenAI to use embeddings later.

    python
    import os
    os.environ["OPENAI_API_KEY"] = "your_openai_api_key"

Loading and Splitting Data

Before storing data in ChromaDB, it is split into manageable chunks. This step ensures compatibility with LLM token limits and improves query performance.

steps

  1. Load Documents: Use the LangChain DirectoryLoader to load text files or .pdf documents.

    python
    from langchain.document_loaders import DirectoryLoader, TextLoader
    
    loader = DirectoryLoader("data_folder", glob="*.txt", loader_cls=TextLoader)
    documents = loader.load()
  2. Split Data: Use RecursiveCharacterTextSplitter to divide documents into chunks while maintaining context.

    python
    from langchain.text_splitter import RecursiveCharacterTextSplitter
    
    splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
    chunks = splitter.split_documents(documents)
    print(len(chunks))  # Number of document chunks

Using Embeddings to Create Vectors

With preprocessed chunks, the next step is to generate embeddings and store the resulting vectors in the database.

steps

  1. Initialize OpenAI Embeddings: Load the default embedding model using LangChain’s OpenAIEmbeddings.

    python
    from langchain.embeddings import OpenAIEmbeddings
    
    embedding = OpenAIEmbeddings()
  2. Store Embeddings in ChromaDB: Use the from_documents function from LangChain’s Chroma integration.

    python
    from langchain.vectorstores import Chroma
    
    db = Chroma.from_documents(
        chunks, 
        embedding, 
        persist_directory="chroma_db"
    )
    db.persist()
  3. Reload Database: After saving, reload the database for later use.

    python
    db = Chroma(
        persist_directory="chroma_db", 
        embedding_function=embedding
    )

Performing Semantic Search in ChromaDB

ChromaDB allows for efficient semantic search using the stored vector embeddings.

steps

  1. Query the Database: Use the similarity_search method to retrieve relevant chunks.

    python
    query = "What are the benefits of using vector databases?"
    results = db.similarity_search(query, k=2)  # Retrieves top-2 results
    print(results)
  2. Integrate with LangChain: To enhance responses, integrate ChromaDB with LangChain's RetrievalQA.

    python
    from langchain.chains import RetrievalQA
    from langchain.llms import OpenAI
    
    retriever = db.as_retriever(search_kwargs={"k": 2})
    llm = OpenAI(temperature=0)
    qa_chain = RetrievalQA.from_chain_type(
        llm=llm, 
        chain_type="stuff", 
        retriever=retriever, 
        return_source_documents=True
    )
    
    question = "What is ChromaDB used for?"
    response = qa_chain.run(question)
    print(response)

Deleting and Managing ChromaDB Data

ChromaDB saves data locally, allowing for manual cleanup or migration.

Comparing ChromaDB with Pinecone and Weaviate

comparison

ChromaDB

  • Local-first vector database, no internet dependency.
  • Ideal for prototyping and local development.
  • Free-to-use and open-source.

Pinecone

  • A fully managed vector database service hosted in the cloud.
  • Suitable for scalable and production environments.

Weaviate

  • Cloud-hosted or on-premise vector DB with a flexible schema.
  • Useful for advanced AI workflows that require diverse integrations.

FAQ

What is ChromaDB used for in AI applications?

ChromaDB is a local vector database for storing high-dimensional embeddings. It is widely used for semantic search, LLM memory systems, and recommendation engines.

How is ChromaDB different from Pinecone?

ChromaDB is a lightweight, local-first solution ideal for prototyping and offline use. Pinecone, on the other hand, is a managed cloud service, designed for scalable, production-grade vector database needs.

What kind of embeddings can I use with ChromaDB?

ChromaDB supports a variety of embedding models, including OpenAI embeddings, Hugging Face transformers, and other custom embeddings.

How do I delete data from ChromaDB?

You can delete the ChromaDB database by removing its persistent directory. Use a terminal command like rm -r chroma_db/ to clean up the files.


Official reference: Chroma documentation.