qdrant.py 7.9 KB

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