milvus.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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(
  117. self, collection_name: str, filter: dict, limit: int = 1
  118. ) -> Optional[SearchResult]:
  119. # Query the items from the collection based on the filter.
  120. filter_string = " && ".join(
  121. [
  122. f"JSON_CONTAINS(metadata[{key}], '{[value] if isinstance(value, str) else value}')"
  123. for key, value in filter.items()
  124. ]
  125. )
  126. result = self.client.query(
  127. collection_name=f"{self.collection_prefix}_{collection_name}",
  128. filter=filter_string,
  129. limit=limit,
  130. )
  131. return self._result_to_search_result([result])
  132. def get(self, collection_name: str) -> Optional[GetResult]:
  133. # Get all the items in the collection.
  134. result = self.client.query(
  135. collection_name=f"{self.collection_prefix}_{collection_name}",
  136. filter='id != ""',
  137. )
  138. return self._result_to_get_result([result])
  139. def insert(self, collection_name: str, items: list[VectorItem]):
  140. # Insert the items into the collection, if the collection does not exist, it will be created.
  141. if not self.client.has_collection(
  142. collection_name=f"{self.collection_prefix}_{collection_name}"
  143. ):
  144. self._create_collection(
  145. collection_name=collection_name, dimension=len(items[0]["vector"])
  146. )
  147. return self.client.insert(
  148. collection_name=f"{self.collection_prefix}_{collection_name}",
  149. data=[
  150. {
  151. "id": item["id"],
  152. "vector": item["vector"],
  153. "data": {"text": item["text"]},
  154. "metadata": item["metadata"],
  155. }
  156. for item in items
  157. ],
  158. )
  159. def upsert(self, collection_name: str, items: list[VectorItem]):
  160. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  161. if not self.client.has_collection(
  162. collection_name=f"{self.collection_prefix}_{collection_name}"
  163. ):
  164. self._create_collection(
  165. collection_name=collection_name, dimension=len(items[0]["vector"])
  166. )
  167. return self.client.upsert(
  168. collection_name=f"{self.collection_prefix}_{collection_name}",
  169. data=[
  170. {
  171. "id": item["id"],
  172. "vector": item["vector"],
  173. "data": {"text": item["text"]},
  174. "metadata": item["metadata"],
  175. }
  176. for item in items
  177. ],
  178. )
  179. def delete(
  180. self,
  181. collection_name: str,
  182. ids: Optional[list[str]] = None,
  183. filter: Optional[dict] = None,
  184. ):
  185. # Delete the items from the collection based on the ids.
  186. if ids:
  187. return self.client.delete(
  188. collection_name=f"{self.collection_prefix}_{collection_name}",
  189. ids=ids,
  190. )
  191. elif filter:
  192. # Convert the filter dictionary to a string using JSON_CONTAINS.
  193. filter_string = " && ".join(
  194. [
  195. f"JSON_CONTAINS(metadata[{key}], '{[value] if isinstance(value, str) else value}')"
  196. for key, value in filter.items()
  197. ]
  198. )
  199. return self.client.delete(
  200. collection_name=f"{self.collection_prefix}_{collection_name}",
  201. filter=filter_string,
  202. )
  203. def reset(self):
  204. # Resets the database. This will delete all collections and item entries.
  205. collection_names = self.client.list_collections()
  206. for collection_name in collection_names:
  207. if collection_name.startswith(self.collection_prefix):
  208. self.client.drop_collection(collection_name=collection_name)