embedchain.py 15 KB

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