embedchain.py 18 KB

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