qdrant.py 9.1 KB

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