milvus.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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", index_type="HNSW", metric_type="COSINE", params={}
  86. )
  87. self.client.create_collection(
  88. collection_name=f"{self.collection_prefix}_{collection_name}",
  89. schema=schema,
  90. index_params=index_params,
  91. )
  92. def has_collection(self, collection_name: str) -> bool:
  93. # Check if the collection exists based on the collection name.
  94. return self.client.has_collection(
  95. collection_name=f"{self.collection_prefix}_{collection_name}"
  96. )
  97. def delete_collection(self, collection_name: str):
  98. # Delete the collection based on the collection name.
  99. return self.client.drop_collection(
  100. collection_name=f"{self.collection_prefix}_{collection_name}"
  101. )
  102. def search(
  103. self, collection_name: str, vectors: list[list[float | int]], limit: int
  104. ) -> Optional[SearchResult]:
  105. # Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
  106. result = self.client.search(
  107. collection_name=f"{self.collection_prefix}_{collection_name}",
  108. data=vectors,
  109. limit=limit,
  110. output_fields=["data", "metadata"],
  111. )
  112. return self._result_to_search_result(result)
  113. def get(self, collection_name: str) -> Optional[GetResult]:
  114. # Get all the items in the collection.
  115. result = self.client.query(
  116. collection_name=f"{self.collection_prefix}_{collection_name}",
  117. filter='id != ""',
  118. )
  119. return self._result_to_get_result([result])
  120. def insert(self, collection_name: str, items: list[VectorItem]):
  121. # Insert the items into the collection, if the collection does not exist, it will be created.
  122. if not self.client.has_collection(
  123. collection_name=f"{self.collection_prefix}_{collection_name}"
  124. ):
  125. self._create_collection(
  126. collection_name=collection_name, dimension=len(items[0]["vector"])
  127. )
  128. return self.client.insert(
  129. collection_name=f"{self.collection_prefix}_{collection_name}",
  130. data=[
  131. {
  132. "id": item["id"],
  133. "vector": item["vector"],
  134. "data": {"text": item["text"]},
  135. "metadata": item["metadata"],
  136. }
  137. for item in items
  138. ],
  139. )
  140. def upsert(self, collection_name: str, items: list[VectorItem]):
  141. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  142. if not self.client.has_collection(
  143. collection_name=f"{self.collection_prefix}_{collection_name}"
  144. ):
  145. self._create_collection(
  146. collection_name=collection_name, dimension=len(items[0]["vector"])
  147. )
  148. return self.client.upsert(
  149. collection_name=f"{self.collection_prefix}_{collection_name}",
  150. data=[
  151. {
  152. "id": item["id"],
  153. "vector": item["vector"],
  154. "data": {"text": item["text"]},
  155. "metadata": item["metadata"],
  156. }
  157. for item in items
  158. ],
  159. )
  160. def delete(self, collection_name: str, ids: list[str]):
  161. # Delete the items from the collection based on the ids.
  162. return self.client.delete(
  163. collection_name=f"{self.collection_prefix}_{collection_name}",
  164. ids=ids,
  165. )
  166. def reset(self):
  167. # Resets the database. This will delete all collections and item entries.
  168. collection_names = self.client.list_collections()
  169. for collection_name in collection_names:
  170. if collection_name.startswith(self.collection_prefix):
  171. self.client.drop_collection(collection_name=collection_name)