embedchain.py 16 KB

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