embedchain.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. import hashlib
  2. import json
  3. import logging
  4. import sqlite3
  5. from typing import Any, Dict, List, Optional, Tuple, Union
  6. from dotenv import load_dotenv
  7. from langchain.docstore.document import Document
  8. from embedchain.chunkers.base_chunker import BaseChunker
  9. from embedchain.config import AddConfig, BaseLlmConfig, ChunkerConfig
  10. from embedchain.config.apps.base_app_config import BaseAppConfig
  11. from embedchain.constants import SQLITE_PATH
  12. from embedchain.data_formatter import DataFormatter
  13. from embedchain.embedder.base import BaseEmbedder
  14. from embedchain.helpers.json_serializable import JSONSerializable
  15. from embedchain.llm.base import BaseLlm
  16. from embedchain.loaders.base_loader import BaseLoader
  17. from embedchain.models.data_type import (DataType, DirectDataType,
  18. IndirectDataType, SpecialDataType)
  19. from embedchain.telemetry.posthog import AnonymousTelemetry
  20. from embedchain.utils import detect_datatype, is_valid_json_string
  21. from embedchain.vectordb.base import BaseVectorDB
  22. load_dotenv()
  23. class EmbedChain(JSONSerializable):
  24. def __init__(
  25. self,
  26. config: BaseAppConfig,
  27. llm: BaseLlm,
  28. db: BaseVectorDB = None,
  29. embedder: BaseEmbedder = None,
  30. system_prompt: Optional[str] = None,
  31. ):
  32. """
  33. Initializes the EmbedChain instance, sets up a vector DB client and
  34. creates a collection.
  35. :param config: Configuration just for the app, not the db or llm or embedder.
  36. :type config: BaseAppConfig
  37. :param llm: Instance of the LLM you want to use.
  38. :type llm: BaseLlm
  39. :param db: Instance of the Database to use, defaults to None
  40. :type db: BaseVectorDB, optional
  41. :param embedder: instance of the embedder to use, defaults to None
  42. :type embedder: BaseEmbedder, optional
  43. :param system_prompt: System prompt to use in the llm query, defaults to None
  44. :type system_prompt: Optional[str], optional
  45. :raises ValueError: No database or embedder provided.
  46. """
  47. self.config = config
  48. # Llm
  49. self.llm = llm
  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. # Fetch the history from the database if exists
  68. self.llm.update_history(app_id=self.config.id)
  69. # Attributes that aren't subclass related.
  70. self.user_asks = []
  71. self.chunker: ChunkerConfig = None
  72. # Send anonymous telemetry
  73. self._telemetry_props = {"class": self.__class__.__name__}
  74. self.telemetry = AnonymousTelemetry(enabled=self.config.collect_metrics)
  75. # Establish a connection to the SQLite database
  76. self.connection = sqlite3.connect(SQLITE_PATH, check_same_thread=False)
  77. self.cursor = self.connection.cursor()
  78. # Create the 'data_sources' table if it doesn't exist
  79. self.cursor.execute(
  80. """
  81. CREATE TABLE IF NOT EXISTS data_sources (
  82. pipeline_id TEXT,
  83. hash TEXT,
  84. type TEXT,
  85. value TEXT,
  86. metadata TEXT,
  87. is_uploaded INTEGER DEFAULT 0,
  88. PRIMARY KEY (pipeline_id, hash)
  89. )
  90. """
  91. )
  92. self.connection.commit()
  93. # Send anonymous telemetry
  94. self.telemetry.capture(event_name="init", properties=self._telemetry_props)
  95. @property
  96. def collect_metrics(self):
  97. return self.config.collect_metrics
  98. @collect_metrics.setter
  99. def collect_metrics(self, value):
  100. if not isinstance(value, bool):
  101. raise ValueError(f"Boolean value expected but got {type(value)}.")
  102. self.config.collect_metrics = value
  103. @property
  104. def online(self):
  105. return self.llm.online
  106. @online.setter
  107. def online(self, value):
  108. if not isinstance(value, bool):
  109. raise ValueError(f"Boolean value expected but got {type(value)}.")
  110. self.llm.online = value
  111. def add(
  112. self,
  113. source: Any,
  114. data_type: Optional[DataType] = None,
  115. metadata: Optional[Dict[str, Any]] = None,
  116. config: Optional[AddConfig] = None,
  117. dry_run=False,
  118. loader: Optional[BaseLoader] = None,
  119. chunker: Optional[BaseChunker] = None,
  120. **kwargs: Optional[Dict[str, Any]],
  121. ):
  122. """
  123. Adds the data from the given URL to the vector db.
  124. Loads the data, chunks it, create embedding for each chunk
  125. and then stores the embedding to vector database.
  126. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  127. :type source: Any
  128. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  129. defaults to None
  130. :type data_type: Optional[DataType], optional
  131. :param metadata: Metadata associated with the data source., defaults to None
  132. :type metadata: Optional[Dict[str, Any]], optional
  133. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  134. :type config: Optional[AddConfig], optional
  135. :raises ValueError: Invalid data type
  136. :param dry_run: Optional. A dry run displays the chunks to ensure that the loader and chunker work as intended.
  137. deafaults to False
  138. :return: source_hash, a md5-hash of the source, in hexadecimal representation.
  139. :rtype: str
  140. """
  141. if config is not None:
  142. pass
  143. elif self.chunker is not None:
  144. config = AddConfig(chunker=self.chunker)
  145. else:
  146. config = AddConfig()
  147. try:
  148. DataType(source)
  149. logging.warning(
  150. 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
  151. )
  152. logging.warning(
  153. "Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
  154. )
  155. source, data_type = data_type, source
  156. except ValueError:
  157. pass
  158. if data_type:
  159. try:
  160. data_type = DataType(data_type)
  161. except ValueError:
  162. logging.info(
  163. f"Invalid data_type: '{data_type}', using `custom` instead.\n Check docs to pass the valid data type: `https://docs.embedchain.ai/data-sources/overview`" # noqa: E501
  164. )
  165. data_type = DataType.CUSTOM
  166. if not data_type:
  167. data_type = detect_datatype(source)
  168. # `source_hash` is the md5 hash of the source argument
  169. source_hash = hashlib.md5(str(source).encode("utf-8")).hexdigest()
  170. self.user_asks.append([source, data_type.value, metadata])
  171. data_formatter = DataFormatter(data_type, config, loader, chunker)
  172. documents, metadatas, _ids, new_chunks = self._load_and_embed(
  173. data_formatter.loader, data_formatter.chunker, source, metadata, source_hash, config, dry_run, **kwargs
  174. )
  175. if data_type in {DataType.DOCS_SITE}:
  176. self.is_docs_site_instance = True
  177. # Insert the data into the 'data' table
  178. self.cursor.execute(
  179. """
  180. INSERT OR REPLACE INTO data_sources (hash, pipeline_id, type, value, metadata)
  181. VALUES (?, ?, ?, ?, ?)
  182. """,
  183. (source_hash, self.config.id, data_type.value, str(source), json.dumps(metadata)),
  184. )
  185. # Commit the transaction
  186. self.connection.commit()
  187. if dry_run:
  188. data_chunks_info = {"chunks": documents, "metadata": metadatas, "count": len(documents), "type": data_type}
  189. logging.debug(f"Dry run info : {data_chunks_info}")
  190. return data_chunks_info
  191. # Send anonymous telemetry
  192. if self.config.collect_metrics:
  193. # it's quicker to check the variable twice than to count words when they won't be submitted.
  194. word_count = data_formatter.chunker.get_word_count(documents)
  195. # Send anonymous telemetry
  196. event_properties = {
  197. **self._telemetry_props,
  198. "data_type": data_type.value,
  199. "word_count": word_count,
  200. "chunks_count": new_chunks,
  201. }
  202. self.telemetry.capture(event_name="add", properties=event_properties)
  203. return source_hash
  204. def add_local(
  205. self,
  206. source: Any,
  207. data_type: Optional[DataType] = None,
  208. metadata: Optional[Dict[str, Any]] = None,
  209. config: Optional[AddConfig] = None,
  210. **kwargs: Optional[Dict[str, Any]],
  211. ):
  212. """
  213. Adds the data from the given URL to the vector db.
  214. Loads the data, chunks it, create embedding for each chunk
  215. and then stores the embedding to vector database.
  216. Warning:
  217. This method is deprecated and will be removed in future versions. Use `add` instead.
  218. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  219. :type source: Any
  220. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  221. defaults to None
  222. :type data_type: Optional[DataType], optional
  223. :param metadata: Metadata associated with the data source., defaults to None
  224. :type metadata: Optional[Dict[str, Any]], optional
  225. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  226. :type config: Optional[AddConfig], optional
  227. :raises ValueError: Invalid data type
  228. :return: source_hash, a md5-hash of the source, in hexadecimal representation.
  229. :rtype: str
  230. """
  231. logging.warning(
  232. "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
  233. )
  234. return self.add(
  235. source=source,
  236. data_type=data_type,
  237. metadata=metadata,
  238. config=config,
  239. **kwargs,
  240. )
  241. def _get_existing_doc_id(self, chunker: BaseChunker, src: Any):
  242. """
  243. Get id of existing document for a given source, based on the data type
  244. """
  245. # Find existing embeddings for the source
  246. # Depending on the data type, existing embeddings are checked for.
  247. if chunker.data_type.value in [item.value for item in DirectDataType]:
  248. # DirectDataTypes can't be updated.
  249. # Think of a text:
  250. # Either it's the same, then it won't change, so it's not an update.
  251. # Or it's different, then it will be added as a new text.
  252. return None
  253. elif chunker.data_type.value in [item.value for item in IndirectDataType]:
  254. # These types have a indirect source reference
  255. # As long as the reference is the same, they can be updated.
  256. where = {"url": src}
  257. if chunker.data_type == DataType.JSON and is_valid_json_string(src):
  258. url = hashlib.sha256((src).encode("utf-8")).hexdigest()
  259. where = {"url": url}
  260. if self.config.id is not None:
  261. where.update({"app_id": self.config.id})
  262. existing_embeddings = self.db.get(
  263. where=where,
  264. limit=1,
  265. )
  266. if len(existing_embeddings.get("metadatas", [])) > 0:
  267. return existing_embeddings["metadatas"][0]["doc_id"]
  268. else:
  269. return None
  270. elif chunker.data_type.value in [item.value for item in SpecialDataType]:
  271. # These types don't contain indirect references.
  272. # Through custom logic, they can be attributed to a source and be updated.
  273. if chunker.data_type == DataType.QNA_PAIR:
  274. # QNA_PAIRs update the answer if the question already exists.
  275. where = {"question": src[0]}
  276. if self.config.id is not None:
  277. where.update({"app_id": self.config.id})
  278. existing_embeddings = self.db.get(
  279. where=where,
  280. limit=1,
  281. )
  282. if len(existing_embeddings.get("metadatas", [])) > 0:
  283. return existing_embeddings["metadatas"][0]["doc_id"]
  284. else:
  285. return None
  286. else:
  287. raise NotImplementedError(
  288. f"SpecialDataType {chunker.data_type} must have a custom logic to check for existing data"
  289. )
  290. else:
  291. raise TypeError(
  292. f"{chunker.data_type} is type {type(chunker.data_type)}. "
  293. "When it should be DirectDataType, IndirectDataType or SpecialDataType."
  294. )
  295. def _load_and_embed(
  296. self,
  297. loader: BaseLoader,
  298. chunker: BaseChunker,
  299. src: Any,
  300. metadata: Optional[Dict[str, Any]] = None,
  301. source_hash: Optional[str] = None,
  302. add_config: Optional[AddConfig] = None,
  303. dry_run=False,
  304. **kwargs: Optional[Dict[str, Any]],
  305. ):
  306. """
  307. Loads the data from the given URL, chunks it, and adds it to database.
  308. :param loader: The loader to use to load the data.
  309. :param chunker: The chunker to use to chunk the data.
  310. :param src: The data to be handled by the loader. Can be a URL for
  311. remote sources or local content for local loaders.
  312. :param metadata: Optional. Metadata associated with the data source.
  313. :param source_hash: Hexadecimal hash of the source.
  314. :param dry_run: Optional. A dry run returns chunks and doesn't update DB.
  315. :type dry_run: bool, defaults to False
  316. :return: (List) documents (embedded text), (List) metadata, (list) ids, (int) number of chunks
  317. """
  318. existing_doc_id = self._get_existing_doc_id(chunker=chunker, src=src)
  319. app_id = self.config.id if self.config is not None else None
  320. # Create chunks
  321. embeddings_data = chunker.create_chunks(loader, src, app_id=app_id, config=add_config.chunker)
  322. # spread chunking results
  323. documents = embeddings_data["documents"]
  324. metadatas = embeddings_data["metadatas"]
  325. ids = embeddings_data["ids"]
  326. new_doc_id = embeddings_data["doc_id"]
  327. embeddings = embeddings_data.get("embeddings")
  328. if existing_doc_id and existing_doc_id == new_doc_id:
  329. print("Doc content has not changed. Skipping creating chunks and embeddings")
  330. return [], [], [], 0
  331. # this means that doc content has changed.
  332. if existing_doc_id and existing_doc_id != new_doc_id:
  333. print("Doc content has changed. Recomputing chunks and embeddings intelligently.")
  334. self.db.delete({"doc_id": existing_doc_id})
  335. # get existing ids, and discard doc if any common id exist.
  336. where = {"url": src}
  337. if chunker.data_type == DataType.JSON and is_valid_json_string(src):
  338. url = hashlib.sha256((src).encode("utf-8")).hexdigest()
  339. where = {"url": url}
  340. # if data type is qna_pair, we check for question
  341. if chunker.data_type == DataType.QNA_PAIR:
  342. where = {"question": src[0]}
  343. if self.config.id is not None:
  344. where["app_id"] = self.config.id
  345. db_result = self.db.get(ids=ids, where=where) # optional filter
  346. existing_ids = set(db_result["ids"])
  347. if len(existing_ids):
  348. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  349. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  350. if not data_dict:
  351. src_copy = src
  352. if len(src_copy) > 50:
  353. src_copy = src[:50] + "..."
  354. print(f"All data from {src_copy} already exists in the database.")
  355. # Make sure to return a matching return type
  356. return [], [], [], 0
  357. ids = list(data_dict.keys())
  358. documents, metadatas = zip(*data_dict.values())
  359. # Loop though all metadatas and add extras.
  360. new_metadatas = []
  361. for m in metadatas:
  362. # Add app id in metadatas so that they can be queried on later
  363. if self.config.id:
  364. m["app_id"] = self.config.id
  365. # Add hashed source
  366. m["hash"] = source_hash
  367. # Note: Metadata is the function argument
  368. if metadata:
  369. # Spread whatever is in metadata into the new object.
  370. m.update(metadata)
  371. new_metadatas.append(m)
  372. metadatas = new_metadatas
  373. if dry_run:
  374. return list(documents), metadatas, ids, 0
  375. # Count before, to calculate a delta in the end.
  376. chunks_before_addition = self.db.count()
  377. self.db.add(
  378. embeddings=embeddings,
  379. documents=documents,
  380. metadatas=metadatas,
  381. ids=ids,
  382. skip_embedding=(chunker.data_type == DataType.IMAGES),
  383. **kwargs,
  384. )
  385. count_new_chunks = self.db.count() - chunks_before_addition
  386. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  387. return list(documents), metadatas, ids, count_new_chunks
  388. def _format_result(self, results):
  389. return [
  390. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  391. for result in zip(
  392. results["documents"][0],
  393. results["metadatas"][0],
  394. results["distances"][0],
  395. )
  396. ]
  397. def _retrieve_from_database(
  398. self,
  399. input_query: str,
  400. config: Optional[BaseLlmConfig] = None,
  401. where=None,
  402. citations: bool = False,
  403. **kwargs: Optional[Dict[str, Any]],
  404. ) -> Union[List[Tuple[str, str, str]], List[str]]:
  405. """
  406. Queries the vector database based on the given input query.
  407. Gets relevant doc based on the query
  408. :param input_query: The query to use.
  409. :type input_query: str
  410. :param config: The query configuration, defaults to None
  411. :type config: Optional[BaseLlmConfig], optional
  412. :param where: A dictionary of key-value pairs to filter the database results, defaults to None
  413. :type where: _type_, optional
  414. :param citations: A boolean to indicate if db should fetch citation source
  415. :type citations: bool
  416. :return: List of contents of the document that matched your query
  417. :rtype: List[str]
  418. """
  419. query_config = config or self.llm.config
  420. if where is not None:
  421. where = where
  422. else:
  423. where = {}
  424. if query_config is not None and query_config.where is not None:
  425. where = query_config.where
  426. if self.config.id is not None:
  427. where.update({"app_id": self.config.id})
  428. # We cannot query the database with the input query in case of an image search. This is because we need
  429. # to bring down both the image and text to the same dimension to be able to compare them.
  430. db_query = input_query
  431. if hasattr(config, "query_type") and config.query_type == "Images":
  432. # We import the clip processor here to make sure the package is not dependent on clip dependency even if the
  433. # image dataset is not being used
  434. from embedchain.models.clip_processor import ClipProcessor
  435. db_query = ClipProcessor.get_text_features(query=input_query)
  436. contexts = self.db.query(
  437. input_query=db_query,
  438. n_results=query_config.number_documents,
  439. where=where,
  440. skip_embedding=(hasattr(config, "query_type") and config.query_type == "Images"),
  441. citations=citations,
  442. **kwargs,
  443. )
  444. return contexts
  445. def query(
  446. self,
  447. input_query: str,
  448. config: BaseLlmConfig = None,
  449. dry_run=False,
  450. where: Optional[Dict] = None,
  451. citations: bool = False,
  452. **kwargs: Dict[str, Any],
  453. ) -> Union[Tuple[str, List[Tuple[str, str, str]]], str]:
  454. """
  455. Queries the vector database based on the given input query.
  456. Gets relevant doc based on the query and then passes it to an
  457. LLM as context to get the answer.
  458. :param input_query: The query to use.
  459. :type input_query: str
  460. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  461. To persistently use a config, declare it during app init., defaults to None
  462. :type config: Optional[BaseLlmConfig], optional
  463. :param dry_run: A dry run does everything except send the resulting prompt to
  464. the LLM. The purpose is to test the prompt, not the response., defaults to False
  465. :type dry_run: bool, optional
  466. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  467. :type where: Optional[Dict[str, str]], optional
  468. :param kwargs: To read more params for the query function. Ex. we use citations boolean
  469. param to return context along with the answer
  470. :type kwargs: Dict[str, Any]
  471. :return: The answer to the query, with citations if the citation flag is True
  472. or the dry run result
  473. :rtype: str, if citations is False, otherwise Tuple[str,List[Tuple[str,str,str]]]
  474. """
  475. contexts = self._retrieve_from_database(
  476. input_query=input_query, config=config, where=where, citations=citations, **kwargs
  477. )
  478. if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
  479. contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
  480. else:
  481. contexts_data_for_llm_query = contexts
  482. answer = self.llm.query(
  483. input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
  484. )
  485. # Send anonymous telemetry
  486. self.telemetry.capture(event_name="query", properties=self._telemetry_props)
  487. if citations:
  488. return answer, contexts
  489. else:
  490. return answer
  491. def chat(
  492. self,
  493. input_query: str,
  494. config: Optional[BaseLlmConfig] = None,
  495. dry_run=False,
  496. where: Optional[Dict[str, str]] = None,
  497. citations: bool = False,
  498. **kwargs: Dict[str, Any],
  499. ) -> Union[Tuple[str, List[Tuple[str, str, str]]], str]:
  500. """
  501. Queries the vector database on the given input query.
  502. Gets relevant doc based on the query and then passes it to an
  503. LLM as context to get the answer.
  504. Maintains the whole conversation in memory.
  505. :param input_query: The query to use.
  506. :type input_query: str
  507. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  508. To persistently use a config, declare it during app init., defaults to None
  509. :type config: Optional[BaseLlmConfig], optional
  510. :param dry_run: A dry run does everything except send the resulting prompt to
  511. the LLM. The purpose is to test the prompt, not the response., defaults to False
  512. :type dry_run: bool, optional
  513. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  514. :type where: Optional[Dict[str, str]], optional
  515. :param kwargs: To read more params for the query function. Ex. we use citations boolean
  516. param to return context along with the answer
  517. :type kwargs: Dict[str, Any]
  518. :return: The answer to the query, with citations if the citation flag is True
  519. or the dry run result
  520. :rtype: str, if citations is False, otherwise Tuple[str,List[Tuple[str,str,str]]]
  521. """
  522. contexts = self._retrieve_from_database(
  523. input_query=input_query, config=config, where=where, citations=citations, **kwargs
  524. )
  525. if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
  526. contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
  527. else:
  528. contexts_data_for_llm_query = contexts
  529. answer = self.llm.chat(
  530. input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
  531. )
  532. # add conversation in memory
  533. self.llm.add_history(self.config.id, input_query, answer)
  534. # Send anonymous telemetry
  535. self.telemetry.capture(event_name="chat", properties=self._telemetry_props)
  536. if citations:
  537. return answer, contexts
  538. else:
  539. return answer
  540. def set_collection_name(self, name: str):
  541. """
  542. Set the name of the collection. A collection is an isolated space for vectors.
  543. Using `app.db.set_collection_name` method is preferred to this.
  544. :param name: Name of the collection.
  545. :type name: str
  546. """
  547. self.db.set_collection_name(name)
  548. # Create the collection if it does not exist
  549. self.db._get_or_create_collection(name)
  550. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  551. # since the main purpose is the creation.
  552. def count(self) -> int:
  553. """
  554. Count the number of embeddings.
  555. DEPRECATED IN FAVOR OF `db.count()`
  556. :return: The number of embeddings.
  557. :rtype: int
  558. """
  559. logging.warning("DEPRECATION WARNING: Please use `app.db.count()` instead of `app.count()`.")
  560. return self.db.count()
  561. def reset(self):
  562. """
  563. Resets the database. Deletes all embeddings irreversibly.
  564. `App` does not have to be reinitialized after using this method.
  565. """
  566. self.db.reset()
  567. self.cursor.execute("DELETE FROM data_sources WHERE pipeline_id = ?", (self.config.id,))
  568. self.connection.commit()
  569. self.delete_chat_history()
  570. # Send anonymous telemetry
  571. self.telemetry.capture(event_name="reset", properties=self._telemetry_props)
  572. def get_history(self, num_rounds: int = 10, display_format: bool = True):
  573. return self.llm.memory.get_recent_memories(
  574. app_id=self.config.id,
  575. num_rounds=num_rounds,
  576. display_format=display_format,
  577. )
  578. def delete_chat_history(self):
  579. self.llm.memory.delete_chat_history(app_id=self.config.id)
  580. self.llm.update_history(app_id=self.config.id)