qdrant.py 6.9 KB

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