qdrant.py 8.0 KB

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