qdrant.py 7.1 KB

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