qdrant.py 8.0 KB

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