qdrant.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. from typing import Optional
  2. import logging
  3. from urllib.parse import urlparse
  4. from qdrant_client import QdrantClient as Qclient
  5. from qdrant_client.http.models import PointStruct
  6. from qdrant_client.models import models
  7. from open_webui.retrieval.vector.main import (
  8. VectorDBBase,
  9. VectorItem,
  10. SearchResult,
  11. GetResult,
  12. )
  13. from open_webui.config import (
  14. QDRANT_URI,
  15. QDRANT_API_KEY,
  16. QDRANT_ON_DISK,
  17. QDRANT_GRPC_PORT,
  18. QDRANT_PREFER_GRPC,
  19. QDRANT_COLLECTION_PREFIX,
  20. QDRANT_TIMEOUT,
  21. QDRANT_HNSW_M,
  22. )
  23. from open_webui.env import SRC_LOG_LEVELS
  24. NO_LIMIT = 999999999
  25. log = logging.getLogger(__name__)
  26. log.setLevel(SRC_LOG_LEVELS["RAG"])
  27. class QdrantClient(VectorDBBase):
  28. def __init__(self):
  29. self.collection_prefix = QDRANT_COLLECTION_PREFIX
  30. self.QDRANT_URI = QDRANT_URI
  31. self.QDRANT_API_KEY = QDRANT_API_KEY
  32. self.QDRANT_ON_DISK = QDRANT_ON_DISK
  33. self.PREFER_GRPC = QDRANT_PREFER_GRPC
  34. self.GRPC_PORT = QDRANT_GRPC_PORT
  35. self.QDRANT_TIMEOUT = QDRANT_TIMEOUT
  36. self.QDRANT_HNSW_M = QDRANT_HNSW_M
  37. if not self.QDRANT_URI:
  38. self.client = None
  39. return
  40. # Unified handling for either scheme
  41. parsed = urlparse(self.QDRANT_URI)
  42. host = parsed.hostname or self.QDRANT_URI
  43. http_port = parsed.port or 6333 # default REST port
  44. if self.PREFER_GRPC:
  45. self.client = Qclient(
  46. host=host,
  47. port=http_port,
  48. grpc_port=self.GRPC_PORT,
  49. prefer_grpc=self.PREFER_GRPC,
  50. api_key=self.QDRANT_API_KEY,
  51. timeout=self.QDRANT_TIMEOUT,
  52. )
  53. else:
  54. self.client = Qclient(url=self.QDRANT_URI, api_key=self.QDRANT_API_KEY, timeout=QDRANT_TIMEOUT,)
  55. def _result_to_get_result(self, points) -> GetResult:
  56. ids = []
  57. documents = []
  58. metadatas = []
  59. for point in points:
  60. payload = point.payload
  61. ids.append(point.id)
  62. documents.append(payload["text"])
  63. metadatas.append(payload["metadata"])
  64. return GetResult(
  65. **{
  66. "ids": [ids],
  67. "documents": [documents],
  68. "metadatas": [metadatas],
  69. }
  70. )
  71. def _create_collection(self, collection_name: str, dimension: int):
  72. collection_name_with_prefix = f"{self.collection_prefix}_{collection_name}"
  73. self.client.create_collection(
  74. collection_name=collection_name_with_prefix,
  75. vectors_config=models.VectorParams(
  76. size=dimension,
  77. distance=models.Distance.COSINE,
  78. on_disk=self.QDRANT_ON_DISK,
  79. ),
  80. hnsw_config=models.HnswConfigDiff(
  81. m=self.QDRANT_HNSW_M,
  82. ),
  83. )
  84. # Create payload indexes for efficient filtering
  85. self.client.create_payload_index(
  86. collection_name=collection_name_with_prefix,
  87. field_name="metadata.hash",
  88. field_schema=models.KeywordIndexParams(
  89. type=models.KeywordIndexType.KEYWORD,
  90. is_tenant=False,
  91. on_disk=self.QDRANT_ON_DISK,
  92. ),
  93. )
  94. self.client.create_payload_index(
  95. collection_name=collection_name_with_prefix,
  96. field_name="metadata.file_id",
  97. field_schema=models.KeywordIndexParams(
  98. type=models.KeywordIndexType.KEYWORD,
  99. is_tenant=False,
  100. on_disk=self.QDRANT_ON_DISK,
  101. ),
  102. )
  103. log.info(f"collection {collection_name_with_prefix} successfully created!")
  104. def _create_collection_if_not_exists(self, collection_name, dimension):
  105. if not self.has_collection(collection_name=collection_name):
  106. self._create_collection(
  107. collection_name=collection_name, dimension=dimension
  108. )
  109. def _create_points(self, items: list[VectorItem]):
  110. return [
  111. PointStruct(
  112. id=item["id"],
  113. vector=item["vector"],
  114. payload={"text": item["text"], "metadata": item["metadata"]},
  115. )
  116. for item in items
  117. ]
  118. def has_collection(self, collection_name: str) -> bool:
  119. return self.client.collection_exists(
  120. f"{self.collection_prefix}_{collection_name}"
  121. )
  122. def delete_collection(self, collection_name: str):
  123. return self.client.delete_collection(
  124. collection_name=f"{self.collection_prefix}_{collection_name}"
  125. )
  126. def search(
  127. self, collection_name: str, vectors: list[list[float | int]], limit: int
  128. ) -> Optional[SearchResult]:
  129. # Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
  130. if limit is None:
  131. limit = NO_LIMIT # otherwise qdrant would set limit to 10!
  132. query_response = self.client.query_points(
  133. collection_name=f"{self.collection_prefix}_{collection_name}",
  134. query=vectors[0],
  135. limit=limit,
  136. )
  137. get_result = self._result_to_get_result(query_response.points)
  138. return SearchResult(
  139. ids=get_result.ids,
  140. documents=get_result.documents,
  141. metadatas=get_result.metadatas,
  142. # qdrant distance is [-1, 1], normalize to [0, 1]
  143. distances=[[(point.score + 1.0) / 2.0 for point in query_response.points]],
  144. )
  145. def query(self, collection_name: str, filter: dict, limit: Optional[int] = None):
  146. # Construct the filter string for querying
  147. if not self.has_collection(collection_name):
  148. return None
  149. try:
  150. if limit is None:
  151. limit = NO_LIMIT # otherwise qdrant would set limit to 10!
  152. field_conditions = []
  153. for key, value in filter.items():
  154. field_conditions.append(
  155. models.FieldCondition(
  156. key=f"metadata.{key}", match=models.MatchValue(value=value)
  157. )
  158. )
  159. points = self.client.scroll(
  160. collection_name=f"{self.collection_prefix}_{collection_name}",
  161. scroll_filter=models.Filter(should=field_conditions),
  162. limit=limit,
  163. )
  164. return self._result_to_get_result(points[0])
  165. except Exception as e:
  166. log.exception(f"Error querying a collection '{collection_name}': {e}")
  167. return None
  168. def get(self, collection_name: str) -> Optional[GetResult]:
  169. # Get all the items in the collection.
  170. points = self.client.scroll(
  171. collection_name=f"{self.collection_prefix}_{collection_name}",
  172. limit=NO_LIMIT, # otherwise qdrant would set limit to 10!
  173. )
  174. return self._result_to_get_result(points[0])
  175. def insert(self, collection_name: str, items: list[VectorItem]):
  176. # Insert the items into the collection, if the collection does not exist, it will be created.
  177. self._create_collection_if_not_exists(collection_name, len(items[0]["vector"]))
  178. points = self._create_points(items)
  179. self.client.upload_points(f"{self.collection_prefix}_{collection_name}", points)
  180. def upsert(self, collection_name: str, items: list[VectorItem]):
  181. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  182. self._create_collection_if_not_exists(collection_name, len(items[0]["vector"]))
  183. points = self._create_points(items)
  184. return self.client.upsert(f"{self.collection_prefix}_{collection_name}", points)
  185. def delete(
  186. self,
  187. collection_name: str,
  188. ids: Optional[list[str]] = None,
  189. filter: Optional[dict] = None,
  190. ):
  191. # Delete the items from the collection based on the ids.
  192. field_conditions = []
  193. if ids:
  194. for id_value in ids:
  195. field_conditions.append(
  196. models.FieldCondition(
  197. key="metadata.id",
  198. match=models.MatchValue(value=id_value),
  199. ),
  200. ),
  201. elif filter:
  202. for key, value in filter.items():
  203. field_conditions.append(
  204. models.FieldCondition(
  205. key=f"metadata.{key}",
  206. match=models.MatchValue(value=value),
  207. ),
  208. ),
  209. return self.client.delete(
  210. collection_name=f"{self.collection_prefix}_{collection_name}",
  211. points_selector=models.FilterSelector(
  212. filter=models.Filter(must=field_conditions)
  213. ),
  214. )
  215. def reset(self):
  216. # Resets the database. This will delete all collections and item entries.
  217. collection_names = self.client.get_collections().collections
  218. for collection_name in collection_names:
  219. if collection_name.name.startswith(self.collection_prefix):
  220. self.client.delete_collection(collection_name=collection_name.name)