pinecone.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import os
  2. from typing import Optional, 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.misc 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. documents: list[str],
  80. metadatas: list[object],
  81. ids: list[str],
  82. **kwargs: Optional[dict[str, any]],
  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 chunk in chunks(docs, self.BATCH_SIZE, desc="Adding chunks in batches..."):
  104. self.client.upsert(chunk, **kwargs)
  105. def query(
  106. self,
  107. input_query: list[str],
  108. n_results: int,
  109. where: dict[str, any],
  110. citations: bool = False,
  111. **kwargs: Optional[dict[str, any]],
  112. ) -> Union[list[tuple[str, dict]], 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 citations: we use citations boolean param to return context along with the answer.
  122. :type citations: bool, default is False.
  123. :return: The content of the document that matched your query,
  124. along with url of the source and doc_id (if citations flag is true)
  125. :rtype: list[str], if citations=False, otherwise list[tuple[str, str, str]]
  126. """
  127. query_vector = self.embedder.embedding_fn([input_query])[0]
  128. data = self.client.query(vector=query_vector, filter=where, top_k=n_results, include_metadata=True, **kwargs)
  129. contexts = []
  130. for doc in data["matches"]:
  131. metadata = doc["metadata"]
  132. context = metadata["text"]
  133. if citations:
  134. metadata["score"] = doc["score"]
  135. contexts.append(tuple((context, metadata)))
  136. else:
  137. contexts.append(context)
  138. return contexts
  139. def set_collection_name(self, name: str):
  140. """
  141. Set the name of the collection. A collection is an isolated space for vectors.
  142. :param name: Name of the collection.
  143. :type name: str
  144. """
  145. if not isinstance(name, str):
  146. raise TypeError("Collection name must be a string")
  147. self.config.collection_name = name
  148. def count(self) -> int:
  149. """
  150. Count number of documents/chunks embedded in the database.
  151. :return: number of documents
  152. :rtype: int
  153. """
  154. return self.client.describe_index_stats()["total_vector_count"]
  155. def _get_or_create_db(self):
  156. """Called during initialization"""
  157. return self.client
  158. def reset(self):
  159. """
  160. Resets the database. Deletes all embeddings irreversibly.
  161. """
  162. # Delete all data from the database
  163. pinecone.delete_index(self.index_name)
  164. self._setup_pinecone_index()
  165. # Pinecone only allows alphanumeric characters and "-" in the index name
  166. def _get_index_name(self) -> str:
  167. """Get the Pinecone index for a collection
  168. :return: Pinecone index
  169. :rtype: str
  170. """
  171. return f"{self.config.collection_name}-{self.config.vector_dimension}".lower().replace("_", "-")