chroma.py 8.1 KB

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