ernie_bot_retriever.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from .base import BaseRetriever
  15. import os
  16. from langchain.docstore.document import Document
  17. from langchain.text_splitter import RecursiveCharacterTextSplitter
  18. from langchain_community.embeddings import QianfanEmbeddingsEndpoint
  19. from langchain_community.vectorstores import FAISS
  20. from langchain_community import vectorstores
  21. from erniebot_agent.extensions.langchain.embeddings import ErnieEmbeddings
  22. import time
  23. from typing import Dict
  24. class ErnieBotRetriever(BaseRetriever):
  25. """Ernie Bot Retriever"""
  26. entities = [
  27. "ernie-4.0",
  28. "ernie-3.5",
  29. "ernie-3.5-8k",
  30. "ernie-lite",
  31. "ernie-tiny-8k",
  32. "ernie-speed",
  33. "ernie-speed-128k",
  34. "ernie-char-8k",
  35. ]
  36. def __init__(self, config: Dict) -> None:
  37. """
  38. Initializes the ErnieBotRetriever instance with the provided configuration.
  39. Args:
  40. config (Dict): A dictionary containing configuration settings.
  41. - model_name (str): The name of the model to use.
  42. - api_type (str): The type of API to use ('aistudio' or 'qianfan').
  43. - ak (str, optional): The access key for 'qianfan' API.
  44. - sk (str, optional): The secret key for 'qianfan' API.
  45. - access_token (str, optional): The access token for 'aistudio' API.
  46. Raises:
  47. ValueError: If model_name is not in self.entities,
  48. api_type is not 'aistudio' or 'qianfan',
  49. access_token is missing for 'aistudio' API,
  50. or ak and sk are missing for 'qianfan' API.
  51. """
  52. super().__init__()
  53. model_name = config.get("model_name", None)
  54. api_type = config.get("api_type", None)
  55. ak = config.get("ak", None)
  56. sk = config.get("sk", None)
  57. access_token = config.get("access_token", None)
  58. if model_name not in self.entities:
  59. raise ValueError(f"model_name must be in {self.entities} of ErnieBotChat.")
  60. if api_type not in ["aistudio", "qianfan"]:
  61. raise ValueError("api_type must be one of ['aistudio', 'qianfan']")
  62. if api_type == "aistudio" and access_token is None:
  63. raise ValueError("access_token cannot be empty when api_type is aistudio.")
  64. if api_type == "qianfan" and (ak is None or sk is None):
  65. raise ValueError("ak and sk cannot be empty when api_type is qianfan.")
  66. self.model_name = model_name
  67. self.config = config
  68. # Generates a vector database from a list of texts using different embeddings based on the configured API type.
  69. def generate_vector_database(
  70. self,
  71. text_list: list[str],
  72. block_size: int = 300,
  73. separators: list[str] = ["\t", "\n", "。", "\n\n", ""],
  74. sleep_time: float = 0.5,
  75. ) -> FAISS:
  76. """
  77. Generates a vector database from a list of texts.
  78. Args:
  79. text_list (list[str]): A list of texts to generate the vector database from.
  80. block_size (int): The size of each chunk to split the text into.
  81. separators (list[str]): A list of separators to use when splitting the text.
  82. sleep_time (float): The time to sleep between embedding generations to avoid rate limiting.
  83. Returns:
  84. FAISS: The generated vector database.
  85. Raises:
  86. ValueError: If an unsupported API type is configured.
  87. """
  88. text_splitter = RecursiveCharacterTextSplitter(
  89. chunk_size=block_size, chunk_overlap=20, separators=separators
  90. )
  91. texts = text_splitter.split_text("\t".join(text_list))
  92. all_splits = [Document(page_content=text) for text in texts]
  93. api_type = self.config["api_type"]
  94. if api_type == "qianfan":
  95. os.environ["QIANFAN_AK"] = os.environ.get("EB_AK", self.config["ak"])
  96. os.environ["QIANFAN_SK"] = os.environ.get("EB_SK", self.config["sk"])
  97. user_ak = os.environ.get("EB_AK", self.config["ak"])
  98. user_id = hash(user_ak)
  99. vectorstore = FAISS.from_documents(
  100. documents=all_splits, embedding=QianfanEmbeddingsEndpoint()
  101. )
  102. elif api_type == "aistudio":
  103. token = self.config["access_token"]
  104. vectorstore = FAISS.from_documents(
  105. documents=all_splits[0:1],
  106. embedding=ErnieEmbeddings(aistudio_access_token=token),
  107. )
  108. #### ErnieEmbeddings.chunk_size = 16
  109. step = min(16, len(all_splits) - 1)
  110. for shot_splits in [
  111. all_splits[i : i + step] for i in range(1, len(all_splits), step)
  112. ]:
  113. time.sleep(sleep_time)
  114. vectorstore_slice = FAISS.from_documents(
  115. documents=shot_splits,
  116. embedding=ErnieEmbeddings(aistudio_access_token=token),
  117. )
  118. vectorstore.merge_from(vectorstore_slice)
  119. else:
  120. raise ValueError(f"Unsupported api_type: {api_type}")
  121. return vectorstore
  122. def encode_vector_store_to_bytes(self, vectorstore: FAISS) -> str:
  123. """
  124. Encode the vector store serialized to bytes.
  125. Args:
  126. vectorstore (FAISS): The vector store to be serialized and encoded.
  127. Returns:
  128. str: The encoded vector store.
  129. """
  130. vectorstore = self.encode_vector_store(vectorstore.serialize_to_bytes())
  131. return vectorstore
  132. def decode_vector_store_from_bytes(self, vectorstore: str) -> FAISS:
  133. """
  134. Decode a vector store from bytes according to the specified API type.
  135. Args:
  136. vectorstore (str): The serialized vector store string.
  137. Returns:
  138. FAISS: Deserialized vector store object.
  139. Raises:
  140. ValueError: If the retrieved vector store is not for PaddleX
  141. or if an unsupported API type is specified.
  142. """
  143. if not self.is_vector_store(vectorstore):
  144. raise ValueError("The retrieved vectorstore is not for PaddleX.")
  145. api_type = self.config["api_type"]
  146. if api_type == "aistudio":
  147. access_token = self.config["access_token"]
  148. embeddings = ErnieEmbeddings(aistudio_access_token=access_token)
  149. elif api_type == "qianfan":
  150. ak = self.config["ak"]
  151. sk = self.config["sk"]
  152. embeddings = QianfanEmbeddingsEndpoint(qianfan_ak=ak, qianfan_sk=sk)
  153. else:
  154. raise ValueError(f"Unsupported api_type: {api_type}")
  155. vector = vectorstores.FAISS.deserialize_from_bytes(
  156. self.decode_vector_store(vectorstore), embeddings
  157. )
  158. return vector
  159. def similarity_retrieval(
  160. self, query_text_list: list[str], vectorstore: FAISS, sleep_time: float = 0.5
  161. ) -> str:
  162. """
  163. Retrieve similar contexts based on a list of query texts.
  164. Args:
  165. query_text_list (list[str]): A list of query texts to search for similar contexts.
  166. vectorstore (FAISS): The vector store where to perform the similarity search.
  167. sleep_time (float): The time to sleep between each query, in seconds. Default is 0.5.
  168. Returns:
  169. str: A concatenated string of all unique contexts found.
  170. """
  171. C = []
  172. for query_text in query_text_list:
  173. QUESTION = query_text
  174. time.sleep(sleep_time)
  175. docs = vectorstore.similarity_search_with_relevance_scores(QUESTION, k=2)
  176. context = [(document.page_content, score) for document, score in docs]
  177. context = sorted(context, key=lambda x: x[1])
  178. C.extend([x[0] for x in context[::-1]])
  179. C = list(set(C))
  180. all_C = " ".join(C)
  181. return all_C