embedchain.py 24 KB

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