qdrant.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import copy
  2. import os
  3. from typing import Any, Optional, Union
  4. try:
  5. from qdrant_client import QdrantClient
  6. from qdrant_client.http import models
  7. from qdrant_client.http.models import Batch
  8. from qdrant_client.models import Distance, VectorParams
  9. except ImportError:
  10. raise ImportError("Qdrant requires extra dependencies. Install with `pip install embedchain[qdrant]`") from None
  11. from tqdm import tqdm
  12. from embedchain.config.vectordb.qdrant import QdrantDBConfig
  13. from embedchain.vectordb.base import BaseVectorDB
  14. class QdrantDB(BaseVectorDB):
  15. """
  16. Qdrant as vector database
  17. """
  18. BATCH_SIZE = 10
  19. def __init__(self, config: QdrantDBConfig = None):
  20. """
  21. Qdrant as vector database
  22. :param config. Qdrant database config to be used for connection
  23. """
  24. if config is None:
  25. config = QdrantDBConfig()
  26. else:
  27. if not isinstance(config, QdrantDBConfig):
  28. raise TypeError(
  29. "config is not a `QdrantDBConfig` instance. "
  30. "Please make sure the type is right and that you are passing an instance."
  31. )
  32. self.config = config
  33. self.client = QdrantClient(url=os.getenv("QDRANT_URL"), api_key=os.getenv("QDRANT_API_KEY"))
  34. # Call parent init here because embedder is needed
  35. super().__init__(config=self.config)
  36. def _initialize(self):
  37. """
  38. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  39. """
  40. if not self.embedder:
  41. raise ValueError("Embedder not set. Please set an embedder with `set_embedder` before initialization.")
  42. self.collection_name = self._get_or_create_collection()
  43. all_collections = self.client.get_collections()
  44. collection_names = [collection.name for collection in all_collections.collections]
  45. if self.collection_name not in collection_names:
  46. self.client.recreate_collection(
  47. collection_name=self.collection_name,
  48. vectors_config=VectorParams(
  49. size=self.embedder.vector_dimension,
  50. distance=Distance.COSINE,
  51. hnsw_config=self.config.hnsw_config,
  52. quantization_config=self.config.quantization_config,
  53. on_disk=self.config.on_disk,
  54. ),
  55. )
  56. def _get_or_create_db(self):
  57. return self.client
  58. def _get_or_create_collection(self):
  59. return f"{self.config.collection_name}-{self.embedder.vector_dimension}".lower().replace("_", "-")
  60. def get(self, ids: Optional[list[str]] = None, where: Optional[dict[str, any]] = None, limit: Optional[int] = None):
  61. """
  62. Get existing doc ids present in vector database
  63. :param ids: _list of doc ids to check for existence
  64. :type ids: list[str]
  65. :param where: to filter data
  66. :type where: dict[str, any]
  67. :param limit: The number of entries to be fetched
  68. :type limit: Optional int, defaults to None
  69. :return: All the existing IDs
  70. :rtype: Set[str]
  71. """
  72. keys = set(where.keys() if where is not None else set())
  73. qdrant_must_filters = []
  74. if ids:
  75. qdrant_must_filters.append(
  76. models.FieldCondition(
  77. key="identifier",
  78. match=models.MatchAny(
  79. any=ids,
  80. ),
  81. )
  82. )
  83. if len(keys) > 0:
  84. for key in keys:
  85. qdrant_must_filters.append(
  86. models.FieldCondition(
  87. key="metadata.{}".format(key),
  88. match=models.MatchValue(
  89. value=where.get(key),
  90. ),
  91. )
  92. )
  93. offset = 0
  94. existing_ids = []
  95. metadatas = []
  96. while offset is not None:
  97. response = self.client.scroll(
  98. collection_name=self.collection_name,
  99. scroll_filter=models.Filter(must=qdrant_must_filters),
  100. offset=offset,
  101. limit=self.BATCH_SIZE,
  102. )
  103. offset = response[1]
  104. for doc in response[0]:
  105. existing_ids.append(doc.payload["identifier"])
  106. metadatas.append(doc.payload["metadata"])
  107. return {"ids": existing_ids, "metadatas": metadatas}
  108. def add(
  109. self,
  110. documents: list[str],
  111. metadatas: list[object],
  112. ids: list[str],
  113. **kwargs: Optional[dict[str, any]],
  114. ):
  115. """add data in vector database
  116. :param documents: list of texts to add
  117. :type documents: list[str]
  118. :param metadatas: list of metadata associated with docs
  119. :type metadatas: list[object]
  120. :param ids: ids of docs
  121. :type ids: list[str]
  122. """
  123. embeddings = self.embedder.embedding_fn(documents)
  124. payloads = []
  125. qdrant_ids = []
  126. for id, document, metadata in zip(ids, documents, metadatas):
  127. metadata["text"] = document
  128. qdrant_ids.append(id)
  129. payloads.append({"identifier": id, "text": document, "metadata": copy.deepcopy(metadata)})
  130. for i in tqdm(range(0, len(qdrant_ids), self.BATCH_SIZE), desc="Adding data in batches"):
  131. self.client.upsert(
  132. collection_name=self.collection_name,
  133. points=Batch(
  134. ids=qdrant_ids[i : i + self.BATCH_SIZE],
  135. payloads=payloads[i : i + self.BATCH_SIZE],
  136. vectors=embeddings[i : i + self.BATCH_SIZE],
  137. ),
  138. **kwargs,
  139. )
  140. def query(
  141. self,
  142. input_query: str,
  143. n_results: int,
  144. where: dict[str, any],
  145. citations: bool = False,
  146. **kwargs: Optional[dict[str, Any]],
  147. ) -> Union[list[tuple[str, dict]], list[str]]:
  148. """
  149. query contents from vector database based on vector similarity
  150. :param input_query: query string
  151. :type input_query: str
  152. :param n_results: no of similar documents to fetch from database
  153. :type n_results: int
  154. :param where: Optional. to filter data
  155. :type where: dict[str, any]
  156. :param citations: we use citations boolean param to return context along with the answer.
  157. :type citations: bool, default is False.
  158. :return: The content of the document that matched your query,
  159. along with url of the source and doc_id (if citations flag is true)
  160. :rtype: list[str], if citations=False, otherwise list[tuple[str, str, str]]
  161. """
  162. query_vector = self.embedder.embedding_fn([input_query])[0]
  163. keys = set(where.keys() if where is not None else set())
  164. qdrant_must_filters = []
  165. if len(keys) > 0:
  166. for key in keys:
  167. qdrant_must_filters.append(
  168. models.FieldCondition(
  169. key="metadata.{}".format(key),
  170. match=models.MatchValue(
  171. value=where.get(key),
  172. ),
  173. )
  174. )
  175. results = self.client.search(
  176. collection_name=self.collection_name,
  177. query_filter=models.Filter(must=qdrant_must_filters),
  178. query_vector=query_vector,
  179. limit=n_results,
  180. **kwargs,
  181. )
  182. contexts = []
  183. for result in results:
  184. context = result.payload["text"]
  185. if citations:
  186. metadata = result.payload["metadata"]
  187. metadata["score"] = result.score
  188. contexts.append(tuple((context, metadata)))
  189. else:
  190. contexts.append(context)
  191. return contexts
  192. def count(self) -> int:
  193. response = self.client.get_collection(collection_name=self.collection_name)
  194. return response.points_count
  195. def reset(self):
  196. self.client.delete_collection(collection_name=self.collection_name)
  197. self._initialize()
  198. def set_collection_name(self, name: str):
  199. """
  200. Set the name of the collection. A collection is an isolated space for vectors.
  201. :param name: Name of the collection.
  202. :type name: str
  203. """
  204. if not isinstance(name, str):
  205. raise TypeError("Collection name must be a string")
  206. self.config.collection_name = name
  207. self.collection_name = self._get_or_create_collection()
  208. @staticmethod
  209. def _generate_query(where: dict):
  210. must_fields = []
  211. for key, value in where.items():
  212. must_fields.append(
  213. models.FieldCondition(
  214. key=f"metadata.{key}",
  215. match=models.MatchValue(
  216. value=value,
  217. ),
  218. )
  219. )
  220. return models.Filter(must=must_fields)
  221. def delete(self, where: dict):
  222. db_filter = self._generate_query(where)
  223. self.client.delete(collection_name=self.collection_name, points_selector=db_filter)