embedchain.py 28 KB

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