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 Any, Dict, List, Optional, Tuple
  10. import requests
  11. from dotenv import load_dotenv
  12. from tenacity import retry, stop_after_attempt, wait_fixed
  13. from embedchain.chunkers.base_chunker import BaseChunker
  14. from embedchain.config import AddConfig, BaseLlmConfig
  15. from embedchain.config.apps.BaseAppConfig import BaseAppConfig
  16. from embedchain.data_formatter import DataFormatter
  17. from embedchain.embedder.base import BaseEmbedder
  18. from embedchain.helper.json_serializable import JSONSerializable
  19. from embedchain.llm.base import BaseLlm
  20. from embedchain.loaders.base_loader import BaseLoader
  21. from embedchain.models.data_type import DataType
  22. from embedchain.utils import detect_datatype
  23. from embedchain.vectordb.base import BaseVectorDB
  24. load_dotenv()
  25. ABS_PATH = os.getcwd()
  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(JSONSerializable):
  30. def __init__(
  31. self,
  32. config: BaseAppConfig,
  33. llm: BaseLlm,
  34. db: BaseVectorDB = None,
  35. embedder: BaseEmbedder = None,
  36. system_prompt: Optional[str] = None,
  37. ):
  38. """
  39. Initializes the EmbedChain instance, sets up a vector DB client and
  40. creates a collection.
  41. :param config: Configuration just for the app, not the db or llm or embedder.
  42. :type config: BaseAppConfig
  43. :param llm: Instance of the LLM you want to use.
  44. :type llm: BaseLlm
  45. :param db: Instance of the Database to use, defaults to None
  46. :type db: BaseVectorDB, optional
  47. :param embedder: instance of the embedder to use, defaults to None
  48. :type embedder: BaseEmbedder, optional
  49. :param system_prompt: System prompt to use in the llm query, defaults to None
  50. :type system_prompt: Optional[str], optional
  51. :raises ValueError: No database or embedder provided.
  52. """
  53. self.config = config
  54. # Add subclasses
  55. ## Llm
  56. self.llm = llm
  57. ## Database
  58. # Database has support for config assignment for backwards compatibility
  59. if db is None and (not hasattr(self.config, "db") or self.config.db is None):
  60. raise ValueError("App requires Database.")
  61. self.db = db or self.config.db
  62. ## Embedder
  63. if embedder is None:
  64. raise ValueError("App requires Embedder.")
  65. self.embedder = embedder
  66. # Initialize database
  67. self.db._set_embedder(self.embedder)
  68. self.db._initialize()
  69. # Set collection name from app config for backwards compatibility.
  70. if config.collection_name:
  71. self.db.set_collection_name(config.collection_name)
  72. # Add variables that are "shortcuts"
  73. if system_prompt:
  74. self.llm.config.system_prompt = system_prompt
  75. # Attributes that aren't subclass related.
  76. self.user_asks = []
  77. # Send anonymous telemetry
  78. self.s_id = self.config.id if self.config.id else str(uuid.uuid4())
  79. self.u_id = self._load_or_generate_user_id()
  80. # NOTE: Uncomment the next two lines when running tests to see if any test fires a telemetry event.
  81. # if (self.config.collect_metrics):
  82. # raise ConnectionRefusedError("Collection of metrics should not be allowed.")
  83. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("init",))
  84. thread_telemetry.start()
  85. def _load_or_generate_user_id(self) -> str:
  86. """
  87. Loads the user id from the config file if it exists, otherwise generates a new
  88. one and saves it to the config file.
  89. :return: user id
  90. :rtype: str
  91. """
  92. if not os.path.exists(CONFIG_DIR):
  93. os.makedirs(CONFIG_DIR)
  94. if os.path.exists(CONFIG_FILE):
  95. with open(CONFIG_FILE, "r") as f:
  96. data = json.load(f)
  97. if "user_id" in data:
  98. return data["user_id"]
  99. u_id = str(uuid.uuid4())
  100. with open(CONFIG_FILE, "w") as f:
  101. json.dump({"user_id": u_id}, f)
  102. return u_id
  103. def add(
  104. self,
  105. source: Any,
  106. data_type: Optional[DataType] = None,
  107. metadata: Optional[Dict[str, Any]] = None,
  108. config: Optional[AddConfig] = None,
  109. dry_run=False,
  110. ):
  111. """
  112. Adds the data from the given URL to the vector db.
  113. Loads the data, chunks it, create embedding for each chunk
  114. and then stores the embedding to vector database.
  115. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  116. :type source: Any
  117. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  118. defaults to None
  119. :type data_type: Optional[DataType], optional
  120. :param metadata: Metadata associated with the data source., defaults to None
  121. :type metadata: Optional[Dict[str, Any]], optional
  122. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  123. :type config: Optional[AddConfig], optional
  124. :raises ValueError: Invalid data type
  125. :param dry_run: Optional. A dry run displays the chunks to ensure that the loader and chunker work as intended.
  126. deafaults to False
  127. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  128. :rtype: str
  129. """
  130. if config is None:
  131. config = AddConfig()
  132. try:
  133. DataType(source)
  134. logging.warning(
  135. 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
  136. )
  137. logging.warning(
  138. "Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
  139. )
  140. source, data_type = data_type, source
  141. except ValueError:
  142. pass
  143. if data_type:
  144. try:
  145. data_type = DataType(data_type)
  146. except ValueError:
  147. raise ValueError(
  148. f"Invalid data_type: '{data_type}'.",
  149. f"Please use one of the following: {[data_type.value for data_type in DataType]}",
  150. ) from None
  151. if not data_type:
  152. data_type = detect_datatype(source)
  153. # `source_id` is the hash of the source argument
  154. hash_object = hashlib.md5(str(source).encode("utf-8"))
  155. source_id = hash_object.hexdigest()
  156. data_formatter = DataFormatter(data_type, config)
  157. self.user_asks.append([source, data_type.value, metadata])
  158. documents, metadatas, _ids, new_chunks = self.load_and_embed(
  159. data_formatter.loader, data_formatter.chunker, source, metadata, source_id, dry_run
  160. )
  161. if data_type in {DataType.DOCS_SITE}:
  162. self.is_docs_site_instance = True
  163. if dry_run:
  164. data_chunks_info = {"chunks": documents, "metadata": metadatas, "count": len(documents), "type": data_type}
  165. logging.debug(f"Dry run info : {data_chunks_info}")
  166. return data_chunks_info
  167. # Send anonymous telemetry
  168. if self.config.collect_metrics:
  169. # it's quicker to check the variable twice than to count words when they won't be submitted.
  170. word_count = sum([len(document.split(" ")) for document in documents])
  171. extra_metadata = {"data_type": data_type.value, "word_count": word_count, "chunks_count": new_chunks}
  172. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("add", extra_metadata))
  173. thread_telemetry.start()
  174. return source_id
  175. def add_local(
  176. self,
  177. source: Any,
  178. data_type: Optional[DataType] = None,
  179. metadata: Optional[Dict[str, Any]] = None,
  180. config: Optional[AddConfig] = None,
  181. ):
  182. """
  183. Adds the data from the given URL to the vector db.
  184. Loads the data, chunks it, create embedding for each chunk
  185. and then stores the embedding to vector database.
  186. Warning:
  187. This method is deprecated and will be removed in future versions. Use `add` instead.
  188. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  189. :type source: Any
  190. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  191. defaults to None
  192. :type data_type: Optional[DataType], optional
  193. :param metadata: Metadata associated with the data source., defaults to None
  194. :type metadata: Optional[Dict[str, Any]], optional
  195. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  196. :type config: Optional[AddConfig], optional
  197. :raises ValueError: Invalid data type
  198. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  199. :rtype: str
  200. """
  201. logging.warning(
  202. "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
  203. )
  204. return self.add(source=source, data_type=data_type, metadata=metadata, config=config)
  205. def load_and_embed(
  206. self,
  207. loader: BaseLoader,
  208. chunker: BaseChunker,
  209. src: Any,
  210. metadata: Optional[Dict[str, Any]] = None,
  211. source_id: Optional[str] = None,
  212. dry_run = False
  213. ) -> Tuple[List[str], Dict[str, Any], List[str], int]:
  214. """The loader to use to load the data.
  215. :param loader: The loader to use to load the data.
  216. :type loader: BaseLoader
  217. :param chunker: The chunker to use to chunk the data.
  218. :type chunker: BaseChunker
  219. :param src: The data to be handled by the loader.
  220. Can be a URL for remote sources or local content for local loaders.
  221. :type src: Any
  222. :param metadata: Metadata associated with the data source., defaults to None
  223. :type metadata: Dict[str, Any], optional
  224. :param source_id: Hexadecimal hash of the source., defaults to None
  225. :type source_id: str, optional
  226. :param dry_run: Optional. A dry run returns chunks and doesn't update DB.
  227. :type dry_run: bool, defaults to False
  228. :return: (List) documents (embedded text), (List) metadata, (list) ids, (int) number of chunks
  229. :rtype: Tuple[List[str], Dict[str, Any], List[str], int]
  230. """
  231. embeddings_data = chunker.create_chunks(loader, src)
  232. # spread chunking results
  233. documents = embeddings_data["documents"]
  234. metadatas = embeddings_data["metadatas"]
  235. ids = embeddings_data["ids"]
  236. # get existing ids, and discard doc if any common id exist.
  237. where = {"app_id": self.config.id} if self.config.id is not None else {}
  238. # where={"url": src}
  239. existing_ids = self.db.get(
  240. ids=ids,
  241. where=where, # optional filter
  242. )
  243. if len(existing_ids):
  244. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  245. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  246. if not data_dict:
  247. print(f"All data from {src} already exists in the database.")
  248. # Make sure to return a matching return type
  249. return [], [], [], 0
  250. ids = list(data_dict.keys())
  251. documents, metadatas = zip(*data_dict.values())
  252. if dry_run:
  253. return list(documents), metadatas, ids, 0
  254. # Loop though all metadatas and add extras.
  255. new_metadatas = []
  256. for m in metadatas:
  257. # Add app id in metadatas so that they can be queried on later
  258. if self.config.id:
  259. m["app_id"] = self.config.id
  260. # Add hashed source
  261. m["hash"] = source_id
  262. # Note: Metadata is the function argument
  263. if metadata:
  264. # Spread whatever is in metadata into the new object.
  265. m.update(metadata)
  266. new_metadatas.append(m)
  267. metadatas = new_metadatas
  268. # Count before, to calculate a delta in the end.
  269. chunks_before_addition = self.db.count()
  270. self.db.add(documents=documents, metadatas=metadatas, ids=ids)
  271. count_new_chunks = self.db.count() - chunks_before_addition
  272. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  273. return list(documents), metadatas, ids, count_new_chunks
  274. def retrieve_from_database(self, input_query: str, config: Optional[BaseLlmConfig] = None, where=None) -> List[str]:
  275. """
  276. Queries the vector database based on the given input query.
  277. Gets relevant doc based on the query
  278. :param input_query: The query to use.
  279. :type input_query: str
  280. :param config: The query configuration, defaults to None
  281. :type config: Optional[BaseLlmConfig], optional
  282. :param where: A dictionary of key-value pairs to filter the database results, defaults to None
  283. :type where: _type_, optional
  284. :return: List of contents of the document that matched your query
  285. :rtype: List[str]
  286. """
  287. query_config = config or self.llm.config
  288. if where is not None:
  289. where = where
  290. elif query_config is not None and query_config.where is not None:
  291. where = query_config.where
  292. else:
  293. where = {}
  294. if self.config.id is not None:
  295. where.update({"app_id": self.config.id})
  296. contents = self.db.query(
  297. input_query=input_query,
  298. n_results=query_config.number_documents,
  299. where=where,
  300. )
  301. return contents
  302. def query(self, input_query: str, config: BaseLlmConfig = None, dry_run=False, where: Optional[Dict] = None) -> str:
  303. """
  304. Queries the vector database based on the given input query.
  305. Gets relevant doc based on the query and then passes it to an
  306. LLM as context to get the answer.
  307. :param input_query: The query to use.
  308. :type input_query: str
  309. :param config: The `LlmConfig` instance to use as configuration options. This is used for one method call.
  310. To persistently use a config, declare it during app init., defaults to None
  311. :type config: Optional[BaseLlmConfig], optional
  312. :param dry_run: A dry run does everything except send the resulting prompt to
  313. the LLM. The purpose is to test the prompt, not the response., defaults to False
  314. :type dry_run: bool, optional
  315. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  316. :type where: Optional[Dict[str, str]], optional
  317. :return: The answer to the query or the dry run result
  318. :rtype: str
  319. """
  320. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  321. answer = self.llm.query(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  322. # Send anonymous telemetry
  323. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("query",))
  324. thread_telemetry.start()
  325. return answer
  326. def chat(
  327. self,
  328. input_query: str,
  329. config: Optional[BaseLlmConfig] = None,
  330. dry_run=False,
  331. where: Optional[Dict[str, str]] = None,
  332. ) -> str:
  333. """
  334. Queries the vector database on the given input query.
  335. Gets relevant doc based on the query and then passes it to an
  336. LLM as context to get the answer.
  337. Maintains the whole conversation in memory.
  338. :param input_query: The query to use.
  339. :type input_query: str
  340. :param config: The `LlmConfig` instance to use as configuration options. This is used for one method call.
  341. To persistently use a config, declare it during app init., defaults to None
  342. :type config: Optional[BaseLlmConfig], optional
  343. :param dry_run: A dry run does everything except send the resulting prompt to
  344. the LLM. The purpose is to test the prompt, not the response., defaults to False
  345. :type dry_run: bool, optional
  346. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  347. :type where: Optional[Dict[str, str]], optional
  348. :return: The answer to the query or the dry run result
  349. :rtype: str
  350. """
  351. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  352. answer = self.llm.chat(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  353. # Send anonymous telemetry
  354. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("chat",))
  355. thread_telemetry.start()
  356. return answer
  357. def set_collection_name(self, name: str):
  358. """
  359. Set the name of the collection. A collection is an isolated space for vectors.
  360. Using `app.db.set_collection_name` method is preferred to this.
  361. :param name: Name of the collection.
  362. :type name: str
  363. """
  364. self.db.set_collection_name(name)
  365. # Create the collection if it does not exist
  366. self.db._get_or_create_collection(name)
  367. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  368. # since the main purpose is the creation.
  369. def count(self) -> int:
  370. """
  371. Count the number of embeddings.
  372. DEPRECATED IN FAVOR OF `db.count()`
  373. :return: The number of embeddings.
  374. :rtype: int
  375. """
  376. logging.warning("DEPRECATION WARNING: Please use `app.db.count()` instead of `app.count()`.")
  377. return self.db.count()
  378. def reset(self):
  379. """
  380. Resets the database. Deletes all embeddings irreversibly.
  381. `App` does not have to be reinitialized after using this method.
  382. DEPRECATED IN FAVOR OF `db.reset()`
  383. """
  384. # Send anonymous telemetry
  385. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("reset",))
  386. thread_telemetry.start()
  387. logging.warning("DEPRECATION WARNING: Please use `app.db.reset()` instead of `App.reset()`.")
  388. self.db.reset()
  389. @retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
  390. def _send_telemetry_event(self, method: str, extra_metadata: Optional[dict] = None):
  391. """
  392. Send telemetry event to the embedchain server. This is anonymous. It can be toggled off in `AppConfig`.
  393. """
  394. if not self.config.collect_metrics:
  395. return
  396. with threading.Lock():
  397. url = "https://api.embedchain.ai/api/v1/telemetry/"
  398. metadata = {
  399. "s_id": self.s_id,
  400. "version": importlib.metadata.version(__package__ or __name__),
  401. "method": method,
  402. "language": "py",
  403. "u_id": self.u_id,
  404. }
  405. if extra_metadata:
  406. metadata.update(extra_metadata)
  407. response = requests.post(url, json={"metadata": metadata})
  408. if response.status_code != 200:
  409. logging.warning(f"Telemetry event failed with status code {response.status_code}")