pinecone.py 7.1 KB

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