milvus.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from pymilvus import MilvusClient as Client
  2. from pymilvus import FieldSchema, DataType
  3. import json
  4. from typing import Optional
  5. from open_webui.apps.retrieval.vector.main import VectorItem, SearchResult, GetResult
  6. from open_webui.config import (
  7. MILVUS_URI,
  8. )
  9. class MilvusClient:
  10. def __init__(self):
  11. self.collection_prefix = "open_webui"
  12. self.client = Client(uri=MILVUS_URI)
  13. def _result_to_get_result(self, result) -> GetResult:
  14. ids = []
  15. documents = []
  16. metadatas = []
  17. for match in result:
  18. _ids = []
  19. _documents = []
  20. _metadatas = []
  21. for item in match:
  22. _ids.append(item.get("id"))
  23. _documents.append(item.get("data", {}).get("text"))
  24. _metadatas.append(item.get("metadata"))
  25. ids.append(_ids)
  26. documents.append(_documents)
  27. metadatas.append(_metadatas)
  28. return GetResult(
  29. **{
  30. "ids": ids,
  31. "documents": documents,
  32. "metadatas": metadatas,
  33. }
  34. )
  35. def _result_to_search_result(self, result) -> SearchResult:
  36. ids = []
  37. distances = []
  38. documents = []
  39. metadatas = []
  40. for match in result:
  41. _ids = []
  42. _distances = []
  43. _documents = []
  44. _metadatas = []
  45. for item in match:
  46. _ids.append(item.get("id"))
  47. _distances.append(item.get("distance"))
  48. _documents.append(item.get("entity", {}).get("data", {}).get("text"))
  49. _metadatas.append(item.get("entity", {}).get("metadata"))
  50. ids.append(_ids)
  51. distances.append(_distances)
  52. documents.append(_documents)
  53. metadatas.append(_metadatas)
  54. return SearchResult(
  55. **{
  56. "ids": ids,
  57. "distances": distances,
  58. "documents": documents,
  59. "metadatas": metadatas,
  60. }
  61. )
  62. def _create_collection(self, collection_name: str, dimension: int):
  63. schema = self.client.create_schema(
  64. auto_id=False,
  65. enable_dynamic_field=True,
  66. )
  67. schema.add_field(
  68. field_name="id",
  69. datatype=DataType.VARCHAR,
  70. is_primary=True,
  71. max_length=65535,
  72. )
  73. schema.add_field(
  74. field_name="vector",
  75. datatype=DataType.FLOAT_VECTOR,
  76. dim=dimension,
  77. description="vector",
  78. )
  79. schema.add_field(field_name="data", datatype=DataType.JSON, description="data")
  80. schema.add_field(
  81. field_name="metadata", datatype=DataType.JSON, description="metadata"
  82. )
  83. index_params = self.client.prepare_index_params()
  84. index_params.add_index(
  85. field_name="vector",
  86. index_type="HNSW",
  87. metric_type="COSINE",
  88. params={"M": 16, "efConstruction": 100},
  89. )
  90. self.client.create_collection(
  91. collection_name=f"{self.collection_prefix}_{collection_name}",
  92. schema=schema,
  93. index_params=index_params,
  94. )
  95. def has_collection(self, collection_name: str) -> bool:
  96. # Check if the collection exists based on the collection name.
  97. return self.client.has_collection(
  98. collection_name=f"{self.collection_prefix}_{collection_name}"
  99. )
  100. def delete_collection(self, collection_name: str):
  101. # Delete the collection based on the collection name.
  102. return self.client.drop_collection(
  103. collection_name=f"{self.collection_prefix}_{collection_name}"
  104. )
  105. def search(
  106. self, collection_name: str, vectors: list[list[float | int]], limit: int
  107. ) -> Optional[SearchResult]:
  108. # Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
  109. result = self.client.search(
  110. collection_name=f"{self.collection_prefix}_{collection_name}",
  111. data=vectors,
  112. limit=limit,
  113. output_fields=["data", "metadata"],
  114. )
  115. return self._result_to_search_result(result)
  116. def query(self, collection_name: str, filter: dict, limit: Optional[int] = None):
  117. # Construct the filter string for querying
  118. filter_string = " && ".join(
  119. [
  120. f"JSON_CONTAINS(metadata[{key}], '{[value] if isinstance(value, str) else value}')"
  121. for key, value in filter.items()
  122. ]
  123. )
  124. max_limit = 16383 # The maximum number of records per request
  125. all_results = []
  126. if limit is None:
  127. limit = float("inf") # Use infinity as a placeholder for no limit
  128. # Initialize offset and remaining to handle pagination
  129. offset = 0
  130. remaining = limit
  131. # Loop until there are no more items to fetch or the desired limit is reached
  132. while remaining > 0:
  133. current_fetch = min(
  134. max_limit, remaining
  135. ) # Determine how many items to fetch in this iteration
  136. results = self.client.query(
  137. collection_name=f"{self.collection_prefix}_{collection_name}",
  138. filter=filter_string,
  139. output_fields=["*"],
  140. limit=current_fetch,
  141. offset=offset,
  142. )
  143. if not results:
  144. break
  145. all_results.extend(results)
  146. results_count = len(results)
  147. remaining -= (
  148. results_count # Decrease remaining by the number of items fetched
  149. )
  150. offset += results_count
  151. # Break the loop if the results returned are less than the requested fetch count
  152. if results_count < current_fetch:
  153. break
  154. return self._result_to_get_result(all_results)
  155. def get(self, collection_name: str) -> Optional[GetResult]:
  156. # Get all the items in the collection.
  157. result = self.client.query(
  158. collection_name=f"{self.collection_prefix}_{collection_name}",
  159. filter='id != ""',
  160. )
  161. return self._result_to_get_result([result])
  162. def insert(self, collection_name: str, items: list[VectorItem]):
  163. # Insert the items into the collection, if the collection does not exist, it will be created.
  164. if not self.client.has_collection(
  165. collection_name=f"{self.collection_prefix}_{collection_name}"
  166. ):
  167. self._create_collection(
  168. collection_name=collection_name, dimension=len(items[0]["vector"])
  169. )
  170. return self.client.insert(
  171. collection_name=f"{self.collection_prefix}_{collection_name}",
  172. data=[
  173. {
  174. "id": item["id"],
  175. "vector": item["vector"],
  176. "data": {"text": item["text"]},
  177. "metadata": item["metadata"],
  178. }
  179. for item in items
  180. ],
  181. )
  182. def upsert(self, collection_name: str, items: list[VectorItem]):
  183. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  184. if not self.client.has_collection(
  185. collection_name=f"{self.collection_prefix}_{collection_name}"
  186. ):
  187. self._create_collection(
  188. collection_name=collection_name, dimension=len(items[0]["vector"])
  189. )
  190. return self.client.upsert(
  191. collection_name=f"{self.collection_prefix}_{collection_name}",
  192. data=[
  193. {
  194. "id": item["id"],
  195. "vector": item["vector"],
  196. "data": {"text": item["text"]},
  197. "metadata": item["metadata"],
  198. }
  199. for item in items
  200. ],
  201. )
  202. def delete(
  203. self,
  204. collection_name: str,
  205. ids: Optional[list[str]] = None,
  206. filter: Optional[dict] = None,
  207. ):
  208. # Delete the items from the collection based on the ids.
  209. if ids:
  210. return self.client.delete(
  211. collection_name=f"{self.collection_prefix}_{collection_name}",
  212. ids=ids,
  213. )
  214. elif filter:
  215. # Convert the filter dictionary to a string using JSON_CONTAINS.
  216. filter_string = " && ".join(
  217. [
  218. f"JSON_CONTAINS(metadata[{key}], '{[value] if isinstance(value, str) else value}')"
  219. for key, value in filter.items()
  220. ]
  221. )
  222. return self.client.delete(
  223. collection_name=f"{self.collection_prefix}_{collection_name}",
  224. filter=filter_string,
  225. )
  226. def reset(self):
  227. # Resets the database. This will delete all collections and item entries.
  228. collection_names = self.client.list_collections()
  229. for collection_name in collection_names:
  230. if collection_name.startswith(self.collection_prefix):
  231. self.client.drop_collection(collection_name=collection_name)