qdrant.py 7.2 KB

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