embedchain.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. chunks_before_addition = self.count()
  100. # Add metadata to each document
  101. metadatas_with_metadata = [{**meta, **metadata} for meta in metadatas]
  102. self.collection.add(documents=documents, metadatas=list(metadatas_with_metadata), ids=ids)
  103. print((f"Successfully saved {src}. New chunks count: " f"{self.count() - chunks_before_addition}"))
  104. def _format_result(self, results):
  105. return [
  106. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  107. for result in zip(
  108. results["documents"][0],
  109. results["metadatas"][0],
  110. results["distances"][0],
  111. )
  112. ]
  113. def get_llm_model_answer(self):
  114. """
  115. Usually implemented by child class
  116. """
  117. raise NotImplementedError
  118. def retrieve_from_database(self, input_query, config: QueryConfig):
  119. """
  120. Queries the vector database based on the given input query.
  121. Gets relevant doc based on the query
  122. :param input_query: The query to use.
  123. :param config: The query configuration.
  124. :return: The content of the document that matched your query.
  125. """
  126. try:
  127. where = {"app_id": self.config.id} if self.config.id is not None else {} # optional filter
  128. result = self.collection.query(
  129. query_texts=[
  130. input_query,
  131. ],
  132. n_results=config.number_documents,
  133. where=where,
  134. )
  135. except InvalidDimensionException as e:
  136. raise InvalidDimensionException(
  137. e.message()
  138. + ". 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
  139. ) from None
  140. results_formatted = self._format_result(result)
  141. contents = [result[0].page_content for result in results_formatted]
  142. return contents
  143. def _append_search_and_context(self, context, web_search_result):
  144. return f"{context}\nWeb Search Result: {web_search_result}"
  145. def generate_prompt(self, input_query, contexts, config: QueryConfig, **kwargs):
  146. """
  147. Generates a prompt based on the given query and context, ready to be
  148. passed to an LLM
  149. :param input_query: The query to use.
  150. :param contexts: List of similar documents to the query used as context.
  151. :param config: Optional. The `QueryConfig` instance to use as
  152. configuration options.
  153. :return: The prompt
  154. """
  155. context_string = (" | ").join(contexts)
  156. web_search_result = kwargs.get("web_search_result", "")
  157. if web_search_result:
  158. context_string = self._append_search_and_context(context_string, web_search_result)
  159. if not config.history:
  160. prompt = config.template.substitute(context=context_string, query=input_query)
  161. else:
  162. prompt = config.template.substitute(context=context_string, query=input_query, history=config.history)
  163. return prompt
  164. def get_answer_from_llm(self, prompt, config: ChatConfig):
  165. """
  166. Gets an answer based on the given query and context by passing it
  167. to an LLM.
  168. :param query: The query to use.
  169. :param context: Similar documents to the query used as context.
  170. :return: The answer.
  171. """
  172. return self.get_llm_model_answer(prompt, config)
  173. def access_search_and_get_results(self, input_query):
  174. from langchain.tools import DuckDuckGoSearchRun
  175. search = DuckDuckGoSearchRun()
  176. logging.info(f"Access search to get answers for {input_query}")
  177. return search.run(input_query)
  178. def query(self, input_query, config: QueryConfig = None, dry_run=False):
  179. """
  180. Queries the vector database based on the given input query.
  181. Gets relevant doc based on the query and then passes it to an
  182. LLM as context to get the answer.
  183. :param input_query: The query to use.
  184. :param config: Optional. The `QueryConfig` instance to use as
  185. configuration options.
  186. :param dry_run: Optional. A dry run does everything except send the resulting prompt to
  187. the LLM. The purpose is to test the prompt, not the response.
  188. You can use it to test your prompt, including the context provided
  189. by the vector database's doc retrieval.
  190. The only thing the dry run does not consider is the cut-off due to
  191. the `max_tokens` parameter.
  192. :return: The answer to the query.
  193. """
  194. if config is None:
  195. config = QueryConfig()
  196. if self.is_docs_site_instance:
  197. config.template = DOCS_SITE_PROMPT_TEMPLATE
  198. config.number_documents = 5
  199. k = {}
  200. if self.online:
  201. k["web_search_result"] = self.access_search_and_get_results(input_query)
  202. contexts = self.retrieve_from_database(input_query, config)
  203. prompt = self.generate_prompt(input_query, contexts, config, **k)
  204. logging.info(f"Prompt: {prompt}")
  205. if dry_run:
  206. return prompt
  207. answer = self.get_answer_from_llm(prompt, config)
  208. if isinstance(answer, str):
  209. logging.info(f"Answer: {answer}")
  210. return answer
  211. else:
  212. return self._stream_query_response(answer)
  213. def _stream_query_response(self, answer):
  214. streamed_answer = ""
  215. for chunk in answer:
  216. streamed_answer = streamed_answer + chunk
  217. yield chunk
  218. logging.info(f"Answer: {streamed_answer}")
  219. def chat(self, input_query, config: ChatConfig = None, dry_run=False):
  220. """
  221. Queries the vector database on the given input query.
  222. Gets relevant doc based on the query and then passes it to an
  223. LLM as context to get the answer.
  224. Maintains the whole conversation in memory.
  225. :param input_query: The query to use.
  226. :param config: Optional. The `ChatConfig` instance to use as
  227. configuration options.
  228. :param dry_run: Optional. A dry run does everything except send the resulting prompt to
  229. the LLM. The purpose is to test the prompt, not the response.
  230. You can use it to test your prompt, including the context provided
  231. by the vector database's doc retrieval.
  232. The only thing the dry run does not consider is the cut-off due to
  233. the `max_tokens` parameter.
  234. :return: The answer to the query.
  235. """
  236. if config is None:
  237. config = ChatConfig()
  238. if self.is_docs_site_instance:
  239. config.template = DOCS_SITE_PROMPT_TEMPLATE
  240. config.number_documents = 5
  241. k = {}
  242. if self.online:
  243. k["web_search_result"] = self.access_search_and_get_results(input_query)
  244. contexts = self.retrieve_from_database(input_query, config, **k)
  245. global memory
  246. chat_history = memory.load_memory_variables({})["history"]
  247. if chat_history:
  248. config.set_history(chat_history)
  249. prompt = self.generate_prompt(input_query, contexts, config, **k)
  250. logging.info(f"Prompt: {prompt}")
  251. if dry_run:
  252. return prompt
  253. answer = self.get_answer_from_llm(prompt, config)
  254. memory.chat_memory.add_user_message(input_query)
  255. if isinstance(answer, str):
  256. memory.chat_memory.add_ai_message(answer)
  257. logging.info(f"Answer: {answer}")
  258. return answer
  259. else:
  260. # this is a streamed response and needs to be handled differently.
  261. return self._stream_chat_response(answer)
  262. def _stream_chat_response(self, answer):
  263. streamed_answer = ""
  264. for chunk in answer:
  265. streamed_answer = streamed_answer + chunk
  266. yield chunk
  267. memory.chat_memory.add_ai_message(streamed_answer)
  268. logging.info(f"Answer: {streamed_answer}")
  269. def count(self):
  270. """
  271. Count the number of embeddings.
  272. :return: The number of embeddings.
  273. """
  274. return self.collection.count()
  275. def reset(self):
  276. """
  277. Resets the database. Deletes all embeddings irreversibly.
  278. `App` has to be reinitialized after using this method.
  279. """
  280. self.db_client.reset()