embedchain.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 Dict, 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.BaseAppConfig import BaseAppConfig
  17. from embedchain.data_formatter import DataFormatter
  18. from embedchain.embedder.base_embedder import BaseEmbedder
  19. from embedchain.helper_classes.json_serializable import JSONSerializable
  20. from embedchain.llm.base_llm 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_vector_db 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: BaseAppConfig instance to load as configuration.
  43. :param system_prompt: Optional. System prompt string.
  44. """
  45. self.config = config
  46. # Add subclasses
  47. ## Llm
  48. self.llm = llm
  49. ## Database
  50. # Database has support for config assignment for backwards compatibility
  51. if db is None and (not hasattr(self.config, "db") or self.config.db is None):
  52. raise ValueError("App requires Database.")
  53. self.db = db or self.config.db
  54. ## Embedder
  55. if embedder is None:
  56. raise ValueError("App requires Embedder.")
  57. self.embedder = embedder
  58. # Initialize database
  59. self.db._set_embedder(self.embedder)
  60. self.db._initialize()
  61. # Set collection name from app config for backwards compatibility.
  62. if config.collection_name:
  63. self.db.set_collection_name(config.collection_name)
  64. # Add variables that are "shortcuts"
  65. if system_prompt:
  66. self.llm.config.system_prompt = system_prompt
  67. # Attributes that aren't subclass related.
  68. self.user_asks = []
  69. # Send anonymous telemetry
  70. self.s_id = self.config.id if self.config.id else str(uuid.uuid4())
  71. self.u_id = self._load_or_generate_user_id()
  72. # NOTE: Uncomment the next two lines when running tests to see if any test fires a telemetry event.
  73. # if (self.config.collect_metrics):
  74. # raise ConnectionRefusedError("Collection of metrics should not be allowed.")
  75. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("init",))
  76. thread_telemetry.start()
  77. def _load_or_generate_user_id(self):
  78. """
  79. Loads the user id from the config file if it exists, otherwise generates a new
  80. one and saves it to the config file.
  81. """
  82. if not os.path.exists(CONFIG_DIR):
  83. os.makedirs(CONFIG_DIR)
  84. if os.path.exists(CONFIG_FILE):
  85. with open(CONFIG_FILE, "r") as f:
  86. data = json.load(f)
  87. if "user_id" in data:
  88. return data["user_id"]
  89. u_id = str(uuid.uuid4())
  90. with open(CONFIG_FILE, "w") as f:
  91. json.dump({"user_id": u_id}, f)
  92. return u_id
  93. def add(
  94. self,
  95. source,
  96. data_type: Optional[DataType] = None,
  97. metadata: Optional[Dict] = None,
  98. config: Optional[AddConfig] = None,
  99. ):
  100. """
  101. Adds the data from the given URL to the vector db.
  102. Loads the data, chunks it, create embedding for each chunk
  103. and then stores the embedding to vector database.
  104. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  105. :param data_type: Optional. Automatically detected, but can be forced with this argument.
  106. The type of the data to add.
  107. :param metadata: Optional. Metadata associated with the data source.
  108. :param config: Optional. The `AddConfig` instance to use as configuration
  109. options.
  110. :return: source_id, a md5-hash of the source, in hexadecimal representation.
  111. """
  112. if config is None:
  113. config = AddConfig()
  114. try:
  115. DataType(source)
  116. logging.warning(
  117. 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
  118. )
  119. logging.warning(
  120. "Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
  121. )
  122. source, data_type = data_type, source
  123. except ValueError:
  124. pass
  125. if data_type:
  126. try:
  127. data_type = DataType(data_type)
  128. except ValueError:
  129. raise ValueError(
  130. f"Invalid data_type: '{data_type}'.",
  131. f"Please use one of the following: {[data_type.value for data_type in DataType]}",
  132. ) from None
  133. if not data_type:
  134. data_type = detect_datatype(source)
  135. # `source_id` is the hash of the source argument
  136. hash_object = hashlib.md5(str(source).encode("utf-8"))
  137. source_id = hash_object.hexdigest()
  138. data_formatter = DataFormatter(data_type, config)
  139. self.user_asks.append([source, data_type.value, metadata])
  140. documents, _metadatas, _ids, new_chunks = self.load_and_embed(
  141. data_formatter.loader, data_formatter.chunker, source, metadata, source_id
  142. )
  143. if data_type in {DataType.DOCS_SITE}:
  144. self.is_docs_site_instance = True
  145. # Send anonymous telemetry
  146. if self.config.collect_metrics:
  147. # it's quicker to check the variable twice than to count words when they won't be submitted.
  148. word_count = sum([len(document.split(" ")) for document in documents])
  149. extra_metadata = {"data_type": data_type.value, "word_count": word_count, "chunks_count": new_chunks}
  150. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("add", extra_metadata))
  151. thread_telemetry.start()
  152. return source_id
  153. def add_local(self, source, data_type=None, metadata=None, config: AddConfig = None):
  154. """
  155. Warning:
  156. This method is deprecated and will be removed in future versions. Use `add` instead.
  157. Adds the data from the given URL to the vector db.
  158. Loads the data, chunks it, create embedding for each chunk
  159. and then stores the embedding to vector database.
  160. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  161. :param data_type: Optional. Automatically detected, but can be forced with this argument.
  162. The type of the data to add.
  163. :param metadata: Optional. Metadata associated with the data source.
  164. :param config: Optional. The `AddConfig` instance to use as configuration
  165. options.
  166. :return: md5-hash of the source, in hexadecimal representation.
  167. """
  168. logging.warning(
  169. "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
  170. )
  171. return self.add(source=source, data_type=data_type, metadata=metadata, config=config)
  172. def load_and_embed(self, loader: BaseLoader, chunker: BaseChunker, src, metadata=None, source_id=None):
  173. """
  174. Loads the data from the given URL, chunks it, and adds it to database.
  175. :param loader: The loader to use to load the data.
  176. :param chunker: The chunker to use to chunk the data.
  177. :param src: The data to be handled by the loader. Can be a URL for
  178. remote sources or local content for local loaders.
  179. :param metadata: Optional. Metadata associated with the data source.
  180. :param source_id: Hexadecimal hash of the source.
  181. :return: (List) documents (embedded text), (List) metadata, (list) ids, (int) number of chunks
  182. """
  183. embeddings_data = chunker.create_chunks(loader, src)
  184. # spread chunking results
  185. documents = embeddings_data["documents"]
  186. metadatas = embeddings_data["metadatas"]
  187. ids = embeddings_data["ids"]
  188. # get existing ids, and discard doc if any common id exist.
  189. where = {"app_id": self.config.id} if self.config.id is not None else {}
  190. # where={"url": src}
  191. existing_ids = self.db.get(
  192. ids=ids,
  193. where=where, # optional filter
  194. )
  195. if len(existing_ids):
  196. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  197. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  198. if not data_dict:
  199. print(f"All data from {src} already exists in the database.")
  200. # Make sure to return a matching return type
  201. return [], [], [], 0
  202. ids = list(data_dict.keys())
  203. documents, metadatas = zip(*data_dict.values())
  204. # Loop though all metadatas and add extras.
  205. new_metadatas = []
  206. for m in metadatas:
  207. # Add app id in metadatas so that they can be queried on later
  208. if self.config.id:
  209. m["app_id"] = self.config.id
  210. # Add hashed source
  211. m["hash"] = source_id
  212. # Note: Metadata is the function argument
  213. if metadata:
  214. # Spread whatever is in metadata into the new object.
  215. m.update(metadata)
  216. new_metadatas.append(m)
  217. metadatas = new_metadatas
  218. # Count before, to calculate a delta in the end.
  219. chunks_before_addition = self.db.count()
  220. self.db.add(documents=documents, metadatas=metadatas, ids=ids)
  221. count_new_chunks = self.db.count() - chunks_before_addition
  222. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  223. return list(documents), metadatas, ids, count_new_chunks
  224. def _format_result(self, results):
  225. return [
  226. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  227. for result in zip(
  228. results["documents"][0],
  229. results["metadatas"][0],
  230. results["distances"][0],
  231. )
  232. ]
  233. def retrieve_from_database(self, input_query, config: Optional[BaseLlmConfig] = None, where=None):
  234. """
  235. Queries the vector database based on the given input query.
  236. Gets relevant doc based on the query
  237. :param input_query: The query to use.
  238. :param config: The query configuration.
  239. :param where: Optional. A dictionary of key-value pairs to filter the database results.
  240. :return: The content of the document that matched your query.
  241. """
  242. query_config = config or self.llm.config
  243. if where is not None:
  244. where = where
  245. elif query_config is not None and query_config.where is not None:
  246. where = query_config.where
  247. else:
  248. where = {}
  249. if self.config.id is not None:
  250. where.update({"app_id": self.config.id})
  251. contents = self.db.query(
  252. input_query=input_query,
  253. n_results=query_config.number_documents,
  254. where=where,
  255. )
  256. return contents
  257. def query(self, input_query, config: BaseLlmConfig = None, dry_run=False, where=None):
  258. """
  259. Queries the vector database based on the given input query.
  260. Gets relevant doc based on the query and then passes it to an
  261. LLM as context to get the answer.
  262. :param input_query: The query to use.
  263. :param config: Optional. The `LlmConfig` instance to use as configuration options.
  264. This is used for one method call. To persistently use a config, declare it during app init.
  265. :param dry_run: Optional. A dry run does everything except send the resulting prompt to
  266. the LLM. The purpose is to test the prompt, not the response.
  267. You can use it to test your prompt, including the context provided
  268. by the vector database's doc retrieval.
  269. The only thing the dry run does not consider is the cut-off due to
  270. the `max_tokens` parameter.
  271. :param where: Optional. A dictionary of key-value pairs to filter the database results.
  272. :return: The answer to the query.
  273. """
  274. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  275. answer = self.llm.query(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  276. # Send anonymous telemetry
  277. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("query",))
  278. thread_telemetry.start()
  279. return answer
  280. def chat(self, input_query, config: BaseLlmConfig = None, dry_run=False, where=None):
  281. """
  282. Queries the vector database on the given input query.
  283. Gets relevant doc based on the query and then passes it to an
  284. LLM as context to get the answer.
  285. Maintains the whole conversation in memory.
  286. :param input_query: The query to use.
  287. :param config: Optional. The `LlmConfig` instance to use as configuration options.
  288. This is used for one method call. To persistently use a config, declare it during app init.
  289. :param dry_run: Optional. A dry run does everything except send the resulting prompt to
  290. the LLM. The purpose is to test the prompt, not the response.
  291. You can use it to test your prompt, including the context provided
  292. by the vector database's doc retrieval.
  293. The only thing the dry run does not consider is the cut-off due to
  294. the `max_tokens` parameter.
  295. :param where: Optional. A dictionary of key-value pairs to filter the database results.
  296. :return: The answer to the query.
  297. """
  298. contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
  299. answer = self.llm.chat(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
  300. # Send anonymous telemetry
  301. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("chat",))
  302. thread_telemetry.start()
  303. return answer
  304. def set_collection(self, collection_name):
  305. """
  306. Set the collection to use.
  307. :param collection_name: The name of the collection to use.
  308. """
  309. self.db.set_collection_name(collection_name)
  310. # Create the collection if it does not exist
  311. self.db._get_or_create_collection(collection_name)
  312. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  313. # since the main purpose is the creation.
  314. def count(self) -> int:
  315. """
  316. Count the number of embeddings.
  317. DEPRECATED IN FAVOR OF `db.count()`
  318. :return: The number of embeddings.
  319. """
  320. logging.warning("DEPRECATION WARNING: Please use `db.count()` instead of `count()`.")
  321. return self.db.count()
  322. def reset(self):
  323. """
  324. Resets the database. Deletes all embeddings irreversibly.
  325. `App` does not have to be reinitialized after using this method.
  326. DEPRECATED IN FAVOR OF `db.reset()`
  327. """
  328. # Send anonymous telemetry
  329. thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("reset",))
  330. thread_telemetry.start()
  331. logging.warning("DEPRECATION WARNING: Please use `db.reset()` instead of `reset()`.")
  332. self.db.reset()
  333. @retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
  334. def _send_telemetry_event(self, method: str, extra_metadata: Optional[dict] = None):
  335. if not self.config.collect_metrics:
  336. return
  337. with threading.Lock():
  338. url = "https://api.embedchain.ai/api/v1/telemetry/"
  339. metadata = {
  340. "s_id": self.s_id,
  341. "version": importlib.metadata.version(__package__ or __name__),
  342. "method": method,
  343. "language": "py",
  344. "u_id": self.u_id,
  345. }
  346. if extra_metadata:
  347. metadata.update(extra_metadata)
  348. response = requests.post(url, json={"metadata": metadata})
  349. if response.status_code != 200:
  350. logging.warning(f"Telemetry event failed with status code {response.status_code}")