embedchain.py 13 KB

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