chroma_db.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import logging
  2. from typing import Any, Dict, List, Optional
  3. from langchain.docstore.document import Document
  4. from embedchain.config import ChromaDbConfig
  5. from embedchain.helper_classes.json_serializable import register_deserializable
  6. from embedchain.vectordb.base_vector_db import BaseVectorDB
  7. try:
  8. import chromadb
  9. from chromadb.config import Settings
  10. from chromadb.errors import InvalidDimensionException
  11. except RuntimeError:
  12. from embedchain.utils import use_pysqlite3
  13. use_pysqlite3()
  14. import chromadb
  15. from chromadb.config import Settings
  16. from chromadb.errors import InvalidDimensionException
  17. @register_deserializable
  18. class ChromaDB(BaseVectorDB):
  19. """Vector database using ChromaDB."""
  20. def __init__(self, config: Optional[ChromaDbConfig] = None):
  21. if config:
  22. self.config = config
  23. else:
  24. self.config = ChromaDbConfig()
  25. self.settings = Settings()
  26. if self.config.chroma_settings:
  27. for key, value in self.config.chroma_settings.items():
  28. if hasattr(self.settings, key):
  29. setattr(self.settings, key, value)
  30. if self.config.host and self.config.port:
  31. logging.info(f"Connecting to ChromaDB server: {self.config.host}:{self.config.port}")
  32. self.settings.chroma_server_host = self.config.host
  33. self.settings.chroma_server_http_port = self.config.port
  34. self.settings.chroma_api_impl = "chromadb.api.fastapi.FastAPI"
  35. else:
  36. if self.config.dir is None:
  37. self.config.dir = "db"
  38. self.settings.persist_directory = self.config.dir
  39. self.settings.is_persistent = True
  40. self.client = chromadb.Client(self.settings)
  41. super().__init__(config=self.config)
  42. def _initialize(self):
  43. """
  44. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  45. """
  46. if not self.embedder:
  47. raise ValueError("Embedder not set. Please set an embedder with `set_embedder` before initialization.")
  48. self._get_or_create_collection(self.config.collection_name)
  49. def _get_or_create_db(self):
  50. """Get or create the database."""
  51. return self.client
  52. def _get_or_create_collection(self, name):
  53. """Get or create the collection."""
  54. if not hasattr(self, "embedder") or not self.embedder:
  55. raise ValueError("Cannot create a Chroma database collection without an embedder.")
  56. self.collection = self.client.get_or_create_collection(
  57. name=name,
  58. embedding_function=self.embedder.embedding_fn,
  59. )
  60. return self.collection
  61. def get(self, ids: List[str], where: Dict[str, any]) -> List[str]:
  62. """
  63. Get existing doc ids present in vector database
  64. :param ids: list of doc ids to check for existance
  65. :param where: Optional. to filter data
  66. """
  67. existing_docs = self.collection.get(
  68. ids=ids,
  69. where=where, # optional filter
  70. )
  71. return set(existing_docs["ids"])
  72. def add(self, documents: List[str], metadatas: List[object], ids: List[str]) -> Any:
  73. """
  74. add data in vector database
  75. :param documents: list of texts to add
  76. :param metadatas: list of metadata associated with docs
  77. :param ids: ids of docs
  78. """
  79. self.collection.add(documents=documents, metadatas=metadatas, ids=ids)
  80. def _format_result(self, results):
  81. return [
  82. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  83. for result in zip(
  84. results["documents"][0],
  85. results["metadatas"][0],
  86. results["distances"][0],
  87. )
  88. ]
  89. def query(self, input_query: List[str], n_results: int, where: Dict[str, any]) -> List[str]:
  90. """
  91. query contents from vector data base based on vector similarity
  92. :param input_query: list of query string
  93. :param n_results: no of similar documents to fetch from database
  94. :param where: Optional. to filter data
  95. :return: The content of the document that matched your query.
  96. """
  97. try:
  98. result = self.collection.query(
  99. query_texts=[
  100. input_query,
  101. ],
  102. n_results=n_results,
  103. where=where,
  104. )
  105. except InvalidDimensionException as e:
  106. raise InvalidDimensionException(
  107. e.message()
  108. + ". This is commonly a side-effect when an embedding function, different from the one used to add the embeddings, is used to retrieve an embedding from the database." # noqa E501
  109. ) from None
  110. results_formatted = self._format_result(result)
  111. contents = [result[0].page_content for result in results_formatted]
  112. return contents
  113. def set_collection_name(self, name: str):
  114. self.config.collection_name = name
  115. self._get_or_create_collection(self.config.collection_name)
  116. def count(self) -> int:
  117. """
  118. Count the number of embeddings.
  119. :return: The number of embeddings.
  120. """
  121. return self.collection.count()
  122. def reset(self):
  123. """
  124. Resets the database. Deletes all embeddings irreversibly.
  125. `App` does not have to be reinitialized after using this method.
  126. """
  127. # Delete all data from the database
  128. try:
  129. self.client.reset()
  130. except ValueError:
  131. raise ValueError(
  132. "For safety reasons, resetting is disabled."
  133. 'Please enable it by including `chromadb_settings={"allow_reset": True}` in your ChromaDbConfig'
  134. ) from None
  135. # Recreate
  136. self._get_or_create_collection(self.config.collection_name)
  137. # Todo: Automatically recreating a collection with the same name cannot be the best way to handle a reset.
  138. # A downside of this implementation is, if you have two instances,
  139. # the other instance will not get the updated `self.collection` attribute.
  140. # A better way would be to create the collection if it is called again after being reset.
  141. # That means, checking if collection exists in the db-consuming methods, and creating it if it doesn't.
  142. # That's an extra steps for all uses, just to satisfy a niche use case in a niche method. For now, this will do.