embedchain.py 19 KB

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