embedchain.py 24 KB

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