embedchain.py 25 KB

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