embedchain.py 13 KB

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