main.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from pydantic import BaseModel
  2. from abc import ABC, abstractmethod
  3. from typing import Any, Dict, List, Optional, Union
  4. class VectorItem(BaseModel):
  5. id: str
  6. text: str
  7. vector: List[float | int]
  8. metadata: Any
  9. class GetResult(BaseModel):
  10. ids: Optional[List[List[str]]]
  11. documents: Optional[List[List[str]]]
  12. metadatas: Optional[List[List[Any]]]
  13. class SearchResult(GetResult):
  14. distances: Optional[List[List[float | int]]]
  15. class VectorDBBase(ABC):
  16. """
  17. Abstract base class for all vector database backends.
  18. Implementations of this class provide methods for collection management,
  19. vector insertion, deletion, similarity search, and metadata filtering.
  20. Any custom vector database integration must inherit from this class and
  21. implement all abstract methods.
  22. """
  23. @abstractmethod
  24. def has_collection(self, collection_name: str) -> bool:
  25. """Check if the collection exists in the vector DB."""
  26. pass
  27. @abstractmethod
  28. def delete_collection(self, collection_name: str) -> None:
  29. """Delete a collection from the vector DB."""
  30. pass
  31. @abstractmethod
  32. def insert(self, collection_name: str, items: List[VectorItem]) -> None:
  33. """Insert a list of vector items into a collection."""
  34. pass
  35. @abstractmethod
  36. def upsert(self, collection_name: str, items: List[VectorItem]) -> None:
  37. """Insert or update vector items in a collection."""
  38. pass
  39. @abstractmethod
  40. def search(
  41. self, collection_name: str, vectors: List[List[Union[float, int]]], limit: int
  42. ) -> Optional[SearchResult]:
  43. """Search for similar vectors in a collection."""
  44. pass
  45. @abstractmethod
  46. def query(
  47. self, collection_name: str, filter: Dict, limit: Optional[int] = None
  48. ) -> Optional[GetResult]:
  49. """Query vectors from a collection using metadata filter."""
  50. pass
  51. @abstractmethod
  52. def get(self, collection_name: str) -> Optional[GetResult]:
  53. """Retrieve all vectors from a collection."""
  54. pass
  55. @abstractmethod
  56. def delete(
  57. self,
  58. collection_name: str,
  59. ids: Optional[List[str]] = None,
  60. filter: Optional[Dict] = None,
  61. ) -> None:
  62. """Delete vectors by ID or filter from a collection."""
  63. pass
  64. @abstractmethod
  65. def reset(self) -> None:
  66. """Reset the vector database by removing all collections or those matching a condition."""
  67. pass