embedchain.py 19 KB

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