qdrant.py 8.7 KB

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