chroma.py 5.3 KB

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