embedchain.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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_embedder import BaseEmbedder
  18. from embedchain.helper_classes.json_serializable import JSONSerializable
  19. from embedchain.llm.base_llm 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_vector_db 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. ):
  110. """
  111. Adds the data from the given URL to the vector db.
  112. Loads the data, chunks it, create embedding for each chunk
  113. and then stores the embedding to vector database.
  114. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  115. :type source: Any
  116. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  117. defaults to None
  118. :type data_type: Optional[DataType], optional
  119. :param metadata: Metadata associated with the data source., defaults to None
  120. :type metadata: Optional[Dict[str, Any]], optional
  121. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  122. :type config: Optional[AddConfig], optional
  123. :raises ValueError: Invalid data type
  124. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  125. :rtype: str
  126. """
  127. if config is None:
  128. config = AddConfig()
  129. try:
  130. DataType(source)
  131. logging.warning(
  132. 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
  133. )
  134. logging.warning(
  135. "Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
  136. )
  137. source, data_type = data_type, source
  138. except ValueError:
  139. pass
  140. if data_type:
  141. try:
  142. data_type = DataType(data_type)
  143. except ValueError:
  144. raise ValueError(
  145. f"Invalid data_type: '{data_type}'.",
  146. f"Please use one of the following: {[data_type.value for data_type in DataType]}",
  147. ) from None
  148. if not data_type:
  149. data_type = detect_datatype(source)
  150. # `source_id` is the hash of the source argument
  151. hash_object = hashlib.md5(str(source).encode("utf-8"))
  152. source_id = hash_object.hexdigest()
  153. data_formatter = DataFormatter(data_type, config)
  154. self.user_asks.append([source, data_type.value, metadata])
  155. documents, _metadatas, _ids, new_chunks = self.load_and_embed(
  156. data_formatter.loader, data_formatter.chunker, source, metadata, source_id
  157. )
  158. if data_type in {DataType.DOCS_SITE}:
  159. self.is_docs_site_instance = True
  160. # Send anonymous telemetry
  161. if self.config.collect_metrics:
  162. # it's quicker to check the variable twice than to count words when they won't be submitted.
  163. word_count = sum([len(document.split(" ")) for document in documents])
  164. extra_metadata = {"data_type": data_type.value, "word_count": word_count, "chunks_count": new_chunks}
  165. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("add", extra_metadata))
  166. thread_telemetry.start()
  167. return source_id
  168. def add_local(
  169. self,
  170. source: Any,
  171. data_type: Optional[DataType] = None,
  172. metadata: Optional[Dict[str, Any]] = None,
  173. config: Optional[AddConfig] = None,
  174. ):
  175. """
  176. Adds the data from the given URL to the vector db.
  177. Loads the data, chunks it, create embedding for each chunk
  178. and then stores the embedding to vector database.
  179. Warning:
  180. This method is deprecated and will be removed in future versions. Use `add` instead.
  181. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  182. :type source: Any
  183. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  184. defaults to None
  185. :type data_type: Optional[DataType], optional
  186. :param metadata: Metadata associated with the data source., defaults to None
  187. :type metadata: Optional[Dict[str, Any]], optional
  188. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  189. :type config: Optional[AddConfig], optional
  190. :raises ValueError: Invalid data type
  191. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  192. :rtype: str
  193. """
  194. logging.warning(
  195. "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
  196. )
  197. return self.add(source=source, data_type=data_type, metadata=metadata, config=config)
  198. def load_and_embed(
  199. self,
  200. loader: BaseLoader,
  201. chunker: BaseChunker,
  202. src: Any,
  203. metadata: Optional[Dict[str, Any]] = None,
  204. source_id: Optional[str] = None,
  205. ) -> Tuple[List[str], Dict[str, Any], List[str], int]:
  206. """The loader to use to load the data.
  207. :param loader: The loader to use to load the data.
  208. :type loader: BaseLoader
  209. :param chunker: The chunker to use to chunk the data.
  210. :type chunker: BaseChunker
  211. :param src: The data to be handled by the loader.
  212. Can be a URL for remote sources or local content for local loaders.
  213. :type src: Any
  214. :param metadata: Metadata associated with the data source., defaults to None
  215. :type metadata: Dict[str, Any], optional
  216. :param source_id: Hexadecimal hash of the source., defaults to None
  217. :type source_id: str, optional
  218. :return: (List) documents (embedded text), (List) metadata, (list) ids, (int) number of chunks
  219. :rtype: Tuple[List[str], Dict[str, Any], List[str], int]
  220. """
  221. embeddings_data = chunker.create_chunks(loader, src)
  222. # spread chunking results
  223. documents = embeddings_data["documents"]
  224. metadatas = embeddings_data["metadatas"]
  225. ids = embeddings_data["ids"]
  226. # get existing ids, and discard doc if any common id exist.
  227. where = {"app_id": self.config.id} if self.config.id is not None else {}
  228. # where={"url": src}
  229. existing_ids = self.db.get(
  230. ids=ids,
  231. where=where, # optional filter
  232. )
  233. if len(existing_ids):
  234. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  235. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  236. if not data_dict:
  237. print(f"All data from {src} already exists in the database.")
  238. # Make sure to return a matching return type
  239. return [], [], [], 0
  240. ids = list(data_dict.keys())
  241. documents, metadatas = zip(*data_dict.values())
  242. # Loop though all metadatas and add extras.
  243. new_metadatas = []
  244. for m in metadatas:
  245. # Add app id in metadatas so that they can be queried on later
  246. if self.config.id:
  247. m["app_id"] = self.config.id
  248. # Add hashed source
  249. m["hash"] = source_id
  250. # Note: Metadata is the function argument
  251. if metadata:
  252. # Spread whatever is in metadata into the new object.
  253. m.update(metadata)
  254. new_metadatas.append(m)
  255. metadatas = new_metadatas
  256. # Count before, to calculate a delta in the end.
  257. chunks_before_addition = self.db.count()
  258. self.db.add(documents=documents, metadatas=metadatas, ids=ids)
  259. count_new_chunks = self.db.count() - chunks_before_addition
  260. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  261. return list(documents), metadatas, ids, count_new_chunks
  262. def retrieve_from_database(self, input_query: str, config: Optional[BaseLlmConfig] = None, where=None) -> List[str]:
  263. """
  264. Queries the vector database based on the given input query.
  265. Gets relevant doc based on the query
  266. :param input_query: The query to use.
  267. :type input_query: str
  268. :param config: The query configuration, defaults to None
  269. :type config: Optional[BaseLlmConfig], optional
  270. :param where: A dictionary of key-value pairs to filter the database results, defaults to None
  271. :type where: _type_, optional
  272. :return: List of contents of the document that matched your query
  273. :rtype: List[str]
  274. """
  275. query_config = config or self.llm.config
  276. if where is not None:
  277. where = where
  278. elif query_config is not None and query_config.where is not None:
  279. where = query_config.where
  280. else:
  281. where = {}
  282. if self.config.id is not None:
  283. where.update({"app_id": self.config.id})
  284. contents = self.db.query(
  285. input_query=input_query,
  286. n_results=query_config.number_documents,
  287. where=where,
  288. )
  289. return contents
  290. def query(self, input_query: str, config: BaseLlmConfig = None, dry_run=False, where: Optional[Dict] = None) -> str:
  291. """
  292. Queries the vector database based on the given input query.
  293. Gets relevant doc based on the query and then passes it to an
  294. LLM as context to get the answer.
  295. :param input_query: The query to use.
  296. :type input_query: str
  297. :param config: The `LlmConfig` instance to use as configuration options. This is used for one method call.
  298. To persistently use a config, declare it during app init., defaults to None
  299. :type config: Optional[BaseLlmConfig], optional
  300. :param dry_run: A dry run does everything except send the resulting prompt to
  301. the LLM. The purpose is to test the prompt, not the response., defaults to False
  302. :type dry_run: bool, optional
  303. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  304. :type where: Optional[Dict[str, str]], optional
  305. :return: The answer to the query or the dry run result
  306. :rtype: str
  307. """
  308. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  309. answer = self.llm.query(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  310. # Send anonymous telemetry
  311. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("query",))
  312. thread_telemetry.start()
  313. return answer
  314. def chat(
  315. self,
  316. input_query: str,
  317. config: Optional[BaseLlmConfig] = None,
  318. dry_run=False,
  319. where: Optional[Dict[str, str]] = None,
  320. ) -> str:
  321. """
  322. Queries the vector database on the given input query.
  323. Gets relevant doc based on the query and then passes it to an
  324. LLM as context to get the answer.
  325. Maintains the whole conversation in memory.
  326. :param input_query: The query to use.
  327. :type input_query: str
  328. :param config: The `LlmConfig` instance to use as configuration options. This is used for one method call.
  329. To persistently use a config, declare it during app init., defaults to None
  330. :type config: Optional[BaseLlmConfig], optional
  331. :param dry_run: A dry run does everything except send the resulting prompt to
  332. the LLM. The purpose is to test the prompt, not the response., defaults to False
  333. :type dry_run: bool, optional
  334. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  335. :type where: Optional[Dict[str, str]], optional
  336. :return: The answer to the query or the dry run result
  337. :rtype: str
  338. """
  339. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  340. answer = self.llm.chat(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  341. # Send anonymous telemetry
  342. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("chat",))
  343. thread_telemetry.start()
  344. return answer
  345. def set_collection_name(self, name: str):
  346. """
  347. Set the name of the collection. A collection is an isolated space for vectors.
  348. Using `app.db.set_collection_name` method is preferred to this.
  349. :param name: Name of the collection.
  350. :type name: str
  351. """
  352. self.db.set_collection_name(name)
  353. # Create the collection if it does not exist
  354. self.db._get_or_create_collection(name)
  355. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  356. # since the main purpose is the creation.
  357. def count(self) -> int:
  358. """
  359. Count the number of embeddings.
  360. DEPRECATED IN FAVOR OF `db.count()`
  361. :return: The number of embeddings.
  362. :rtype: int
  363. """
  364. logging.warning("DEPRECATION WARNING: Please use `app.db.count()` instead of `app.count()`.")
  365. return self.db.count()
  366. def reset(self):
  367. """
  368. Resets the database. Deletes all embeddings irreversibly.
  369. `App` does not have to be reinitialized after using this method.
  370. DEPRECATED IN FAVOR OF `db.reset()`
  371. """
  372. # Send anonymous telemetry
  373. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("reset",))
  374. thread_telemetry.start()
  375. logging.warning("DEPRECATION WARNING: Please use `app.db.reset()` instead of `App.reset()`.")
  376. self.db.reset()
  377. @retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
  378. def _send_telemetry_event(self, method: str, extra_metadata: Optional[dict] = None):
  379. """
  380. Send telemetry event to the embedchain server. This is anonymous. It can be toggled off in `AppConfig`.
  381. """
  382. if not self.config.collect_metrics:
  383. return
  384. with threading.Lock():
  385. url = "https://api.embedchain.ai/api/v1/telemetry/"
  386. metadata = {
  387. "s_id": self.s_id,
  388. "version": importlib.metadata.version(__package__ or __name__),
  389. "method": method,
  390. "language": "py",
  391. "u_id": self.u_id,
  392. }
  393. if extra_metadata:
  394. metadata.update(extra_metadata)
  395. response = requests.post(url, json={"metadata": metadata})
  396. if response.status_code != 200:
  397. logging.warning(f"Telemetry event failed with status code {response.status_code}")