qdrant_multitenancy.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import logging
  2. from typing import Optional, Tuple, List, Dict, Any
  3. from urllib.parse import urlparse
  4. import grpc
  5. from open_webui.config import (
  6. QDRANT_API_KEY,
  7. QDRANT_GRPC_PORT,
  8. QDRANT_ON_DISK,
  9. QDRANT_PREFER_GRPC,
  10. QDRANT_URI,
  11. QDRANT_COLLECTION_PREFIX,
  12. QDRANT_TIMEOUT,
  13. QDRANT_HNSW_M,
  14. )
  15. from open_webui.env import SRC_LOG_LEVELS
  16. from open_webui.retrieval.vector.main import (
  17. GetResult,
  18. SearchResult,
  19. VectorDBBase,
  20. VectorItem,
  21. )
  22. from qdrant_client import QdrantClient as Qclient
  23. from qdrant_client.http.exceptions import UnexpectedResponse
  24. from qdrant_client.http.models import PointStruct
  25. from qdrant_client.models import models
  26. NO_LIMIT = 999999999
  27. TENANT_ID_FIELD = "tenant_id"
  28. DEFAULT_DIMENSION = 384
  29. log = logging.getLogger(__name__)
  30. log.setLevel(SRC_LOG_LEVELS["RAG"])
  31. def _tenant_filter(tenant_id: str) -> models.FieldCondition:
  32. return models.FieldCondition(
  33. key=TENANT_ID_FIELD, match=models.MatchValue(value=tenant_id)
  34. )
  35. def _metadata_filter(key: str, value: Any) -> models.FieldCondition:
  36. return models.FieldCondition(
  37. key=f"metadata.{key}", match=models.MatchValue(value=value)
  38. )
  39. class QdrantClient(VectorDBBase):
  40. def __init__(self):
  41. self.collection_prefix = QDRANT_COLLECTION_PREFIX
  42. self.QDRANT_URI = QDRANT_URI
  43. self.QDRANT_API_KEY = QDRANT_API_KEY
  44. self.QDRANT_ON_DISK = QDRANT_ON_DISK
  45. self.PREFER_GRPC = QDRANT_PREFER_GRPC
  46. self.GRPC_PORT = QDRANT_GRPC_PORT
  47. self.QDRANT_TIMEOUT = QDRANT_TIMEOUT
  48. self.QDRANT_HNSW_M = QDRANT_HNSW_M
  49. if not self.QDRANT_URI:
  50. raise ValueError(
  51. "QDRANT_URI is not set. Please configure it in the environment variables."
  52. )
  53. # Unified handling for either scheme
  54. parsed = urlparse(self.QDRANT_URI)
  55. host = parsed.hostname or self.QDRANT_URI
  56. http_port = parsed.port or 6333 # default REST port
  57. self.client = (
  58. Qclient(
  59. host=host,
  60. port=http_port,
  61. grpc_port=self.GRPC_PORT,
  62. prefer_grpc=self.PREFER_GRPC,
  63. api_key=self.QDRANT_API_KEY,
  64. timeout=self.QDRANT_TIMEOUT,
  65. )
  66. if self.PREFER_GRPC
  67. else Qclient(url=self.QDRANT_URI, api_key=self.QDRANT_API_KEY, timeout=self.QDRANT_TIMEOUT,)
  68. )
  69. # Main collection types for multi-tenancy
  70. self.MEMORY_COLLECTION = f"{self.collection_prefix}_memories"
  71. self.KNOWLEDGE_COLLECTION = f"{self.collection_prefix}_knowledge"
  72. self.FILE_COLLECTION = f"{self.collection_prefix}_files"
  73. self.WEB_SEARCH_COLLECTION = f"{self.collection_prefix}_web-search"
  74. self.HASH_BASED_COLLECTION = f"{self.collection_prefix}_hash-based"
  75. def _result_to_get_result(self, points) -> GetResult:
  76. ids, documents, metadatas = [], [], []
  77. for point in points:
  78. payload = point.payload
  79. ids.append(point.id)
  80. documents.append(payload["text"])
  81. metadatas.append(payload["metadata"])
  82. return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas])
  83. def _get_collection_and_tenant_id(self, collection_name: str) -> Tuple[str, str]:
  84. """
  85. Maps the traditional collection name to multi-tenant collection and tenant ID.
  86. Returns:
  87. tuple: (collection_name, tenant_id)
  88. """
  89. # Check for user memory collections
  90. tenant_id = collection_name
  91. if collection_name.startswith("user-memory-"):
  92. return self.MEMORY_COLLECTION, tenant_id
  93. # Check for file collections
  94. elif collection_name.startswith("file-"):
  95. return self.FILE_COLLECTION, tenant_id
  96. # Check for web search collections
  97. elif collection_name.startswith("web-search-"):
  98. return self.WEB_SEARCH_COLLECTION, tenant_id
  99. # Handle hash-based collections (YouTube and web URLs)
  100. elif len(collection_name) == 63 and all(
  101. c in "0123456789abcdef" for c in collection_name
  102. ):
  103. return self.HASH_BASED_COLLECTION, tenant_id
  104. else:
  105. return self.KNOWLEDGE_COLLECTION, tenant_id
  106. def _create_multi_tenant_collection(
  107. self, mt_collection_name: str, dimension: int = DEFAULT_DIMENSION
  108. ):
  109. """
  110. Creates a collection with multi-tenancy configuration and payload indexes for tenant_id and metadata fields.
  111. """
  112. self.client.create_collection(
  113. collection_name=mt_collection_name,
  114. vectors_config=models.VectorParams(
  115. size=dimension,
  116. distance=models.Distance.COSINE,
  117. on_disk=self.QDRANT_ON_DISK,
  118. ),
  119. # Disable global index building due to multitenancy
  120. # For more details https://qdrant.tech/documentation/guides/multiple-partitions/#calibrate-performance
  121. hnsw_config=models.HnswConfigDiff(
  122. payload_m=self.QDRANT_HNSW_M,
  123. m=0,
  124. ),
  125. )
  126. log.info(
  127. f"Multi-tenant collection {mt_collection_name} created with dimension {dimension}!"
  128. )
  129. self.client.create_payload_index(
  130. collection_name=mt_collection_name,
  131. field_name=TENANT_ID_FIELD,
  132. field_schema=models.KeywordIndexParams(
  133. type=models.KeywordIndexType.KEYWORD,
  134. is_tenant=True,
  135. on_disk=self.QDRANT_ON_DISK,
  136. ),
  137. )
  138. for field in ("metadata.hash", "metadata.file_id"):
  139. self.client.create_payload_index(
  140. collection_name=mt_collection_name,
  141. field_name=field,
  142. field_schema=models.KeywordIndexParams(
  143. type=models.KeywordIndexType.KEYWORD,
  144. on_disk=self.QDRANT_ON_DISK,
  145. ),
  146. )
  147. def _create_points(
  148. self, items: List[VectorItem], tenant_id: str
  149. ) -> List[PointStruct]:
  150. """
  151. Create point structs from vector items with tenant ID.
  152. """
  153. return [
  154. PointStruct(
  155. id=item["id"],
  156. vector=item["vector"],
  157. payload={
  158. "text": item["text"],
  159. "metadata": item["metadata"],
  160. TENANT_ID_FIELD: tenant_id,
  161. },
  162. )
  163. for item in items
  164. ]
  165. def _ensure_collection(
  166. self, mt_collection_name: str, dimension: int = DEFAULT_DIMENSION
  167. ):
  168. """
  169. Ensure the collection exists and payload indexes are created for tenant_id and metadata fields.
  170. """
  171. if not self.client.collection_exists(collection_name=mt_collection_name):
  172. self._create_multi_tenant_collection(mt_collection_name, dimension)
  173. def has_collection(self, collection_name: str) -> bool:
  174. """
  175. Check if a logical collection exists by checking for any points with the tenant ID.
  176. """
  177. if not self.client:
  178. return False
  179. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  180. if not self.client.collection_exists(collection_name=mt_collection):
  181. return False
  182. tenant_filter = _tenant_filter(tenant_id)
  183. count_result = self.client.count(
  184. collection_name=mt_collection,
  185. count_filter=models.Filter(must=[tenant_filter]),
  186. )
  187. return count_result.count > 0
  188. def delete(
  189. self,
  190. collection_name: str,
  191. ids: Optional[List[str]] = None,
  192. filter: Optional[Dict[str, Any]] = None,
  193. ):
  194. """
  195. Delete vectors by ID or filter from a collection with tenant isolation.
  196. """
  197. if not self.client:
  198. return None
  199. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  200. if not self.client.collection_exists(collection_name=mt_collection):
  201. log.debug(f"Collection {mt_collection} doesn't exist, nothing to delete")
  202. return None
  203. must_conditions = [_tenant_filter(tenant_id)]
  204. should_conditions = []
  205. if ids:
  206. should_conditions = [_metadata_filter("id", id_value) for id_value in ids]
  207. elif filter:
  208. must_conditions += [_metadata_filter(k, v) for k, v in filter.items()]
  209. return self.client.delete(
  210. collection_name=mt_collection,
  211. points_selector=models.FilterSelector(
  212. filter=models.Filter(must=must_conditions, should=should_conditions)
  213. ),
  214. )
  215. def search(
  216. self, collection_name: str, vectors: List[List[float | int]], limit: int
  217. ) -> Optional[SearchResult]:
  218. """
  219. Search for the nearest neighbor items based on the vectors with tenant isolation.
  220. """
  221. if not self.client or not vectors:
  222. return None
  223. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  224. if not self.client.collection_exists(collection_name=mt_collection):
  225. log.debug(f"Collection {mt_collection} doesn't exist, search returns None")
  226. return None
  227. tenant_filter = _tenant_filter(tenant_id)
  228. query_response = self.client.query_points(
  229. collection_name=mt_collection,
  230. query=vectors[0],
  231. limit=limit,
  232. query_filter=models.Filter(must=[tenant_filter]),
  233. )
  234. get_result = self._result_to_get_result(query_response.points)
  235. return SearchResult(
  236. ids=get_result.ids,
  237. documents=get_result.documents,
  238. metadatas=get_result.metadatas,
  239. distances=[[(point.score + 1.0) / 2.0 for point in query_response.points]],
  240. )
  241. def query(
  242. self, collection_name: str, filter: Dict[str, Any], limit: Optional[int] = None
  243. ):
  244. """
  245. Query points with filters and tenant isolation.
  246. """
  247. if not self.client:
  248. return None
  249. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  250. if not self.client.collection_exists(collection_name=mt_collection):
  251. log.debug(f"Collection {mt_collection} doesn't exist, query returns None")
  252. return None
  253. if limit is None:
  254. limit = NO_LIMIT
  255. tenant_filter = _tenant_filter(tenant_id)
  256. field_conditions = [_metadata_filter(k, v) for k, v in filter.items()]
  257. combined_filter = models.Filter(must=[tenant_filter, *field_conditions])
  258. points = self.client.scroll(
  259. collection_name=mt_collection,
  260. scroll_filter=combined_filter,
  261. limit=limit,
  262. )
  263. return self._result_to_get_result(points[0])
  264. def get(self, collection_name: str) -> Optional[GetResult]:
  265. """
  266. Get all items in a collection with tenant isolation.
  267. """
  268. if not self.client:
  269. return None
  270. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  271. if not self.client.collection_exists(collection_name=mt_collection):
  272. log.debug(f"Collection {mt_collection} doesn't exist, get returns None")
  273. return None
  274. tenant_filter = _tenant_filter(tenant_id)
  275. points = self.client.scroll(
  276. collection_name=mt_collection,
  277. scroll_filter=models.Filter(must=[tenant_filter]),
  278. limit=NO_LIMIT,
  279. )
  280. return self._result_to_get_result(points[0])
  281. def upsert(self, collection_name: str, items: List[VectorItem]):
  282. """
  283. Upsert items with tenant ID.
  284. """
  285. if not self.client or not items:
  286. return None
  287. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  288. dimension = len(items[0]["vector"])
  289. self._ensure_collection(mt_collection, dimension)
  290. points = self._create_points(items, tenant_id)
  291. self.client.upload_points(mt_collection, points)
  292. return None
  293. def insert(self, collection_name: str, items: List[VectorItem]):
  294. """
  295. Insert items with tenant ID.
  296. """
  297. return self.upsert(collection_name, items)
  298. def reset(self):
  299. """
  300. Reset the database by deleting all collections.
  301. """
  302. if not self.client:
  303. return None
  304. for collection in self.client.get_collections().collections:
  305. if collection.name.startswith(self.collection_prefix):
  306. self.client.delete_collection(collection_name=collection.name)
  307. def delete_collection(self, collection_name: str):
  308. """
  309. Delete a collection.
  310. """
  311. if not self.client:
  312. return None
  313. mt_collection, tenant_id = self._get_collection_and_tenant_id(collection_name)
  314. if not self.client.collection_exists(collection_name=mt_collection):
  315. log.debug(f"Collection {mt_collection} doesn't exist, nothing to delete")
  316. return None
  317. self.client.delete(
  318. collection_name=mt_collection,
  319. points_selector=models.FilterSelector(
  320. filter=models.Filter(must=[_tenant_filter(tenant_id)])
  321. ),
  322. )