embedchain.py 28 KB

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