pinecone.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. from typing import Optional, List, Dict, Any, Union
  2. import logging
  3. import time # for measuring elapsed time
  4. from pinecone import Pinecone, ServerlessSpec
  5. # Add gRPC support for better performance (Pinecone best practice)
  6. try:
  7. from pinecone.grpc import PineconeGRPC
  8. GRPC_AVAILABLE = True
  9. except ImportError:
  10. GRPC_AVAILABLE = False
  11. import asyncio # for async upserts
  12. import functools # for partial binding in async tasks
  13. import concurrent.futures # for parallel batch upserts
  14. import random # for jitter in retry backoff
  15. from open_webui.retrieval.vector.main import (
  16. VectorDBBase,
  17. VectorItem,
  18. SearchResult,
  19. GetResult,
  20. )
  21. from open_webui.config import (
  22. PINECONE_API_KEY,
  23. PINECONE_ENVIRONMENT,
  24. PINECONE_INDEX_NAME,
  25. PINECONE_DIMENSION,
  26. PINECONE_METRIC,
  27. PINECONE_CLOUD,
  28. )
  29. from open_webui.env import SRC_LOG_LEVELS
  30. NO_LIMIT = 10000 # Reasonable limit to avoid overwhelming the system
  31. BATCH_SIZE = 100 # Recommended batch size for Pinecone operations
  32. log = logging.getLogger(__name__)
  33. log.setLevel(SRC_LOG_LEVELS["RAG"])
  34. class PineconeClient(VectorDBBase):
  35. def __init__(self):
  36. self.collection_prefix = "open-webui"
  37. # Validate required configuration
  38. self._validate_config()
  39. # Store configuration values
  40. self.api_key = PINECONE_API_KEY
  41. self.environment = PINECONE_ENVIRONMENT
  42. self.index_name = PINECONE_INDEX_NAME
  43. self.dimension = PINECONE_DIMENSION
  44. self.metric = PINECONE_METRIC
  45. self.cloud = PINECONE_CLOUD
  46. # Initialize Pinecone client for improved performance
  47. if GRPC_AVAILABLE:
  48. # Use gRPC client for better performance (Pinecone recommendation)
  49. self.client = PineconeGRPC(
  50. api_key=self.api_key,
  51. pool_threads=20, # Improved connection pool size
  52. timeout=30, # Reasonable timeout for operations
  53. )
  54. self.using_grpc = True
  55. log.info("Using Pinecone gRPC client for optimal performance")
  56. else:
  57. # Fallback to HTTP client with enhanced connection pooling
  58. self.client = Pinecone(
  59. api_key=self.api_key,
  60. pool_threads=20, # Improved connection pool size
  61. timeout=30, # Reasonable timeout for operations
  62. )
  63. self.using_grpc = False
  64. log.info("Using Pinecone HTTP client (gRPC not available)")
  65. # Persistent executor for batch operations
  66. self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
  67. # Create index if it doesn't exist
  68. self._initialize_index()
  69. def _validate_config(self) -> None:
  70. """Validate that all required configuration variables are set."""
  71. missing_vars = []
  72. if not PINECONE_API_KEY:
  73. missing_vars.append("PINECONE_API_KEY")
  74. if not PINECONE_ENVIRONMENT:
  75. missing_vars.append("PINECONE_ENVIRONMENT")
  76. if not PINECONE_INDEX_NAME:
  77. missing_vars.append("PINECONE_INDEX_NAME")
  78. if not PINECONE_DIMENSION:
  79. missing_vars.append("PINECONE_DIMENSION")
  80. if not PINECONE_CLOUD:
  81. missing_vars.append("PINECONE_CLOUD")
  82. if missing_vars:
  83. raise ValueError(
  84. f"Required configuration missing: {', '.join(missing_vars)}"
  85. )
  86. def _initialize_index(self) -> None:
  87. """Initialize the Pinecone index."""
  88. try:
  89. # Check if index exists
  90. if self.index_name not in self.client.list_indexes().names():
  91. log.info(f"Creating Pinecone index '{self.index_name}'...")
  92. self.client.create_index(
  93. name=self.index_name,
  94. dimension=self.dimension,
  95. metric=self.metric,
  96. spec=ServerlessSpec(cloud=self.cloud, region=self.environment),
  97. )
  98. log.info(f"Successfully created Pinecone index '{self.index_name}'")
  99. else:
  100. log.info(f"Using existing Pinecone index '{self.index_name}'")
  101. # Connect to the index
  102. self.index = self.client.Index(
  103. self.index_name,
  104. pool_threads=20, # Enhanced connection pool for index operations
  105. )
  106. except Exception as e:
  107. log.error(f"Failed to initialize Pinecone index: {e}")
  108. raise RuntimeError(f"Failed to initialize Pinecone index: {e}")
  109. def _retry_pinecone_operation(self, operation_func, max_retries=3):
  110. """Retry Pinecone operations with exponential backoff for rate limits and network issues."""
  111. for attempt in range(max_retries):
  112. try:
  113. return operation_func()
  114. except Exception as e:
  115. error_str = str(e).lower()
  116. # Check if it's a retryable error (rate limits, network issues, timeouts)
  117. is_retryable = any(
  118. keyword in error_str
  119. for keyword in [
  120. "rate limit",
  121. "quota",
  122. "timeout",
  123. "network",
  124. "connection",
  125. "unavailable",
  126. "internal error",
  127. "429",
  128. "500",
  129. "502",
  130. "503",
  131. "504",
  132. ]
  133. )
  134. if not is_retryable or attempt == max_retries - 1:
  135. # Don't retry for non-retryable errors or on final attempt
  136. raise
  137. # Exponential backoff with jitter
  138. delay = (2**attempt) + random.uniform(0, 1)
  139. log.warning(
  140. f"Pinecone operation failed (attempt {attempt + 1}/{max_retries}), "
  141. f"retrying in {delay:.2f}s: {e}"
  142. )
  143. time.sleep(delay)
  144. def _create_points(
  145. self, items: List[VectorItem], collection_name_with_prefix: str
  146. ) -> List[Dict[str, Any]]:
  147. """Convert VectorItem objects to Pinecone point format."""
  148. points = []
  149. for item in items:
  150. # Start with any existing metadata or an empty dict
  151. metadata = item.get("metadata", {}).copy() if item.get("metadata") else {}
  152. # Add text to metadata if available
  153. if "text" in item:
  154. metadata["text"] = item["text"]
  155. # Always add collection_name to metadata for filtering
  156. metadata["collection_name"] = collection_name_with_prefix
  157. point = {
  158. "id": item["id"],
  159. "values": item["vector"],
  160. "metadata": metadata,
  161. }
  162. points.append(point)
  163. return points
  164. def _get_collection_name_with_prefix(self, collection_name: str) -> str:
  165. """Get the collection name with prefix."""
  166. return f"{self.collection_prefix}_{collection_name}"
  167. def _normalize_distance(self, score: float) -> float:
  168. """Normalize distance score based on the metric used."""
  169. if self.metric.lower() == "cosine":
  170. # Cosine similarity ranges from -1 to 1, normalize to 0 to 1
  171. return (score + 1.0) / 2.0
  172. elif self.metric.lower() in ["euclidean", "dotproduct"]:
  173. # These are already suitable for ranking (smaller is better for Euclidean)
  174. return score
  175. else:
  176. # For other metrics, use as is
  177. return score
  178. def _result_to_get_result(self, matches: list) -> GetResult:
  179. """Convert Pinecone matches to GetResult format."""
  180. ids = []
  181. documents = []
  182. metadatas = []
  183. for match in matches:
  184. metadata = getattr(match, "metadata", {}) or {}
  185. ids.append(match.id if hasattr(match, "id") else match["id"])
  186. documents.append(metadata.get("text", ""))
  187. metadatas.append(metadata)
  188. return GetResult(
  189. **{
  190. "ids": [ids],
  191. "documents": [documents],
  192. "metadatas": [metadatas],
  193. }
  194. )
  195. def has_collection(self, collection_name: str) -> bool:
  196. """Check if a collection exists by searching for at least one item."""
  197. collection_name_with_prefix = self._get_collection_name_with_prefix(
  198. collection_name
  199. )
  200. try:
  201. # Search for at least 1 item with this collection name in metadata
  202. response = self.index.query(
  203. vector=[0.0] * self.dimension, # dummy vector
  204. top_k=1,
  205. filter={"collection_name": collection_name_with_prefix},
  206. include_metadata=False,
  207. )
  208. matches = getattr(response, "matches", []) or []
  209. return len(matches) > 0
  210. except Exception as e:
  211. log.exception(
  212. f"Error checking collection '{collection_name_with_prefix}': {e}"
  213. )
  214. return False
  215. def delete_collection(self, collection_name: str) -> None:
  216. """Delete a collection by removing all vectors with the collection name in metadata."""
  217. collection_name_with_prefix = self._get_collection_name_with_prefix(
  218. collection_name
  219. )
  220. try:
  221. self.index.delete(filter={"collection_name": collection_name_with_prefix})
  222. log.info(
  223. f"Collection '{collection_name_with_prefix}' deleted (all vectors removed)."
  224. )
  225. except Exception as e:
  226. log.warning(
  227. f"Failed to delete collection '{collection_name_with_prefix}': {e}"
  228. )
  229. raise
  230. def insert(self, collection_name: str, items: List[VectorItem]) -> None:
  231. """Insert vectors into a collection."""
  232. if not items:
  233. log.warning("No items to insert")
  234. return
  235. start_time = time.time()
  236. collection_name_with_prefix = self._get_collection_name_with_prefix(
  237. collection_name
  238. )
  239. points = self._create_points(items, collection_name_with_prefix)
  240. # Parallelize batch inserts for performance
  241. executor = self._executor
  242. futures = []
  243. for i in range(0, len(points), BATCH_SIZE):
  244. batch = points[i : i + BATCH_SIZE]
  245. futures.append(executor.submit(self.index.upsert, vectors=batch))
  246. for future in concurrent.futures.as_completed(futures):
  247. try:
  248. future.result()
  249. except Exception as e:
  250. log.error(f"Error inserting batch: {e}")
  251. raise
  252. elapsed = time.time() - start_time
  253. log.debug(f"Insert of {len(points)} vectors took {elapsed:.2f} seconds")
  254. log.info(
  255. f"Successfully inserted {len(points)} vectors in parallel batches "
  256. f"into '{collection_name_with_prefix}'"
  257. )
  258. def upsert(self, collection_name: str, items: List[VectorItem]) -> None:
  259. """Upsert (insert or update) vectors into a collection."""
  260. if not items:
  261. log.warning("No items to upsert")
  262. return
  263. start_time = time.time()
  264. collection_name_with_prefix = self._get_collection_name_with_prefix(
  265. collection_name
  266. )
  267. points = self._create_points(items, collection_name_with_prefix)
  268. # Parallelize batch upserts for performance
  269. executor = self._executor
  270. futures = []
  271. for i in range(0, len(points), BATCH_SIZE):
  272. batch = points[i : i + BATCH_SIZE]
  273. futures.append(executor.submit(self.index.upsert, vectors=batch))
  274. for future in concurrent.futures.as_completed(futures):
  275. try:
  276. future.result()
  277. except Exception as e:
  278. log.error(f"Error upserting batch: {e}")
  279. raise
  280. elapsed = time.time() - start_time
  281. log.debug(f"Upsert of {len(points)} vectors took {elapsed:.2f} seconds")
  282. log.info(
  283. f"Successfully upserted {len(points)} vectors in parallel batches "
  284. f"into '{collection_name_with_prefix}'"
  285. )
  286. async def insert_async(self, collection_name: str, items: List[VectorItem]) -> None:
  287. """Async version of insert using asyncio and run_in_executor for improved performance."""
  288. if not items:
  289. log.warning("No items to insert")
  290. return
  291. collection_name_with_prefix = self._get_collection_name_with_prefix(
  292. collection_name
  293. )
  294. points = self._create_points(items, collection_name_with_prefix)
  295. # Create batches
  296. batches = [
  297. points[i : i + BATCH_SIZE] for i in range(0, len(points), BATCH_SIZE)
  298. ]
  299. loop = asyncio.get_event_loop()
  300. tasks = [
  301. loop.run_in_executor(
  302. None, functools.partial(self.index.upsert, vectors=batch)
  303. )
  304. for batch in batches
  305. ]
  306. results = await asyncio.gather(*tasks, return_exceptions=True)
  307. for result in results:
  308. if isinstance(result, Exception):
  309. log.error(f"Error in async insert batch: {result}")
  310. raise result
  311. log.info(
  312. f"Successfully async inserted {len(points)} vectors in batches "
  313. f"into '{collection_name_with_prefix}'"
  314. )
  315. async def upsert_async(self, collection_name: str, items: List[VectorItem]) -> None:
  316. """Async version of upsert using asyncio and run_in_executor for improved performance."""
  317. if not items:
  318. log.warning("No items to upsert")
  319. return
  320. collection_name_with_prefix = self._get_collection_name_with_prefix(
  321. collection_name
  322. )
  323. points = self._create_points(items, collection_name_with_prefix)
  324. # Create batches
  325. batches = [
  326. points[i : i + BATCH_SIZE] for i in range(0, len(points), BATCH_SIZE)
  327. ]
  328. loop = asyncio.get_event_loop()
  329. tasks = [
  330. loop.run_in_executor(
  331. None, functools.partial(self.index.upsert, vectors=batch)
  332. )
  333. for batch in batches
  334. ]
  335. results = await asyncio.gather(*tasks, return_exceptions=True)
  336. for result in results:
  337. if isinstance(result, Exception):
  338. log.error(f"Error in async upsert batch: {result}")
  339. raise result
  340. log.info(
  341. f"Successfully async upserted {len(points)} vectors in batches "
  342. f"into '{collection_name_with_prefix}'"
  343. )
  344. def search(
  345. self, collection_name: str, vectors: List[List[Union[float, int]]], limit: int
  346. ) -> Optional[SearchResult]:
  347. """Search for similar vectors in a collection."""
  348. if not vectors or not vectors[0]:
  349. log.warning("No vectors provided for search")
  350. return None
  351. collection_name_with_prefix = self._get_collection_name_with_prefix(
  352. collection_name
  353. )
  354. if limit is None or limit <= 0:
  355. limit = NO_LIMIT
  356. try:
  357. # Search using the first vector (assuming this is the intended behavior)
  358. query_vector = vectors[0]
  359. # Perform the search
  360. query_response = self.index.query(
  361. vector=query_vector,
  362. top_k=limit,
  363. include_metadata=True,
  364. filter={"collection_name": collection_name_with_prefix},
  365. )
  366. matches = getattr(query_response, "matches", []) or []
  367. if not matches:
  368. # Return empty result if no matches
  369. return SearchResult(
  370. ids=[[]],
  371. documents=[[]],
  372. metadatas=[[]],
  373. distances=[[]],
  374. )
  375. # Convert to GetResult format
  376. get_result = self._result_to_get_result(matches)
  377. # Calculate normalized distances based on metric
  378. distances = [
  379. [
  380. self._normalize_distance(getattr(match, "score", 0.0))
  381. for match in matches
  382. ]
  383. ]
  384. return SearchResult(
  385. ids=get_result.ids,
  386. documents=get_result.documents,
  387. metadatas=get_result.metadatas,
  388. distances=distances,
  389. )
  390. except Exception as e:
  391. log.error(f"Error searching in '{collection_name_with_prefix}': {e}")
  392. return None
  393. def query(
  394. self, collection_name: str, filter: Dict, limit: Optional[int] = None
  395. ) -> Optional[GetResult]:
  396. """Query vectors by metadata filter."""
  397. collection_name_with_prefix = self._get_collection_name_with_prefix(
  398. collection_name
  399. )
  400. if limit is None or limit <= 0:
  401. limit = NO_LIMIT
  402. try:
  403. # Create a zero vector for the dimension as Pinecone requires a vector
  404. zero_vector = [0.0] * self.dimension
  405. # Combine user filter with collection_name
  406. pinecone_filter = {"collection_name": collection_name_with_prefix}
  407. if filter:
  408. pinecone_filter.update(filter)
  409. # Perform metadata-only query
  410. query_response = self.index.query(
  411. vector=zero_vector,
  412. filter=pinecone_filter,
  413. top_k=limit,
  414. include_metadata=True,
  415. )
  416. matches = getattr(query_response, "matches", []) or []
  417. return self._result_to_get_result(matches)
  418. except Exception as e:
  419. log.error(f"Error querying collection '{collection_name}': {e}")
  420. return None
  421. def get(self, collection_name: str) -> Optional[GetResult]:
  422. """Get all vectors in a collection."""
  423. collection_name_with_prefix = self._get_collection_name_with_prefix(
  424. collection_name
  425. )
  426. try:
  427. # Use a zero vector for fetching all entries
  428. zero_vector = [0.0] * self.dimension
  429. # Add filter to only get vectors for this collection
  430. query_response = self.index.query(
  431. vector=zero_vector,
  432. top_k=NO_LIMIT,
  433. include_metadata=True,
  434. filter={"collection_name": collection_name_with_prefix},
  435. )
  436. matches = getattr(query_response, "matches", []) or []
  437. return self._result_to_get_result(matches)
  438. except Exception as e:
  439. log.error(f"Error getting collection '{collection_name}': {e}")
  440. return None
  441. def delete(
  442. self,
  443. collection_name: str,
  444. ids: Optional[List[str]] = None,
  445. filter: Optional[Dict] = None,
  446. ) -> None:
  447. """Delete vectors by IDs or filter."""
  448. collection_name_with_prefix = self._get_collection_name_with_prefix(
  449. collection_name
  450. )
  451. try:
  452. if ids:
  453. # Delete by IDs (in batches for large deletions)
  454. for i in range(0, len(ids), BATCH_SIZE):
  455. batch_ids = ids[i : i + BATCH_SIZE]
  456. # Note: When deleting by ID, we can't filter by collection_name
  457. # This is a limitation of Pinecone - be careful with ID uniqueness
  458. self.index.delete(ids=batch_ids)
  459. log.debug(
  460. f"Deleted batch of {len(batch_ids)} vectors by ID "
  461. f"from '{collection_name_with_prefix}'"
  462. )
  463. log.info(
  464. f"Successfully deleted {len(ids)} vectors by ID "
  465. f"from '{collection_name_with_prefix}'"
  466. )
  467. elif filter:
  468. # Combine user filter with collection_name
  469. pinecone_filter = {"collection_name": collection_name_with_prefix}
  470. if filter:
  471. pinecone_filter.update(filter)
  472. # Delete by metadata filter
  473. self.index.delete(filter=pinecone_filter)
  474. log.info(
  475. f"Successfully deleted vectors by filter from '{collection_name_with_prefix}'"
  476. )
  477. else:
  478. log.warning("No ids or filter provided for delete operation")
  479. except Exception as e:
  480. log.error(f"Error deleting from collection '{collection_name}': {e}")
  481. raise
  482. def reset(self) -> None:
  483. """Reset the database by deleting all collections."""
  484. try:
  485. self.index.delete(delete_all=True)
  486. log.info("All vectors successfully deleted from the index.")
  487. except Exception as e:
  488. log.error(f"Failed to reset Pinecone index: {e}")
  489. raise
  490. def close(self):
  491. """Shut down resources."""
  492. try:
  493. # The new Pinecone client doesn't need explicit closing
  494. pass
  495. except Exception as e:
  496. log.warning(f"Failed to clean up Pinecone resources: {e}")
  497. self._executor.shutdown(wait=True)
  498. def __enter__(self):
  499. """Enter context manager."""
  500. return self
  501. def __exit__(self, exc_type, exc_val, exc_tb):
  502. """Exit context manager, ensuring resources are cleaned up."""
  503. self.close()