qdrant.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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(
  55. url=self.QDRANT_URI,
  56. api_key=self.QDRANT_API_KEY,
  57. timeout=QDRANT_TIMEOUT,
  58. )
  59. def _result_to_get_result(self, points) -> GetResult:
  60. ids = []
  61. documents = []
  62. metadatas = []
  63. for point in points:
  64. payload = point.payload
  65. ids.append(point.id)
  66. documents.append(payload["text"])
  67. metadatas.append(payload["metadata"])
  68. return GetResult(
  69. **{
  70. "ids": [ids],
  71. "documents": [documents],
  72. "metadatas": [metadatas],
  73. }
  74. )
  75. def _create_collection(self, collection_name: str, dimension: int):
  76. collection_name_with_prefix = f"{self.collection_prefix}_{collection_name}"
  77. self.client.create_collection(
  78. collection_name=collection_name_with_prefix,
  79. vectors_config=models.VectorParams(
  80. size=dimension,
  81. distance=models.Distance.COSINE,
  82. on_disk=self.QDRANT_ON_DISK,
  83. ),
  84. hnsw_config=models.HnswConfigDiff(
  85. m=self.QDRANT_HNSW_M,
  86. ),
  87. )
  88. # Create payload indexes for efficient filtering
  89. self.client.create_payload_index(
  90. collection_name=collection_name_with_prefix,
  91. field_name="metadata.hash",
  92. field_schema=models.KeywordIndexParams(
  93. type=models.KeywordIndexType.KEYWORD,
  94. is_tenant=False,
  95. on_disk=self.QDRANT_ON_DISK,
  96. ),
  97. )
  98. self.client.create_payload_index(
  99. collection_name=collection_name_with_prefix,
  100. field_name="metadata.file_id",
  101. field_schema=models.KeywordIndexParams(
  102. type=models.KeywordIndexType.KEYWORD,
  103. is_tenant=False,
  104. on_disk=self.QDRANT_ON_DISK,
  105. ),
  106. )
  107. log.info(f"collection {collection_name_with_prefix} successfully created!")
  108. def _create_collection_if_not_exists(self, collection_name, dimension):
  109. if not self.has_collection(collection_name=collection_name):
  110. self._create_collection(
  111. collection_name=collection_name, dimension=dimension
  112. )
  113. def _create_points(self, items: list[VectorItem]):
  114. return [
  115. PointStruct(
  116. id=item["id"],
  117. vector=item["vector"],
  118. payload={"text": item["text"], "metadata": item["metadata"]},
  119. )
  120. for item in items
  121. ]
  122. def has_collection(self, collection_name: str) -> bool:
  123. return self.client.collection_exists(
  124. f"{self.collection_prefix}_{collection_name}"
  125. )
  126. def delete_collection(self, collection_name: str):
  127. return self.client.delete_collection(
  128. collection_name=f"{self.collection_prefix}_{collection_name}"
  129. )
  130. def search(
  131. self, collection_name: str, vectors: list[list[float | int]], limit: int
  132. ) -> Optional[SearchResult]:
  133. # Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
  134. if limit is None:
  135. limit = NO_LIMIT # otherwise qdrant would set limit to 10!
  136. query_response = self.client.query_points(
  137. collection_name=f"{self.collection_prefix}_{collection_name}",
  138. query=vectors[0],
  139. limit=limit,
  140. )
  141. get_result = self._result_to_get_result(query_response.points)
  142. return SearchResult(
  143. ids=get_result.ids,
  144. documents=get_result.documents,
  145. metadatas=get_result.metadatas,
  146. # qdrant distance is [-1, 1], normalize to [0, 1]
  147. distances=[[(point.score + 1.0) / 2.0 for point in query_response.points]],
  148. )
  149. def query(self, collection_name: str, filter: dict, limit: Optional[int] = None):
  150. # Construct the filter string for querying
  151. if not self.has_collection(collection_name):
  152. return None
  153. try:
  154. if limit is None:
  155. limit = NO_LIMIT # otherwise qdrant would set limit to 10!
  156. field_conditions = []
  157. for key, value in filter.items():
  158. field_conditions.append(
  159. models.FieldCondition(
  160. key=f"metadata.{key}", match=models.MatchValue(value=value)
  161. )
  162. )
  163. points = self.client.scroll(
  164. collection_name=f"{self.collection_prefix}_{collection_name}",
  165. scroll_filter=models.Filter(should=field_conditions),
  166. limit=limit,
  167. )
  168. return self._result_to_get_result(points[0])
  169. except Exception as e:
  170. log.exception(f"Error querying a collection '{collection_name}': {e}")
  171. return None
  172. def get(self, collection_name: str) -> Optional[GetResult]:
  173. # Get all the items in the collection.
  174. points = self.client.scroll(
  175. collection_name=f"{self.collection_prefix}_{collection_name}",
  176. limit=NO_LIMIT, # otherwise qdrant would set limit to 10!
  177. )
  178. return self._result_to_get_result(points[0])
  179. def insert(self, collection_name: str, items: list[VectorItem]):
  180. # Insert the items into the collection, if the collection does not exist, it will be created.
  181. self._create_collection_if_not_exists(collection_name, len(items[0]["vector"]))
  182. points = self._create_points(items)
  183. self.client.upload_points(f"{self.collection_prefix}_{collection_name}", points)
  184. def upsert(self, collection_name: str, items: list[VectorItem]):
  185. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  186. self._create_collection_if_not_exists(collection_name, len(items[0]["vector"]))
  187. points = self._create_points(items)
  188. return self.client.upsert(f"{self.collection_prefix}_{collection_name}", points)
  189. def delete(
  190. self,
  191. collection_name: str,
  192. ids: Optional[list[str]] = None,
  193. filter: Optional[dict] = None,
  194. ):
  195. # Delete the items from the collection based on the ids.
  196. field_conditions = []
  197. if ids:
  198. for id_value in ids:
  199. field_conditions.append(
  200. models.FieldCondition(
  201. key="metadata.id",
  202. match=models.MatchValue(value=id_value),
  203. ),
  204. ),
  205. elif filter:
  206. for key, value in filter.items():
  207. field_conditions.append(
  208. models.FieldCondition(
  209. key=f"metadata.{key}",
  210. match=models.MatchValue(value=value),
  211. ),
  212. ),
  213. return self.client.delete(
  214. collection_name=f"{self.collection_prefix}_{collection_name}",
  215. points_selector=models.FilterSelector(
  216. filter=models.Filter(must=field_conditions)
  217. ),
  218. )
  219. def reset(self):
  220. # Resets the database. This will delete all collections and item entries.
  221. collection_names = self.client.get_collections().collections
  222. for collection_name in collection_names:
  223. if collection_name.name.startswith(self.collection_prefix):
  224. self.client.delete_collection(collection_name=collection_name.name)