milvus.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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.rag.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 get(self, collection_name: str) -> Optional[GetResult]:
  117. # Get all the items in the collection.
  118. result = self.client.query(
  119. collection_name=f"{self.collection_prefix}_{collection_name}",
  120. filter='id != ""',
  121. )
  122. return self._result_to_get_result([result])
  123. def insert(self, collection_name: str, items: list[VectorItem]):
  124. # Insert the items into the collection, if the collection does not exist, it will be created.
  125. if not self.client.has_collection(
  126. collection_name=f"{self.collection_prefix}_{collection_name}"
  127. ):
  128. self._create_collection(
  129. collection_name=collection_name, dimension=len(items[0]["vector"])
  130. )
  131. return self.client.insert(
  132. collection_name=f"{self.collection_prefix}_{collection_name}",
  133. data=[
  134. {
  135. "id": item["id"],
  136. "vector": item["vector"],
  137. "data": {"text": item["text"]},
  138. "metadata": item["metadata"],
  139. }
  140. for item in items
  141. ],
  142. )
  143. def upsert(self, collection_name: str, items: list[VectorItem]):
  144. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  145. if not self.client.has_collection(
  146. collection_name=f"{self.collection_prefix}_{collection_name}"
  147. ):
  148. self._create_collection(
  149. collection_name=collection_name, dimension=len(items[0]["vector"])
  150. )
  151. return self.client.upsert(
  152. collection_name=f"{self.collection_prefix}_{collection_name}",
  153. data=[
  154. {
  155. "id": item["id"],
  156. "vector": item["vector"],
  157. "data": {"text": item["text"]},
  158. "metadata": item["metadata"],
  159. }
  160. for item in items
  161. ],
  162. )
  163. def delete(self, collection_name: str, ids: list[str]):
  164. # Delete the items from the collection based on the ids.
  165. return self.client.delete(
  166. collection_name=f"{self.collection_prefix}_{collection_name}",
  167. ids=ids,
  168. )
  169. def reset(self):
  170. # Resets the database. This will delete all collections and item entries.
  171. collection_names = self.client.list_collections()
  172. for collection_name in collection_names:
  173. if collection_name.startswith(self.collection_prefix):
  174. self.client.drop_collection(collection_name=collection_name)