embedchain.py 26 KB

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