chroma.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import logging
  2. from typing import Any, Dict, List, Optional
  3. from chromadb import Collection, QueryResult
  4. from langchain.docstore.document import Document
  5. from embedchain.config import ChromaDbConfig
  6. from embedchain.helper.json_serializable import register_deserializable
  7. from embedchain.vectordb.base import BaseVectorDB
  8. try:
  9. import chromadb
  10. from chromadb.config import Settings
  11. from chromadb.errors import InvalidDimensionException
  12. except RuntimeError:
  13. from embedchain.utils import use_pysqlite3
  14. use_pysqlite3()
  15. import chromadb
  16. from chromadb.config import Settings
  17. from chromadb.errors import InvalidDimensionException
  18. @register_deserializable
  19. class ChromaDB(BaseVectorDB):
  20. """Vector database using ChromaDB."""
  21. def __init__(self, config: Optional[ChromaDbConfig] = None):
  22. """Initialize a new ChromaDB instance
  23. :param config: Configuration options for Chroma, defaults to None
  24. :type config: Optional[ChromaDbConfig], optional
  25. """
  26. if config:
  27. self.config = config
  28. else:
  29. self.config = ChromaDbConfig()
  30. self.settings = Settings()
  31. self.settings.allow_reset = self.config.allow_reset
  32. if self.config.chroma_settings:
  33. for key, value in self.config.chroma_settings.items():
  34. if hasattr(self.settings, key):
  35. setattr(self.settings, key, value)
  36. if self.config.host and self.config.port:
  37. logging.info(f"Connecting to ChromaDB server: {self.config.host}:{self.config.port}")
  38. self.settings.chroma_server_host = self.config.host
  39. self.settings.chroma_server_http_port = self.config.port
  40. self.settings.chroma_api_impl = "chromadb.api.fastapi.FastAPI"
  41. else:
  42. if self.config.dir is None:
  43. self.config.dir = "db"
  44. self.settings.persist_directory = self.config.dir
  45. self.settings.is_persistent = True
  46. self.client = chromadb.Client(self.settings)
  47. super().__init__(config=self.config)
  48. def _initialize(self):
  49. """
  50. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  51. """
  52. if not self.embedder:
  53. raise ValueError(
  54. "Embedder not set. Please set an embedder with `_set_embedder()` function before initialization."
  55. )
  56. self._get_or_create_collection(self.config.collection_name)
  57. def _get_or_create_db(self):
  58. """Called during initialization"""
  59. return self.client
  60. def _get_or_create_collection(self, name: str) -> Collection:
  61. """
  62. Get or create a named collection.
  63. :param name: Name of the collection
  64. :type name: str
  65. :raises ValueError: No embedder configured.
  66. :return: Created collection
  67. :rtype: Collection
  68. """
  69. if not hasattr(self, "embedder") or not self.embedder:
  70. raise ValueError("Cannot create a Chroma database collection without an embedder.")
  71. self.collection = self.client.get_or_create_collection(
  72. name=name,
  73. embedding_function=self.embedder.embedding_fn,
  74. )
  75. return self.collection
  76. def get(self, ids: Optional[List[str]] = None, where: Optional[Dict[str, any]] = None, limit: Optional[int] = None):
  77. """
  78. Get existing doc ids present in vector database
  79. :param ids: list of doc ids to check for existence
  80. :type ids: List[str]
  81. :param where: Optional. to filter data
  82. :type where: Dict[str, Any]
  83. :param limit: Optional. maximum number of documents
  84. :type limit: Optional[int]
  85. :return: Existing documents.
  86. :rtype: List[str]
  87. """
  88. args = {}
  89. if ids:
  90. args["ids"] = ids
  91. if where:
  92. args["where"] = where
  93. if limit:
  94. args["limit"] = limit
  95. return self.collection.get(**args)
  96. def get_advanced(self, where):
  97. return self.collection.get(where=where, limit=1)
  98. def add(
  99. self,
  100. embeddings: List[List[float]],
  101. documents: List[str],
  102. metadatas: List[object],
  103. ids: List[str],
  104. skip_embedding: bool,
  105. ) -> Any:
  106. """
  107. Add vectors to chroma database
  108. :param documents: Documents
  109. :type documents: List[str]
  110. :param metadatas: Metadatas
  111. :type metadatas: List[object]
  112. :param ids: ids
  113. :type ids: List[str]
  114. """
  115. if skip_embedding:
  116. self.collection.add(embeddings=embeddings, documents=documents, metadatas=metadatas, ids=ids)
  117. else:
  118. self.collection.add(documents=documents, metadatas=metadatas, ids=ids)
  119. def _format_result(self, results: QueryResult) -> list[tuple[Document, float]]:
  120. """
  121. Format Chroma results
  122. :param results: ChromaDB query results to format.
  123. :type results: QueryResult
  124. :return: Formatted results
  125. :rtype: list[tuple[Document, float]]
  126. """
  127. return [
  128. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  129. for result in zip(
  130. results["documents"][0],
  131. results["metadatas"][0],
  132. results["distances"][0],
  133. )
  134. ]
  135. def query(self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool) -> List[str]:
  136. """
  137. Query contents from vector data base based on vector similarity
  138. :param input_query: list of query string
  139. :type input_query: List[str]
  140. :param n_results: no of similar documents to fetch from database
  141. :type n_results: int
  142. :param where: to filter data
  143. :type where: Dict[str, Any]
  144. :raises InvalidDimensionException: Dimensions do not match.
  145. :return: The content of the document that matched your query.
  146. :rtype: List[str]
  147. """
  148. try:
  149. if skip_embedding:
  150. result = self.collection.query(
  151. query_embeddings=[
  152. input_query,
  153. ],
  154. n_results=n_results,
  155. where=where,
  156. )
  157. else:
  158. result = self.collection.query(
  159. query_texts=[
  160. input_query,
  161. ],
  162. n_results=n_results,
  163. where=where,
  164. )
  165. except InvalidDimensionException as e:
  166. raise InvalidDimensionException(
  167. e.message()
  168. + ". 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
  169. ) from None
  170. results_formatted = self._format_result(result)
  171. contents = [result[0].page_content for result in results_formatted]
  172. return contents
  173. def set_collection_name(self, name: str):
  174. """
  175. Set the name of the collection. A collection is an isolated space for vectors.
  176. :param name: Name of the collection.
  177. :type name: str
  178. """
  179. if not isinstance(name, str):
  180. raise TypeError("Collection name must be a string")
  181. self.config.collection_name = name
  182. self._get_or_create_collection(self.config.collection_name)
  183. def count(self) -> int:
  184. """
  185. Count number of documents/chunks embedded in the database.
  186. :return: number of documents
  187. :rtype: int
  188. """
  189. return self.collection.count()
  190. def delete(self, where):
  191. return self.collection.delete(where=where)
  192. def reset(self):
  193. """
  194. Resets the database. Deletes all embeddings irreversibly.
  195. """
  196. # Delete all data from the database
  197. try:
  198. self.client.reset()
  199. except ValueError:
  200. raise ValueError(
  201. "For safety reasons, resetting is disabled. "
  202. "Please enable it by setting `allow_reset=True` in your ChromaDbConfig"
  203. ) from None
  204. # Recreate
  205. self._get_or_create_collection(self.config.collection_name)
  206. # Todo: Automatically recreating a collection with the same name cannot be the best way to handle a reset.
  207. # A downside of this implementation is, if you have two instances,
  208. # the other instance will not get the updated `self.collection` attribute.
  209. # A better way would be to create the collection if it is called again after being reset.
  210. # That means, checking if collection exists in the db-consuming methods, and creating it if it doesn't.
  211. # That's an extra steps for all uses, just to satisfy a niche use case in a niche method. For now, this will do.