embedchain.py 19 KB

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