embedchain.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import logging
  2. import os
  3. from chromadb.errors import InvalidDimensionException
  4. from dotenv import load_dotenv
  5. from langchain.docstore.document import Document
  6. from langchain.memory import ConversationBufferMemory
  7. from embedchain.chunkers.base_chunker import BaseChunker
  8. from embedchain.config import AddConfig, ChatConfig, QueryConfig
  9. from embedchain.config.apps.BaseAppConfig import BaseAppConfig
  10. from embedchain.config.QueryConfig import DOCS_SITE_PROMPT_TEMPLATE
  11. from embedchain.data_formatter import DataFormatter
  12. from embedchain.loaders.base_loader import BaseLoader
  13. load_dotenv()
  14. ABS_PATH = os.getcwd()
  15. DB_DIR = os.path.join(ABS_PATH, "db")
  16. memory = ConversationBufferMemory()
  17. class EmbedChain:
  18. def __init__(self, config: BaseAppConfig):
  19. """
  20. Initializes the EmbedChain instance, sets up a vector DB client and
  21. creates a collection.
  22. :param config: BaseAppConfig instance to load as configuration.
  23. """
  24. self.config = config
  25. self.db_client = self.config.db.client
  26. self.collection = self.config.db.collection
  27. self.user_asks = []
  28. self.is_docs_site_instance = False
  29. self.online = False
  30. def add(self, data_type, url, metadata=None, config: AddConfig = None):
  31. """
  32. Adds the data from the given URL to the vector db.
  33. Loads the data, chunks it, create embedding for each chunk
  34. and then stores the embedding to vector database.
  35. :param data_type: The type of the data to add.
  36. :param url: The URL where the data is located.
  37. :param metadata: Optional. Metadata associated with the data source.
  38. :param config: Optional. The `AddConfig` instance to use as configuration
  39. options.
  40. """
  41. if config is None:
  42. config = AddConfig()
  43. data_formatter = DataFormatter(data_type, config)
  44. self.user_asks.append([data_type, url, metadata])
  45. self.load_and_embed(data_formatter.loader, data_formatter.chunker, url, metadata)
  46. if data_type in ("docs_site",):
  47. self.is_docs_site_instance = True
  48. def add_local(self, data_type, content, metadata=None, config: AddConfig = None):
  49. """
  50. Adds the data you supply to the vector db.
  51. Loads the data, chunks it, create embedding for each chunk
  52. and then stores the embedding to vector database.
  53. :param data_type: The type of the data to add.
  54. :param content: The local data. Refer to the `README` for formatting.
  55. :param metadata: Optional. Metadata associated with the data source.
  56. :param config: Optional. The `AddConfig` instance to use as
  57. configuration options.
  58. """
  59. if config is None:
  60. config = AddConfig()
  61. data_formatter = DataFormatter(data_type, config)
  62. self.user_asks.append([data_type, content])
  63. self.load_and_embed(
  64. data_formatter.loader,
  65. data_formatter.chunker,
  66. content,
  67. metadata,
  68. )
  69. def load_and_embed(self, loader: BaseLoader, chunker: BaseChunker, src, metadata=None):
  70. """
  71. Loads the data from the given URL, chunks it, and adds it to database.
  72. :param loader: The loader to use to load the data.
  73. :param chunker: The chunker to use to chunk the data.
  74. :param src: The data to be handled by the loader. Can be a URL for
  75. remote sources or local content for local loaders.
  76. :param metadata: Optional. Metadata associated with the data source.
  77. """
  78. embeddings_data = chunker.create_chunks(loader, src)
  79. documents = embeddings_data["documents"]
  80. metadatas = embeddings_data["metadatas"]
  81. ids = embeddings_data["ids"]
  82. # get existing ids, and discard doc if any common id exist.
  83. where = {"app_id": self.config.id} if self.config.id is not None else {}
  84. # where={"url": src}
  85. existing_docs = self.collection.get(
  86. ids=ids,
  87. where=where, # optional filter
  88. )
  89. existing_ids = set(existing_docs["ids"])
  90. if len(existing_ids):
  91. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  92. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  93. if not data_dict:
  94. print(f"All data from {src} already exists in the database.")
  95. return
  96. ids = list(data_dict.keys())
  97. documents, metadatas = zip(*data_dict.values())
  98. # Add app id in metadatas so that they can be queried on later
  99. if self.config.id is not None:
  100. metadatas = [{**m, "app_id": self.config.id} for m in metadatas]
  101. # FIXME: Fix the error handling logic when metadatas or metadata is None
  102. metadatas = metadatas if metadatas else []
  103. metadata = metadata if metadata else {}
  104. chunks_before_addition = self.count()
  105. # Add metadata to each document
  106. metadatas_with_metadata = [{**meta, **metadata} for meta in metadatas]
  107. self.collection.add(documents=documents, metadatas=list(metadatas_with_metadata), ids=ids)
  108. print((f"Successfully saved {src}. New chunks count: " f"{self.count() - chunks_before_addition}"))
  109. def _format_result(self, results):
  110. return [
  111. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  112. for result in zip(
  113. results["documents"][0],
  114. results["metadatas"][0],
  115. results["distances"][0],
  116. )
  117. ]
  118. def get_llm_model_answer(self):
  119. """
  120. Usually implemented by child class
  121. """
  122. raise NotImplementedError
  123. def retrieve_from_database(self, input_query, config: QueryConfig):
  124. """
  125. Queries the vector database based on the given input query.
  126. Gets relevant doc based on the query
  127. :param input_query: The query to use.
  128. :param config: The query configuration.
  129. :return: The content of the document that matched your query.
  130. """
  131. try:
  132. where = {"app_id": self.config.id} if self.config.id is not None else {} # optional filter
  133. result = self.collection.query(
  134. query_texts=[
  135. input_query,
  136. ],
  137. n_results=config.number_documents,
  138. where=where,
  139. )
  140. except InvalidDimensionException as e:
  141. raise InvalidDimensionException(
  142. e.message()
  143. + ". This is commonly a side-effect when an embedding function, different from the one used to add the embeddings, is used to retrieve an embedding from the database." # noqa E501
  144. ) from None
  145. results_formatted = self._format_result(result)
  146. contents = [result[0].page_content for result in results_formatted]
  147. return contents
  148. def _append_search_and_context(self, context, web_search_result):
  149. return f"{context}\nWeb Search Result: {web_search_result}"
  150. def generate_prompt(self, input_query, contexts, config: QueryConfig, **kwargs):
  151. """
  152. Generates a prompt based on the given query and context, ready to be
  153. passed to an LLM
  154. :param input_query: The query to use.
  155. :param contexts: List of similar documents to the query used as context.
  156. :param config: Optional. The `QueryConfig` instance to use as
  157. configuration options.
  158. :return: The prompt
  159. """
  160. context_string = (" | ").join(contexts)
  161. web_search_result = kwargs.get("web_search_result", "")
  162. if web_search_result:
  163. context_string = self._append_search_and_context(context_string, web_search_result)
  164. if not config.history:
  165. prompt = config.template.substitute(context=context_string, query=input_query)
  166. else:
  167. prompt = config.template.substitute(context=context_string, query=input_query, history=config.history)
  168. return prompt
  169. def get_answer_from_llm(self, prompt, config: ChatConfig):
  170. """
  171. Gets an answer based on the given query and context by passing it
  172. to an LLM.
  173. :param query: The query to use.
  174. :param context: Similar documents to the query used as context.
  175. :return: The answer.
  176. """
  177. return self.get_llm_model_answer(prompt, config)
  178. def access_search_and_get_results(self, input_query):
  179. from langchain.tools import DuckDuckGoSearchRun
  180. search = DuckDuckGoSearchRun()
  181. logging.info(f"Access search to get answers for {input_query}")
  182. return search.run(input_query)
  183. def query(self, input_query, config: QueryConfig = None, dry_run=False):
  184. """
  185. Queries the vector database based on the given input query.
  186. Gets relevant doc based on the query and then passes it to an
  187. LLM as context to get the answer.
  188. :param input_query: The query to use.
  189. :param config: Optional. The `QueryConfig` instance to use as
  190. configuration options.
  191. :param dry_run: Optional. A dry run does everything except send the resulting prompt to
  192. the LLM. The purpose is to test the prompt, not the response.
  193. You can use it to test your prompt, including the context provided
  194. by the vector database's doc retrieval.
  195. The only thing the dry run does not consider is the cut-off due to
  196. the `max_tokens` parameter.
  197. :return: The answer to the query.
  198. """
  199. if config is None:
  200. config = QueryConfig()
  201. if self.is_docs_site_instance:
  202. config.template = DOCS_SITE_PROMPT_TEMPLATE
  203. config.number_documents = 5
  204. k = {}
  205. if self.online:
  206. k["web_search_result"] = self.access_search_and_get_results(input_query)
  207. contexts = self.retrieve_from_database(input_query, config)
  208. prompt = self.generate_prompt(input_query, contexts, config, **k)
  209. logging.info(f"Prompt: {prompt}")
  210. if dry_run:
  211. return prompt
  212. answer = self.get_answer_from_llm(prompt, config)
  213. if isinstance(answer, str):
  214. logging.info(f"Answer: {answer}")
  215. return answer
  216. else:
  217. return self._stream_query_response(answer)
  218. def _stream_query_response(self, answer):
  219. streamed_answer = ""
  220. for chunk in answer:
  221. streamed_answer = streamed_answer + chunk
  222. yield chunk
  223. logging.info(f"Answer: {streamed_answer}")
  224. def chat(self, input_query, config: ChatConfig = None, dry_run=False):
  225. """
  226. Queries the vector database on the given input query.
  227. Gets relevant doc based on the query and then passes it to an
  228. LLM as context to get the answer.
  229. Maintains the whole conversation in memory.
  230. :param input_query: The query to use.
  231. :param config: Optional. The `ChatConfig` instance to use as
  232. configuration options.
  233. :param dry_run: Optional. A dry run does everything except send the resulting prompt to
  234. the LLM. The purpose is to test the prompt, not the response.
  235. You can use it to test your prompt, including the context provided
  236. by the vector database's doc retrieval.
  237. The only thing the dry run does not consider is the cut-off due to
  238. the `max_tokens` parameter.
  239. :return: The answer to the query.
  240. """
  241. if config is None:
  242. config = ChatConfig()
  243. if self.is_docs_site_instance:
  244. config.template = DOCS_SITE_PROMPT_TEMPLATE
  245. config.number_documents = 5
  246. k = {}
  247. if self.online:
  248. k["web_search_result"] = self.access_search_and_get_results(input_query)
  249. contexts = self.retrieve_from_database(input_query, config)
  250. global memory
  251. chat_history = memory.load_memory_variables({})["history"]
  252. if chat_history:
  253. config.set_history(chat_history)
  254. prompt = self.generate_prompt(input_query, contexts, config, **k)
  255. logging.info(f"Prompt: {prompt}")
  256. if dry_run:
  257. return prompt
  258. answer = self.get_answer_from_llm(prompt, config)
  259. memory.chat_memory.add_user_message(input_query)
  260. if isinstance(answer, str):
  261. memory.chat_memory.add_ai_message(answer)
  262. logging.info(f"Answer: {answer}")
  263. return answer
  264. else:
  265. # this is a streamed response and needs to be handled differently.
  266. return self._stream_chat_response(answer)
  267. def _stream_chat_response(self, answer):
  268. streamed_answer = ""
  269. for chunk in answer:
  270. streamed_answer = streamed_answer + chunk
  271. yield chunk
  272. memory.chat_memory.add_ai_message(streamed_answer)
  273. logging.info(f"Answer: {streamed_answer}")
  274. def count(self):
  275. """
  276. Count the number of embeddings.
  277. :return: The number of embeddings.
  278. """
  279. return self.collection.count()
  280. def reset(self):
  281. """
  282. Resets the database. Deletes all embeddings irreversibly.
  283. `App` has to be reinitialized after using this method.
  284. """
  285. self.db_client.reset()