chroma.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import chromadb
  2. from chromadb import Settings
  3. from chromadb.utils.batch_utils import create_batches
  4. from typing import Optional
  5. from open_webui.apps.retrieval.vector.main import VectorItem, SearchResult, GetResult
  6. from open_webui.config import (
  7. CHROMA_DATA_PATH,
  8. CHROMA_HTTP_HOST,
  9. CHROMA_HTTP_PORT,
  10. CHROMA_HTTP_HEADERS,
  11. CHROMA_HTTP_SSL,
  12. CHROMA_TENANT,
  13. CHROMA_DATABASE,
  14. CHROMA_CLIENT_AUTH_PROVIDER,
  15. CHROMA_CLIENT_AUTH_CREDENTIALS,
  16. )
  17. class ChromaClient:
  18. def __init__(self):
  19. settings_dict = {
  20. "allow_reset": True,
  21. "anonymized_telemetry": False,
  22. }
  23. if CHROMA_CLIENT_AUTH_PROVIDER is not None:
  24. settings_dict["chroma_client_auth_provider"] = CHROMA_CLIENT_AUTH_PROVIDER
  25. if CHROMA_CLIENT_AUTH_CREDENTIALS is not None:
  26. settings_dict["chroma_client_auth_credentials"] = CHROMA_CLIENT_AUTH_CREDENTIALS
  27. if CHROMA_HTTP_HOST != "":
  28. self.client = chromadb.HttpClient(
  29. host=CHROMA_HTTP_HOST,
  30. port=CHROMA_HTTP_PORT,
  31. headers=CHROMA_HTTP_HEADERS,
  32. ssl=CHROMA_HTTP_SSL,
  33. tenant=CHROMA_TENANT,
  34. database=CHROMA_DATABASE,
  35. settings=Settings(**settings_dict),
  36. )
  37. else:
  38. self.client = chromadb.PersistentClient(
  39. path=CHROMA_DATA_PATH,
  40. settings=Settings(**settings_dict),
  41. tenant=CHROMA_TENANT,
  42. database=CHROMA_DATABASE,
  43. )
  44. def has_collection(self, collection_name: str) -> bool:
  45. # Check if the collection exists based on the collection name.
  46. collections = self.client.list_collections()
  47. return collection_name in [collection.name for collection in collections]
  48. def delete_collection(self, collection_name: str):
  49. # Delete the collection based on the collection name.
  50. return self.client.delete_collection(name=collection_name)
  51. def search(
  52. self, collection_name: str, vectors: list[list[float | int]], limit: int
  53. ) -> Optional[SearchResult]:
  54. # Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
  55. try:
  56. collection = self.client.get_collection(name=collection_name)
  57. if collection:
  58. result = collection.query(
  59. query_embeddings=vectors,
  60. n_results=limit,
  61. )
  62. return SearchResult(
  63. **{
  64. "ids": result["ids"],
  65. "distances": result["distances"],
  66. "documents": result["documents"],
  67. "metadatas": result["metadatas"],
  68. }
  69. )
  70. return None
  71. except Exception as e:
  72. return None
  73. def query(
  74. self, collection_name: str, filter: dict, limit: Optional[int] = None
  75. ) -> Optional[GetResult]:
  76. # Query the items from the collection based on the filter.
  77. try:
  78. collection = self.client.get_collection(name=collection_name)
  79. if collection:
  80. result = collection.get(
  81. where=filter,
  82. limit=limit,
  83. )
  84. return GetResult(
  85. **{
  86. "ids": [result["ids"]],
  87. "documents": [result["documents"]],
  88. "metadatas": [result["metadatas"]],
  89. }
  90. )
  91. return None
  92. except Exception as e:
  93. print(e)
  94. return None
  95. def get(self, collection_name: str) -> Optional[GetResult]:
  96. # Get all the items in the collection.
  97. collection = self.client.get_collection(name=collection_name)
  98. if collection:
  99. result = collection.get()
  100. return GetResult(
  101. **{
  102. "ids": [result["ids"]],
  103. "documents": [result["documents"]],
  104. "metadatas": [result["metadatas"]],
  105. }
  106. )
  107. return None
  108. def insert(self, collection_name: str, items: list[VectorItem]):
  109. # Insert the items into the collection, if the collection does not exist, it will be created.
  110. collection = self.client.get_or_create_collection(
  111. name=collection_name, metadata={"hnsw:space": "cosine"}
  112. )
  113. ids = [item["id"] for item in items]
  114. documents = [item["text"] for item in items]
  115. embeddings = [item["vector"] for item in items]
  116. metadatas = [item["metadata"] for item in items]
  117. for batch in create_batches(
  118. api=self.client,
  119. documents=documents,
  120. embeddings=embeddings,
  121. ids=ids,
  122. metadatas=metadatas,
  123. ):
  124. collection.add(*batch)
  125. def upsert(self, collection_name: str, items: list[VectorItem]):
  126. # Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
  127. collection = self.client.get_or_create_collection(
  128. name=collection_name, metadata={"hnsw:space": "cosine"}
  129. )
  130. ids = [item["id"] for item in items]
  131. documents = [item["text"] for item in items]
  132. embeddings = [item["vector"] for item in items]
  133. metadatas = [item["metadata"] for item in items]
  134. collection.upsert(
  135. ids=ids, documents=documents, embeddings=embeddings, metadatas=metadatas
  136. )
  137. def delete(
  138. self,
  139. collection_name: str,
  140. ids: Optional[list[str]] = None,
  141. filter: Optional[dict] = None,
  142. ):
  143. # Delete the items from the collection based on the ids.
  144. collection = self.client.get_collection(name=collection_name)
  145. if collection:
  146. if ids:
  147. collection.delete(ids=ids)
  148. elif filter:
  149. collection.delete(where=filter)
  150. def reset(self):
  151. # Resets the database. This will delete all collections and item entries.
  152. return self.client.reset()