embedchain.py 23 KB

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