embedchain.py 15 KB

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