qdrant.py 6.7 KB

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