vector.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """Abstraction for a vector that can be stored in the system."""
  2. from enum import Enum
  3. from typing import Any, Optional
  4. from uuid import UUID
  5. from pydantic import BaseModel, Field
  6. from .base import R2RSerializable
  7. class VectorType(str, Enum):
  8. FIXED = "FIXED"
  9. class IndexMethod(str, Enum):
  10. """An enum representing the index methods available.
  11. This class currently only supports the 'ivfflat' method but may
  12. expand in the future.
  13. Attributes:
  14. auto (str): Automatically choose the best available index method.
  15. ivfflat (str): The ivfflat index method.
  16. hnsw (str): The hnsw index method.
  17. """
  18. auto = "auto"
  19. ivfflat = "ivfflat"
  20. hnsw = "hnsw"
  21. def __str__(self) -> str:
  22. return self.value
  23. class IndexMeasure(str, Enum):
  24. """An enum representing the types of distance measures available for
  25. indexing.
  26. Attributes:
  27. cosine_distance (str): The cosine distance measure for indexing.
  28. l2_distance (str): The Euclidean (L2) distance measure for indexing.
  29. max_inner_product (str): The maximum inner product measure for indexing.
  30. """
  31. l2_distance = "l2_distance"
  32. max_inner_product = "max_inner_product"
  33. cosine_distance = "cosine_distance"
  34. l1_distance = "l1_distance"
  35. hamming_distance = "hamming_distance"
  36. jaccard_distance = "jaccard_distance"
  37. def __str__(self) -> str:
  38. return self.value
  39. @property
  40. def ops(self) -> str:
  41. return {
  42. IndexMeasure.l2_distance: "_l2_ops",
  43. IndexMeasure.max_inner_product: "_ip_ops",
  44. IndexMeasure.cosine_distance: "_cosine_ops",
  45. IndexMeasure.l1_distance: "_l1_ops",
  46. IndexMeasure.hamming_distance: "_hamming_ops",
  47. IndexMeasure.jaccard_distance: "_jaccard_ops",
  48. }[self]
  49. @property
  50. def pgvector_repr(self) -> str:
  51. return {
  52. IndexMeasure.l2_distance: "<->",
  53. IndexMeasure.max_inner_product: "<#>",
  54. IndexMeasure.cosine_distance: "<=>",
  55. IndexMeasure.l1_distance: "<+>",
  56. IndexMeasure.hamming_distance: "<~>",
  57. IndexMeasure.jaccard_distance: "<%>",
  58. }[self]
  59. class IndexArgsIVFFlat(R2RSerializable):
  60. """A class for arguments that can optionally be supplied to the index
  61. creation method when building an IVFFlat type index.
  62. Attributes:
  63. nlist (int): The number of IVF centroids that the index should use
  64. """
  65. n_lists: int
  66. class IndexArgsHNSW(R2RSerializable):
  67. """A class for arguments that can optionally be supplied to the index
  68. creation method when building an HNSW type index.
  69. Ref: https://github.com/pgvector/pgvector#index-options
  70. Both attributes are Optional in case the user only wants to specify one and
  71. leave the other as default
  72. Attributes:
  73. m (int): Maximum number of connections per node per layer (default: 16)
  74. ef_construction (int): Size of the dynamic candidate list for
  75. constructing the graph (default: 64)
  76. """
  77. m: Optional[int] = 16
  78. ef_construction: Optional[int] = 64
  79. class VectorTableName(str, Enum):
  80. """This enum represents the different tables where we store vectors."""
  81. CHUNKS = "chunks"
  82. ENTITIES_DOCUMENT = "documents_entities"
  83. GRAPHS_ENTITIES = "graphs_entities"
  84. # TODO: Add support for relationships
  85. # TRIPLES = "relationship"
  86. COMMUNITIES = "graphs_communities"
  87. def __str__(self) -> str:
  88. return self.value
  89. class VectorQuantizationType(str, Enum):
  90. """An enum representing the types of quantization available for vectors.
  91. Attributes:
  92. FP32 (str): 32-bit floating point quantization.
  93. FP16 (str): 16-bit floating point quantization.
  94. INT1 (str): 1-bit integer quantization.
  95. SPARSE (str): Sparse vector quantization.
  96. """
  97. FP32 = "FP32"
  98. FP16 = "FP16"
  99. INT1 = "INT1"
  100. SPARSE = "SPARSE"
  101. def __str__(self) -> str:
  102. return self.value
  103. @property
  104. def db_type(self) -> str:
  105. db_type_mapping = {
  106. "FP32": "vector",
  107. "FP16": "halfvec",
  108. "INT1": "bit",
  109. "SPARSE": "sparsevec",
  110. }
  111. return db_type_mapping[self.value]
  112. class VectorQuantizationSettings(R2RSerializable):
  113. quantization_type: VectorQuantizationType = Field(
  114. default=VectorQuantizationType.FP32
  115. )
  116. class Vector(R2RSerializable):
  117. """A vector with the option to fix the number of elements."""
  118. data: list[float]
  119. type: VectorType = Field(default=VectorType.FIXED)
  120. length: int = Field(default=-1)
  121. def __init__(self, **data):
  122. super().__init__(**data)
  123. if (
  124. self.type == VectorType.FIXED
  125. and self.length > 0
  126. and len(self.data) != self.length
  127. ):
  128. raise ValueError(
  129. f"Vector must be exactly {self.length} elements long."
  130. )
  131. def __repr__(self) -> str:
  132. return (
  133. f"Vector(data={self.data}, type={self.type}, length={self.length})"
  134. )
  135. class VectorEntry(R2RSerializable):
  136. """A vector entry that can be stored directly in supported vector
  137. databases."""
  138. id: UUID
  139. document_id: UUID
  140. owner_id: UUID
  141. collection_ids: list[UUID]
  142. vector: Vector
  143. text: str
  144. metadata: dict[str, Any]
  145. def __str__(self) -> str:
  146. """Return a string representation of the VectorEntry."""
  147. return (
  148. f"VectorEntry("
  149. f"chunk_id={self.id}, "
  150. f"document_id={self.document_id}, "
  151. f"owner_id={self.owner_id}, "
  152. f"collection_ids={self.collection_ids}, "
  153. f"vector={self.vector}, "
  154. f"text={self.text}, "
  155. f"metadata={self.metadata})"
  156. )
  157. def __repr__(self) -> str:
  158. """Return an unambiguous string representation of the VectorEntry."""
  159. return self.__str__()
  160. class StorageResult(R2RSerializable):
  161. """A result of a storage operation."""
  162. success: bool
  163. document_id: UUID
  164. num_chunks: int = 0
  165. error_message: Optional[str] = None
  166. def __str__(self) -> str:
  167. """Return a string representation of the StorageResult."""
  168. return f"StorageResult(success={self.success}, error_message={self.error_message})"
  169. def __repr__(self) -> str:
  170. """Return an unambiguous string representation of the StorageResult."""
  171. return self.__str__()
  172. class IndexConfig(BaseModel):
  173. name: Optional[str] = Field(default=None)
  174. table_name: Optional[str] = Field(default=VectorTableName.CHUNKS)
  175. index_method: Optional[str] = Field(default=IndexMethod.hnsw)
  176. index_measure: Optional[str] = Field(default=IndexMeasure.cosine_distance)
  177. index_arguments: Optional[IndexArgsIVFFlat | IndexArgsHNSW] = Field(
  178. default=None
  179. )
  180. index_name: Optional[str] = Field(default=None)
  181. index_column: Optional[str] = Field(default=None)
  182. concurrently: Optional[bool] = Field(default=True)