embedchain.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 langchain.docstore.document import Document
  13. from tenacity import retry, stop_after_attempt, wait_fixed
  14. from embedchain.chunkers.base_chunker import BaseChunker
  15. from embedchain.config import AddConfig, BaseLlmConfig
  16. from embedchain.config.apps.BaseAppConfig import BaseAppConfig
  17. from embedchain.data_formatter import DataFormatter
  18. from embedchain.embedder.base import BaseEmbedder
  19. from embedchain.helper.json_serializable import JSONSerializable
  20. from embedchain.llm.base import BaseLlm
  21. from embedchain.loaders.base_loader import BaseLoader
  22. from embedchain.models.data_type import (DataType, DirectDataType,
  23. IndirectDataType, SpecialDataType)
  24. from embedchain.utils import detect_datatype
  25. from embedchain.vectordb.base import BaseVectorDB
  26. load_dotenv()
  27. ABS_PATH = os.getcwd()
  28. HOME_DIR = str(Path.home())
  29. CONFIG_DIR = os.path.join(HOME_DIR, ".embedchain")
  30. CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
  31. class EmbedChain(JSONSerializable):
  32. def __init__(
  33. self,
  34. config: BaseAppConfig,
  35. llm: BaseLlm,
  36. db: BaseVectorDB = None,
  37. embedder: BaseEmbedder = None,
  38. system_prompt: Optional[str] = None,
  39. ):
  40. """
  41. Initializes the EmbedChain instance, sets up a vector DB client and
  42. creates a collection.
  43. :param config: Configuration just for the app, not the db or llm or embedder.
  44. :type config: BaseAppConfig
  45. :param llm: Instance of the LLM you want to use.
  46. :type llm: BaseLlm
  47. :param db: Instance of the Database to use, defaults to None
  48. :type db: BaseVectorDB, optional
  49. :param embedder: instance of the embedder to use, defaults to None
  50. :type embedder: BaseEmbedder, optional
  51. :param system_prompt: System prompt to use in the llm query, defaults to None
  52. :type system_prompt: Optional[str], optional
  53. :raises ValueError: No database or embedder provided.
  54. """
  55. self.config = config
  56. # Add subclasses
  57. ## Llm
  58. self.llm = llm
  59. ## Database
  60. # Database has support for config assignment for backwards compatibility
  61. if db is None and (not hasattr(self.config, "db") or self.config.db is None):
  62. raise ValueError("App requires Database.")
  63. self.db = db or self.config.db
  64. ## Embedder
  65. if embedder is None:
  66. raise ValueError("App requires Embedder.")
  67. self.embedder = embedder
  68. # Initialize database
  69. self.db._set_embedder(self.embedder)
  70. self.db._initialize()
  71. # Set collection name from app config for backwards compatibility.
  72. if config.collection_name:
  73. self.db.set_collection_name(config.collection_name)
  74. # Add variables that are "shortcuts"
  75. if system_prompt:
  76. self.llm.config.system_prompt = system_prompt
  77. # Attributes that aren't subclass related.
  78. self.user_asks = []
  79. # Send anonymous telemetry
  80. self.s_id = self.config.id if self.config.id else str(uuid.uuid4())
  81. self.u_id = self._load_or_generate_user_id()
  82. # NOTE: Uncomment the next two lines when running tests to see if any test fires a telemetry event.
  83. # if (self.config.collect_metrics):
  84. # raise ConnectionRefusedError("Collection of metrics should not be allowed.")
  85. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("init",))
  86. thread_telemetry.start()
  87. @property
  88. def collect_metrics(self):
  89. return self.config.collect_metrics
  90. @collect_metrics.setter
  91. def collect_metrics(self, value):
  92. if not isinstance(value, bool):
  93. raise ValueError(f"Boolean value expected but got {type(value)}.")
  94. self.config.collect_metrics = value
  95. def _load_or_generate_user_id(self) -> str:
  96. """
  97. Loads the user id from the config file if it exists, otherwise generates a new
  98. one and saves it to the config file.
  99. :return: user id
  100. :rtype: str
  101. """
  102. if not os.path.exists(CONFIG_DIR):
  103. os.makedirs(CONFIG_DIR)
  104. if os.path.exists(CONFIG_FILE):
  105. with open(CONFIG_FILE, "r") as f:
  106. data = json.load(f)
  107. if "user_id" in data:
  108. return data["user_id"]
  109. u_id = str(uuid.uuid4())
  110. with open(CONFIG_FILE, "w") as f:
  111. json.dump({"user_id": u_id}, f)
  112. return u_id
  113. def add(
  114. self,
  115. source: Any,
  116. data_type: Optional[DataType] = None,
  117. metadata: Optional[Dict[str, Any]] = None,
  118. config: Optional[AddConfig] = None,
  119. dry_run=False,
  120. ):
  121. """
  122. Adds the data from the given URL to the vector db.
  123. Loads the data, chunks it, create embedding for each chunk
  124. and then stores the embedding to vector database.
  125. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  126. :type source: Any
  127. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  128. defaults to None
  129. :type data_type: Optional[DataType], optional
  130. :param metadata: Metadata associated with the data source., defaults to None
  131. :type metadata: Optional[Dict[str, Any]], optional
  132. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  133. :type config: Optional[AddConfig], optional
  134. :raises ValueError: Invalid data type
  135. :param dry_run: Optional. A dry run displays the chunks to ensure that the loader and chunker work as intended.
  136. deafaults to False
  137. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  138. :rtype: str
  139. """
  140. if config is None:
  141. config = AddConfig()
  142. try:
  143. DataType(source)
  144. logging.warning(
  145. 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
  146. )
  147. logging.warning(
  148. "Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
  149. )
  150. source, data_type = data_type, source
  151. except ValueError:
  152. pass
  153. if data_type:
  154. try:
  155. data_type = DataType(data_type)
  156. except ValueError:
  157. raise ValueError(
  158. f"Invalid data_type: '{data_type}'.",
  159. f"Please use one of the following: {[data_type.value for data_type in DataType]}",
  160. ) from None
  161. if not data_type:
  162. data_type = detect_datatype(source)
  163. # `source_id` is the hash of the source argument
  164. hash_object = hashlib.md5(str(source).encode("utf-8"))
  165. source_id = hash_object.hexdigest()
  166. data_formatter = DataFormatter(data_type, config)
  167. self.user_asks.append([source, data_type.value, metadata])
  168. documents, metadatas, _ids, new_chunks = self.load_and_embed_v2(
  169. data_formatter.loader, data_formatter.chunker, source, metadata, source_id, dry_run
  170. )
  171. if data_type in {DataType.DOCS_SITE}:
  172. self.is_docs_site_instance = True
  173. if dry_run:
  174. data_chunks_info = {"chunks": documents, "metadata": metadatas, "count": len(documents), "type": data_type}
  175. logging.debug(f"Dry run info : {data_chunks_info}")
  176. return data_chunks_info
  177. # Send anonymous telemetry
  178. if self.config.collect_metrics:
  179. # it's quicker to check the variable twice than to count words when they won't be submitted.
  180. word_count = sum([len(document.split(" ")) for document in documents])
  181. extra_metadata = {"data_type": data_type.value, "word_count": word_count, "chunks_count": new_chunks}
  182. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("add", extra_metadata))
  183. thread_telemetry.start()
  184. return source_id
  185. def add_local(
  186. self,
  187. source: Any,
  188. data_type: Optional[DataType] = None,
  189. metadata: Optional[Dict[str, Any]] = None,
  190. config: Optional[AddConfig] = None,
  191. ):
  192. """
  193. Adds the data from the given URL to the vector db.
  194. Loads the data, chunks it, create embedding for each chunk
  195. and then stores the embedding to vector database.
  196. Warning:
  197. This method is deprecated and will be removed in future versions. Use `add` instead.
  198. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  199. :type source: Any
  200. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  201. defaults to None
  202. :type data_type: Optional[DataType], optional
  203. :param metadata: Metadata associated with the data source., defaults to None
  204. :type metadata: Optional[Dict[str, Any]], optional
  205. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  206. :type config: Optional[AddConfig], optional
  207. :raises ValueError: Invalid data type
  208. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  209. :rtype: str
  210. """
  211. logging.warning(
  212. "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
  213. )
  214. return self.add(source=source, data_type=data_type, metadata=metadata, config=config)
  215. def load_and_embed(
  216. self,
  217. loader: BaseLoader,
  218. chunker: BaseChunker,
  219. src: Any,
  220. metadata: Optional[Dict[str, Any]] = None,
  221. source_id: Optional[str] = None,
  222. dry_run=False,
  223. ) -> Tuple[List[str], Dict[str, Any], List[str], int]:
  224. """The loader to use to load the data.
  225. :param loader: The loader to use to load the data.
  226. :type loader: BaseLoader
  227. :param chunker: The chunker to use to chunk the data.
  228. :type chunker: BaseChunker
  229. :param src: The data to be handled by the loader.
  230. Can be a URL for remote sources or local content for local loaders.
  231. :type src: Any
  232. :param metadata: Metadata associated with the data source., defaults to None
  233. :type metadata: Dict[str, Any], optional
  234. :param source_id: Hexadecimal hash of the source., defaults to None
  235. :type source_id: str, optional
  236. :param dry_run: Optional. A dry run returns chunks and doesn't update DB.
  237. :type dry_run: bool, defaults to False
  238. :return: (List) documents (embedded text), (List) metadata, (list) ids, (int) number of chunks
  239. :rtype: Tuple[List[str], Dict[str, Any], List[str], int]
  240. """
  241. embeddings_data = chunker.create_chunks(loader, src)
  242. # spread chunking results
  243. documents = embeddings_data["documents"]
  244. metadatas = embeddings_data["metadatas"]
  245. ids = embeddings_data["ids"]
  246. # get existing ids, and discard doc if any common id exist.
  247. where = {"app_id": self.config.id} if self.config.id is not None else {}
  248. # where={"url": src}
  249. db_result = self.db.get(
  250. ids=ids,
  251. where=where, # optional filter
  252. )
  253. existing_ids = set(db_result["ids"])
  254. if len(existing_ids):
  255. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  256. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  257. if not data_dict:
  258. src_copy = src
  259. if len(src_copy) > 50:
  260. src_copy = src[:50] + "..."
  261. print(f"All data from {src_copy} already exists in the database.")
  262. # Make sure to return a matching return type
  263. return [], [], [], 0
  264. ids = list(data_dict.keys())
  265. documents, metadatas = zip(*data_dict.values())
  266. if dry_run:
  267. return list(documents), metadatas, ids, 0
  268. # Loop though all metadatas and add extras.
  269. new_metadatas = []
  270. for m in metadatas:
  271. # Add app id in metadatas so that they can be queried on later
  272. if self.config.id:
  273. m["app_id"] = self.config.id
  274. # Add hashed source
  275. m["hash"] = source_id
  276. # Note: Metadata is the function argument
  277. if metadata:
  278. # Spread whatever is in metadata into the new object.
  279. m.update(metadata)
  280. new_metadatas.append(m)
  281. metadatas = new_metadatas
  282. # Count before, to calculate a delta in the end.
  283. chunks_before_addition = self.db.count()
  284. self.db.add(documents=documents, metadatas=metadatas, ids=ids)
  285. count_new_chunks = self.db.count() - chunks_before_addition
  286. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  287. return list(documents), metadatas, ids, count_new_chunks
  288. def _get_existing_doc_id(self, chunker: BaseChunker, src: Any):
  289. """
  290. Get id of existing document for a given source, based on the data type
  291. """
  292. # Find existing embeddings for the source
  293. # Depending on the data type, existing embeddings are checked for.
  294. if chunker.data_type.value in [item.value for item in DirectDataType]:
  295. # DirectDataTypes can't be updated.
  296. # Think of a text:
  297. # Either it's the same, then it won't change, so it's not an update.
  298. # Or it's different, then it will be added as a new text.
  299. return None
  300. elif chunker.data_type.value in [item.value for item in IndirectDataType]:
  301. # These types have a indirect source reference
  302. # As long as the reference is the same, they can be updated.
  303. existing_embeddings_data = self.db.get(
  304. where={
  305. "url": src,
  306. },
  307. limit=1,
  308. )
  309. if len(existing_embeddings_data.get("metadatas", [])) > 0:
  310. return existing_embeddings_data["metadatas"][0]["doc_id"]
  311. else:
  312. return None
  313. elif chunker.data_type.value in [item.value for item in SpecialDataType]:
  314. # These types don't contain indirect references.
  315. # Through custom logic, they can be attributed to a source and be updated.
  316. if chunker.data_type == DataType.QNA_PAIR:
  317. # QNA_PAIRs update the answer if the question already exists.
  318. existing_embeddings_data = self.db.get(
  319. where={
  320. "question": src[0],
  321. },
  322. limit=1,
  323. )
  324. if len(existing_embeddings_data.get("metadatas", [])) > 0:
  325. return existing_embeddings_data["metadatas"][0]["doc_id"]
  326. else:
  327. return None
  328. else:
  329. raise NotImplementedError(
  330. f"SpecialDataType {chunker.data_type} must have a custom logic to check for existing data"
  331. )
  332. else:
  333. raise TypeError(
  334. f"{chunker.data_type} is type {type(chunker.data_type)}. "
  335. "When it should be DirectDataType, IndirectDataType or SpecialDataType."
  336. )
  337. def load_and_embed_v2(
  338. self,
  339. loader: BaseLoader,
  340. chunker: BaseChunker,
  341. src: Any,
  342. metadata: Optional[Dict[str, Any]] = None,
  343. source_id: Optional[str] = None,
  344. dry_run=False,
  345. ):
  346. """
  347. Loads the data from the given URL, chunks it, and adds it to database.
  348. :param loader: The loader to use to load the data.
  349. :param chunker: The chunker to use to chunk the data.
  350. :param src: The data to be handled by the loader. Can be a URL for
  351. remote sources or local content for local loaders.
  352. :param metadata: Optional. Metadata associated with the data source.
  353. :param source_id: Hexadecimal hash of the source.
  354. :return: (List) documents (embedded text), (List) metadata, (list) ids, (int) number of chunks
  355. """
  356. existing_doc_id = self._get_existing_doc_id(chunker=chunker, src=src)
  357. # Create chunks
  358. embeddings_data = chunker.create_chunks(loader, src)
  359. # spread chunking results
  360. documents = embeddings_data["documents"]
  361. metadatas = embeddings_data["metadatas"]
  362. ids = embeddings_data["ids"]
  363. new_doc_id = embeddings_data["doc_id"]
  364. if existing_doc_id and existing_doc_id == new_doc_id:
  365. print("Doc content has not changed. Skipping creating chunks and embeddings")
  366. return [], [], [], 0
  367. # this means that doc content has changed.
  368. if existing_doc_id and existing_doc_id != new_doc_id:
  369. print("Doc content has changed. Recomputing chunks and embeddings intelligently.")
  370. self.db.delete({"doc_id": existing_doc_id})
  371. # get existing ids, and discard doc if any common id exist.
  372. where = {"app_id": self.config.id} if self.config.id is not None else {}
  373. # where={"url": src}
  374. db_result = self.db.get(
  375. ids=ids,
  376. where=where, # optional filter
  377. )
  378. existing_ids = set(db_result["ids"])
  379. if len(existing_ids):
  380. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  381. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  382. if not data_dict:
  383. src_copy = src
  384. if len(src_copy) > 50:
  385. src_copy = src[:50] + "..."
  386. print(f"All data from {src_copy} already exists in the database.")
  387. # Make sure to return a matching return type
  388. return [], [], [], 0
  389. ids = list(data_dict.keys())
  390. documents, metadatas = zip(*data_dict.values())
  391. # Loop though all metadatas and add extras.
  392. new_metadatas = []
  393. for m in metadatas:
  394. # Add app id in metadatas so that they can be queried on later
  395. if self.config.id:
  396. m["app_id"] = self.config.id
  397. # Add hashed source
  398. m["hash"] = source_id
  399. # Note: Metadata is the function argument
  400. if metadata:
  401. # Spread whatever is in metadata into the new object.
  402. m.update(metadata)
  403. new_metadatas.append(m)
  404. metadatas = new_metadatas
  405. # Count before, to calculate a delta in the end.
  406. chunks_before_addition = self.count()
  407. self.db.add(documents=documents, metadatas=metadatas, ids=ids)
  408. count_new_chunks = self.count() - chunks_before_addition
  409. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  410. return list(documents), metadatas, ids, count_new_chunks
  411. def _format_result(self, results):
  412. return [
  413. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  414. for result in zip(
  415. results["documents"][0],
  416. results["metadatas"][0],
  417. results["distances"][0],
  418. )
  419. ]
  420. def retrieve_from_database(self, input_query: str, config: Optional[BaseLlmConfig] = None, where=None) -> List[str]:
  421. """
  422. Queries the vector database based on the given input query.
  423. Gets relevant doc based on the query
  424. :param input_query: The query to use.
  425. :type input_query: str
  426. :param config: The query configuration, defaults to None
  427. :type config: Optional[BaseLlmConfig], optional
  428. :param where: A dictionary of key-value pairs to filter the database results, defaults to None
  429. :type where: _type_, optional
  430. :return: List of contents of the document that matched your query
  431. :rtype: List[str]
  432. """
  433. query_config = config or self.llm.config
  434. if where is not None:
  435. where = where
  436. elif query_config is not None and query_config.where is not None:
  437. where = query_config.where
  438. else:
  439. where = {}
  440. if self.config.id is not None:
  441. where.update({"app_id": self.config.id})
  442. contents = self.db.query(
  443. input_query=input_query,
  444. n_results=query_config.number_documents,
  445. where=where,
  446. )
  447. return contents
  448. def query(self, input_query: str, config: BaseLlmConfig = None, dry_run=False, where: Optional[Dict] = None) -> str:
  449. """
  450. Queries the vector database based on the given input query.
  451. Gets relevant doc based on the query and then passes it to an
  452. LLM as context to get the answer.
  453. :param input_query: The query to use.
  454. :type input_query: str
  455. :param config: The `LlmConfig` instance to use as configuration options. This is used for one method call.
  456. To persistently use a config, declare it during app init., defaults to None
  457. :type config: Optional[BaseLlmConfig], optional
  458. :param dry_run: A dry run does everything except send the resulting prompt to
  459. the LLM. The purpose is to test the prompt, not the response., defaults to False
  460. :type dry_run: bool, optional
  461. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  462. :type where: Optional[Dict[str, str]], optional
  463. :return: The answer to the query or the dry run result
  464. :rtype: str
  465. """
  466. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  467. answer = self.llm.query(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  468. # Send anonymous telemetry
  469. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("query",))
  470. thread_telemetry.start()
  471. return answer
  472. def chat(
  473. self,
  474. input_query: str,
  475. config: Optional[BaseLlmConfig] = None,
  476. dry_run=False,
  477. where: Optional[Dict[str, str]] = None,
  478. ) -> str:
  479. """
  480. Queries the vector database on the given input query.
  481. Gets relevant doc based on the query and then passes it to an
  482. LLM as context to get the answer.
  483. Maintains the whole conversation in memory.
  484. :param input_query: The query to use.
  485. :type input_query: str
  486. :param config: The `LlmConfig` instance to use as configuration options. This is used for one method call.
  487. To persistently use a config, declare it during app init., defaults to None
  488. :type config: Optional[BaseLlmConfig], optional
  489. :param dry_run: A dry run does everything except send the resulting prompt to
  490. the LLM. The purpose is to test the prompt, not the response., defaults to False
  491. :type dry_run: bool, optional
  492. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  493. :type where: Optional[Dict[str, str]], optional
  494. :return: The answer to the query or the dry run result
  495. :rtype: str
  496. """
  497. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  498. answer = self.llm.chat(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  499. # Send anonymous telemetry
  500. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("chat",))
  501. thread_telemetry.start()
  502. return answer
  503. def set_collection_name(self, name: str):
  504. """
  505. Set the name of the collection. A collection is an isolated space for vectors.
  506. Using `app.db.set_collection_name` method is preferred to this.
  507. :param name: Name of the collection.
  508. :type name: str
  509. """
  510. self.db.set_collection_name(name)
  511. # Create the collection if it does not exist
  512. self.db._get_or_create_collection(name)
  513. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  514. # since the main purpose is the creation.
  515. def count(self) -> int:
  516. """
  517. Count the number of embeddings.
  518. DEPRECATED IN FAVOR OF `db.count()`
  519. :return: The number of embeddings.
  520. :rtype: int
  521. """
  522. logging.warning("DEPRECATION WARNING: Please use `app.db.count()` instead of `app.count()`.")
  523. return self.db.count()
  524. def reset(self):
  525. """
  526. Resets the database. Deletes all embeddings irreversibly.
  527. `App` does not have to be reinitialized after using this method.
  528. DEPRECATED IN FAVOR OF `db.reset()`
  529. """
  530. # Send anonymous telemetry
  531. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("reset",))
  532. thread_telemetry.start()
  533. logging.warning("DEPRECATION WARNING: Please use `app.db.reset()` instead of `App.reset()`.")
  534. self.db.reset()
  535. @retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
  536. def _send_telemetry_event(self, method: str, extra_metadata: Optional[dict] = None):
  537. """
  538. Send telemetry event to the embedchain server. This is anonymous. It can be toggled off in `AppConfig`.
  539. """
  540. if not self.config.collect_metrics:
  541. return
  542. with threading.Lock():
  543. url = "https://api.embedchain.ai/api/v1/telemetry/"
  544. metadata = {
  545. "s_id": self.s_id,
  546. "version": importlib.metadata.version(__package__ or __name__),
  547. "method": method,
  548. "language": "py",
  549. "u_id": self.u_id,
  550. }
  551. if extra_metadata:
  552. metadata.update(extra_metadata)
  553. response = requests.post(url, json={"metadata": metadata})
  554. if response.status_code != 200:
  555. logging.warning(f"Telemetry event failed with status code {response.status_code}")