chroma_db.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import logging
  2. import chromadb
  3. from chromadb.config import Settings
  4. from embedchain.vectordb.base_vector_db import BaseVectorDB
  5. class ChromaDB(BaseVectorDB):
  6. """Vector database using ChromaDB."""
  7. def __init__(self, db_dir=None, embedding_fn=None, host=None, port=None):
  8. self.embedding_fn = embedding_fn
  9. if not hasattr(embedding_fn, "__call__"):
  10. raise ValueError("Embedding function is not a function")
  11. if host and port:
  12. logging.info(f"Connecting to ChromaDB server: {host}:{port}")
  13. self.settings = Settings(chroma_server_host=host, chroma_server_http_port=port)
  14. self.client = chromadb.HttpClient(self.settings)
  15. else:
  16. if db_dir is None:
  17. db_dir = "db"
  18. self.settings = Settings(anonymized_telemetry=False, allow_reset=True)
  19. self.client = chromadb.PersistentClient(
  20. path=db_dir,
  21. settings=self.settings,
  22. )
  23. super().__init__()
  24. def _get_or_create_db(self):
  25. """Get or create the database."""
  26. return self.client
  27. def _get_or_create_collection(self):
  28. """Get or create the collection."""
  29. return self.client.get_or_create_collection(
  30. "embedchain_store",
  31. embedding_function=self.embedding_fn,
  32. )