↓Skip to main content

Using ChromaDB as a vector store with python

·3 mins

Chroma calls itself the data infrastructure for AI. It allows you to store vector embeddings, text, images and associated metadata and allows you to search through them efficiently. A very popular use case for Chroma would be for RAG (Retrieval augmented generation) in GenAI workflows. You may have pdf documents that contain information (eg: stock analysis reports, SEC filings, medical journal articles) that you can create vector embeddings for and store them in Chroma. Then you can write a script where you can ask a question and you can do a vector similarity search using the question string against the vector embeddings stored in Chroma and the results can be fed to your LLM to summarize. If you use the disk based storage option for Chroma , it will store the metadata related to the document in a sqlite3 database and it stores the actual vector embeddings in files it creates on disk. You can directly feed text documents to Chroma and it can create the embeddings for you too.

Below is a script you can use to provide a pdf file as the input, vectorize it and store it in Chroma and create a langchain process to answer a question you ask based on that data. This script uses Amazon Titan for creating the embeddings and uses Amazon Nova lite for summarizing and answering your question.

import os
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_aws import BedrockEmbeddings
from langchain_chroma import Chroma
from langchain_aws import ChatBedrock
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help="File Name", required=True)
parser.add_argument('-m', '--model', choices=['us.anthropic.claude-3-7-sonnet-20250219-v1:0','us.anthropic.claude-3-5-sonnet-20241022-v2:0','anthropic.claude-3-5-sonnet-20240620-v1:0','us.amazon.nova-lite-v1:0'],help="Model Name choose one of us.anthropic.claude-3-7-sonnet-20250219-v1:0,us.anthropic.claude-3-5-sonnet-20241022-v2:0,anthropic.claude-3-5-sonnet-20240620-v1:0,us.amazon.nova-lite-v1:0", required=False)
args = parser.parse_args()

if not os.path.isfile(args.file):
   print('Cannot access '+args.file)
   quit()

if args.model is None:
   l_fm='us.amazon.nova-lite-v1:0'
elif args.model:
   l_fm=args.model
else:
   print('Invalid Model '+args.model)
   quit()
     
print('Using FM '+l_fm)

# Initialize Bedrock client
def init_bedrock_client():
    bedrock_client = ChatBedrock(
        region_name="us-east-1",
        model_id=l_fm,
        model_kwargs=dict(temperature=0.7)
    )
    return bedrock_client

# Load and chunk the PDF
def process_pdf(file_path):
    # Load PDF
    loader = PyPDFLoader(file_path)
    documents = loader.load()
    
    # Create text splitter
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=1000,
        chunk_overlap=100,
        separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
        length_function=len
    )
    
    # Split documents into chunks
    chunks = text_splitter.split_documents(documents)
    return chunks

# Create vector store
def create_vector_store(chunks):
    # Initialize Bedrock embeddings
    embeddings = BedrockEmbeddings(region_name="us-east-1",model_id="amazon.titan-embed-text-v2:0")
    
    # Create vector store
    vector_store = Chroma.from_documents(chunks, embeddings,collection_name="hcls_collection",persist_directory="./chroma_db")
    return vector_store

# Setup QA chain
def setup_qa_chain(vector_store):
    llm = init_bedrock_client()
    retriever = vector_store.as_retriever(search_kwargs={"k": 3})

    prompt_template = ChatPromptTemplate.from_template(
        "Answer the question based only on the following context:\n\n"
        "{context}\n\n"
        "Question: {user_input}"
    )

    output_parser = StrOutputParser()

    qa_chain = (
        {"context": retriever, "user_input": RunnablePassthrough()}
        | prompt_template
        | llm
        | output_parser
    )

    return qa_chain

def main():
    # Path to your PDF file
    pdf_path = args.file
    
    # Process the PDF
    print("Processing PDF...")
    chunks = process_pdf(pdf_path)
    print(f"Created {len(chunks)} chunks")
    
    # Create vector store
    print("Creating vector store...")
    vector_store = create_vector_store(chunks)
    
    # Setup QA chain
    print("Setting up QA chain...")
    qa_chain = setup_qa_chain(vector_store)
    
    # Interactive question answering
    while True:
        question = input("\nEnter your question (or 'quit' to exit): ")
        if question.lower() == 'quit':
            break
            
        try:
            response = qa_chain.invoke(question)
            print("\nAnswer:", {response})
        except Exception as e:
            print(f"Error: {str(e)}")

if __name__ == "__main__":
    main()

You will run the script by passing the pdf file you want to store in Chroma as shown below

python3 python-chroma.py -f your-file-name-here.pdf

The first time you run the script it will create a subdirectory ./chroma-db under which it will store the chroma related files. If you have sqlite3 installed on your machine you can open up the sqlite database (There will be a .sqlite file in the ./chroma-db directory) and check the table names and its contents.