pinecone.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import os
  2. from typing import Dict, List, Optional, Tuple, Union
  3. try:
  4. import pinecone
  5. except ImportError:
  6. raise ImportError(
  7. "Pinecone requires extra dependencies. Install with `pip install --upgrade 'embedchain[pinecone]'`"
  8. ) from None
  9. from embedchain.config.vectordb.pinecone import PineconeDBConfig
  10. from embedchain.helper.json_serializable import register_deserializable
  11. from embedchain.vectordb.base import BaseVectorDB
  12. @register_deserializable
  13. class PineconeDB(BaseVectorDB):
  14. """
  15. Pinecone as vector database
  16. """
  17. BATCH_SIZE = 100
  18. def __init__(
  19. self,
  20. config: Optional[PineconeDBConfig] = None,
  21. ):
  22. """Pinecone as vector database.
  23. :param config: Pinecone database config, defaults to None
  24. :type config: PineconeDBConfig, optional
  25. :raises ValueError: No config provided
  26. """
  27. if config is None:
  28. self.config = PineconeDBConfig()
  29. else:
  30. if not isinstance(config, PineconeDBConfig):
  31. raise TypeError(
  32. "config is not a `PineconeDBConfig` instance. "
  33. "Please make sure the type is right and that you are passing an instance."
  34. )
  35. self.config = config
  36. self.client = self._setup_pinecone_index()
  37. # Call parent init here because embedder is needed
  38. super().__init__(config=self.config)
  39. def _initialize(self):
  40. """
  41. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  42. """
  43. if not self.embedder:
  44. raise ValueError("Embedder not set. Please set an embedder with `set_embedder` before initialization.")
  45. # Loads the Pinecone index or creates it if not present.
  46. def _setup_pinecone_index(self):
  47. pinecone.init(
  48. api_key=os.environ.get("PINECONE_API_KEY"),
  49. environment=os.environ.get("PINECONE_ENV"),
  50. **self.config.extra_params,
  51. )
  52. self.index_name = self._get_index_name()
  53. indexes = pinecone.list_indexes()
  54. if indexes is None or self.index_name not in indexes:
  55. pinecone.create_index(
  56. name=self.index_name, metric=self.config.metric, dimension=self.config.vector_dimension
  57. )
  58. return pinecone.Index(self.index_name)
  59. def get(self, ids: Optional[List[str]] = None, where: Optional[Dict[str, any]] = None, limit: Optional[int] = None):
  60. """
  61. Get existing doc ids present in vector database
  62. :param ids: _list of doc ids to check for existence
  63. :type ids: List[str]
  64. :param where: to filter data
  65. :type where: Dict[str, any]
  66. :return: ids
  67. :rtype: Set[str]
  68. """
  69. existing_ids = list()
  70. if ids is not None:
  71. for i in range(0, len(ids), 1000):
  72. result = self.client.fetch(ids=ids[i : i + 1000])
  73. batch_existing_ids = list(result.get("vectors").keys())
  74. existing_ids.extend(batch_existing_ids)
  75. return {"ids": existing_ids}
  76. def add(
  77. self,
  78. embeddings: List[List[float]],
  79. documents: List[str],
  80. metadatas: List[object],
  81. ids: List[str],
  82. skip_embedding: bool,
  83. ):
  84. """add data in vector database
  85. :param documents: list of texts to add
  86. :type documents: List[str]
  87. :param metadatas: list of metadata associated with docs
  88. :type metadatas: List[object]
  89. :param ids: ids of docs
  90. :type ids: List[str]
  91. """
  92. docs = []
  93. print("Adding documents to Pinecone...")
  94. embeddings = self.embedder.embedding_fn(documents)
  95. for id, text, metadata, embedding in zip(ids, documents, metadatas, embeddings):
  96. docs.append(
  97. {
  98. "id": id,
  99. "values": embedding,
  100. "metadata": {**metadata, "text": text},
  101. }
  102. )
  103. for i in range(0, len(docs), self.BATCH_SIZE):
  104. self.client.upsert(docs[i : i + self.BATCH_SIZE])
  105. def query(
  106. self,
  107. input_query: List[str],
  108. n_results: int,
  109. where: Dict[str, any],
  110. skip_embedding: bool,
  111. citations: bool = False,
  112. ) -> Union[List[Tuple[str, str, str]], List[str]]:
  113. """
  114. query contents from vector database based on vector similarity
  115. :param input_query: list of query string
  116. :type input_query: List[str]
  117. :param n_results: no of similar documents to fetch from database
  118. :type n_results: int
  119. :param where: Optional. to filter data
  120. :type where: Dict[str, any]
  121. :param skip_embedding: Optional. if True, input_query is already embedded
  122. :type skip_embedding: bool
  123. :param citations: we use citations boolean param to return context along with the answer.
  124. :type citations: bool, default is False.
  125. :return: The content of the document that matched your query,
  126. along with url of the source and doc_id (if citations flag is true)
  127. :rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
  128. """
  129. if not skip_embedding:
  130. query_vector = self.embedder.embedding_fn([input_query])[0]
  131. else:
  132. query_vector = input_query
  133. data = self.client.query(vector=query_vector, filter=where, top_k=n_results, include_metadata=True)
  134. contexts = []
  135. for doc in data["matches"]:
  136. metadata = doc["metadata"]
  137. context = metadata["text"]
  138. if citations:
  139. source = metadata["url"]
  140. doc_id = metadata["doc_id"]
  141. contexts.append(tuple((context, source, doc_id)))
  142. else:
  143. contexts.append(context)
  144. return contexts
  145. def set_collection_name(self, name: str):
  146. """
  147. Set the name of the collection. A collection is an isolated space for vectors.
  148. :param name: Name of the collection.
  149. :type name: str
  150. """
  151. if not isinstance(name, str):
  152. raise TypeError("Collection name must be a string")
  153. self.config.collection_name = name
  154. def count(self) -> int:
  155. """
  156. Count number of documents/chunks embedded in the database.
  157. :return: number of documents
  158. :rtype: int
  159. """
  160. return self.client.describe_index_stats()["total_vector_count"]
  161. def _get_or_create_db(self):
  162. """Called during initialization"""
  163. return self.client
  164. def reset(self):
  165. """
  166. Resets the database. Deletes all embeddings irreversibly.
  167. """
  168. # Delete all data from the database
  169. pinecone.delete_index(self.index_name)
  170. self._setup_pinecone_index()
  171. # Pinecone only allows alphanumeric characters and "-" in the index name
  172. def _get_index_name(self) -> str:
  173. """Get the Pinecone index for a collection
  174. :return: Pinecone index
  175. :rtype: str
  176. """
  177. return f"{self.config.collection_name}-{self.config.vector_dimension}".lower().replace("_", "-")