embedchain.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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.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: 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 a 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. embeddings = embeddings_data.get("embeddings")
  332. if existing_doc_id and existing_doc_id == new_doc_id:
  333. print("Doc content has not changed. Skipping creating chunks and embeddings")
  334. return [], [], [], 0
  335. # this means that doc content has changed.
  336. if existing_doc_id and existing_doc_id != new_doc_id:
  337. print("Doc content has changed. Recomputing chunks and embeddings intelligently.")
  338. self.db.delete({"doc_id": existing_doc_id})
  339. # get existing ids, and discard doc if any common id exist.
  340. where = {"url": src}
  341. if chunker.data_type == DataType.JSON and is_valid_json_string(src):
  342. url = hashlib.sha256((src).encode("utf-8")).hexdigest()
  343. where = {"url": url}
  344. # if data type is qna_pair, we check for question
  345. if chunker.data_type == DataType.QNA_PAIR:
  346. where = {"question": src[0]}
  347. if self.config.id is not None:
  348. where["app_id"] = self.config.id
  349. db_result = self.db.get(ids=ids, where=where) # optional filter
  350. existing_ids = set(db_result["ids"])
  351. if len(existing_ids):
  352. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  353. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  354. if not data_dict:
  355. src_copy = src
  356. if len(src_copy) > 50:
  357. src_copy = src[:50] + "..."
  358. print(f"All data from {src_copy} already exists in the database.")
  359. # Make sure to return a matching return type
  360. return [], [], [], 0
  361. ids = list(data_dict.keys())
  362. documents, metadatas = zip(*data_dict.values())
  363. # Loop though all metadatas and add extras.
  364. new_metadatas = []
  365. for m in metadatas:
  366. # Add app id in metadatas so that they can be queried on later
  367. if self.config.id:
  368. m["app_id"] = self.config.id
  369. # Add hashed source
  370. m["hash"] = source_hash
  371. # Note: Metadata is the function argument
  372. if metadata:
  373. # Spread whatever is in metadata into the new object.
  374. m.update(metadata)
  375. new_metadatas.append(m)
  376. metadatas = new_metadatas
  377. if dry_run:
  378. return list(documents), metadatas, ids, 0
  379. # Count before, to calculate a delta in the end.
  380. chunks_before_addition = self.db.count()
  381. self.db.add(
  382. embeddings=embeddings,
  383. documents=documents,
  384. metadatas=metadatas,
  385. ids=ids,
  386. **kwargs,
  387. )
  388. count_new_chunks = self.db.count() - chunks_before_addition
  389. print((f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}"))
  390. return list(documents), metadatas, ids, count_new_chunks
  391. def _format_result(self, results):
  392. return [
  393. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  394. for result in zip(
  395. results["documents"][0],
  396. results["metadatas"][0],
  397. results["distances"][0],
  398. )
  399. ]
  400. def _retrieve_from_database(
  401. self,
  402. input_query: str,
  403. config: Optional[BaseLlmConfig] = None,
  404. where=None,
  405. citations: bool = False,
  406. **kwargs: Optional[Dict[str, Any]],
  407. ) -> Union[List[Tuple[str, str, str]], List[str]]:
  408. """
  409. Queries the vector database based on the given input query.
  410. Gets relevant doc based on the query
  411. :param input_query: The query to use.
  412. :type input_query: str
  413. :param config: The query configuration, defaults to None
  414. :type config: Optional[BaseLlmConfig], optional
  415. :param where: A dictionary of key-value pairs to filter the database results, defaults to None
  416. :type where: _type_, optional
  417. :param citations: A boolean to indicate if db should fetch citation source
  418. :type citations: bool
  419. :return: List of contents of the document that matched your query
  420. :rtype: List[str]
  421. """
  422. query_config = config or self.llm.config
  423. if where is not None:
  424. where = where
  425. else:
  426. where = {}
  427. if query_config is not None and query_config.where is not None:
  428. where = query_config.where
  429. if self.config.id is not None:
  430. where.update({"app_id": self.config.id})
  431. contexts = self.db.query(
  432. input_query=input_query,
  433. n_results=query_config.number_documents,
  434. where=where,
  435. citations=citations,
  436. **kwargs,
  437. )
  438. return contexts
  439. def query(
  440. self,
  441. input_query: str,
  442. config: BaseLlmConfig = None,
  443. dry_run=False,
  444. where: Optional[Dict] = None,
  445. citations: bool = False,
  446. **kwargs: Dict[str, Any],
  447. ) -> Union[Tuple[str, List[Tuple[str, Dict]]], str]:
  448. """
  449. Queries the vector database based on the given input query.
  450. Gets relevant doc based on the query and then passes it to an
  451. LLM as context to get the answer.
  452. :param input_query: The query to use.
  453. :type input_query: str
  454. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  455. To persistently use a config, declare it during app init., defaults to None
  456. :type config: Optional[BaseLlmConfig], optional
  457. :param dry_run: A dry run does everything except send the resulting prompt to
  458. the LLM. The purpose is to test the prompt, not the response., defaults to False
  459. :type dry_run: bool, optional
  460. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  461. :type where: Optional[Dict[str, str]], optional
  462. :param kwargs: To read more params for the query function. Ex. we use citations boolean
  463. param to return context along with the answer
  464. :type kwargs: Dict[str, Any]
  465. :return: The answer to the query, with citations if the citation flag is True
  466. or the dry run result
  467. :rtype: str, if citations is False, otherwise Tuple[str,List[Tuple[str,str,str]]]
  468. """
  469. contexts = self._retrieve_from_database(
  470. input_query=input_query, config=config, where=where, citations=citations, **kwargs
  471. )
  472. if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
  473. contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
  474. else:
  475. contexts_data_for_llm_query = contexts
  476. if self.cache_config is not None:
  477. logging.info("Cache enabled. Checking cache...")
  478. answer = adapt(
  479. llm_handler=self.llm.query,
  480. cache_data_convert=gptcache_data_convert,
  481. update_cache_callback=gptcache_update_cache_callback,
  482. session=get_gptcache_session(session_id=self.config.id),
  483. input_query=input_query,
  484. contexts=contexts_data_for_llm_query,
  485. config=config,
  486. dry_run=dry_run,
  487. )
  488. else:
  489. answer = self.llm.query(
  490. input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
  491. )
  492. # Send anonymous telemetry
  493. self.telemetry.capture(event_name="query", properties=self._telemetry_props)
  494. if citations:
  495. return answer, contexts
  496. else:
  497. return answer
  498. def chat(
  499. self,
  500. input_query: str,
  501. config: Optional[BaseLlmConfig] = None,
  502. dry_run=False,
  503. session_id: str = "default",
  504. where: Optional[Dict[str, str]] = None,
  505. citations: bool = False,
  506. **kwargs: Dict[str, Any],
  507. ) -> Union[Tuple[str, List[Tuple[str, Dict]]], str]:
  508. """
  509. Queries the vector database on the given input query.
  510. Gets relevant doc based on the query and then passes it to an
  511. LLM as context to get the answer.
  512. Maintains the whole conversation in memory.
  513. :param input_query: The query to use.
  514. :type input_query: str
  515. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  516. To persistently use a config, declare it during app init., defaults to None
  517. :type config: Optional[BaseLlmConfig], optional
  518. :param dry_run: A dry run does everything except send the resulting prompt to
  519. the LLM. The purpose is to test the prompt, not the response., defaults to False
  520. :type dry_run: bool, optional
  521. :param session_id: The session id to use for chat history, defaults to 'default'.
  522. :type session_id: Optional[str], optional
  523. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  524. :type where: Optional[Dict[str, str]], optional
  525. :param kwargs: To read more params for the query function. Ex. we use citations boolean
  526. param to return context along with the answer
  527. :type kwargs: Dict[str, Any]
  528. :return: The answer to the query, with citations if the citation flag is True
  529. or the dry run result
  530. :rtype: str, if citations is False, otherwise Tuple[str,List[Tuple[str,str,str]]]
  531. """
  532. contexts = self._retrieve_from_database(
  533. input_query=input_query, config=config, where=where, citations=citations, **kwargs
  534. )
  535. if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
  536. contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
  537. else:
  538. contexts_data_for_llm_query = contexts
  539. # Update the history beforehand so that we can handle multiple chat sessions in the same python session
  540. self.llm.update_history(app_id=self.config.id, session_id=session_id)
  541. if self.cache_config is not None:
  542. logging.info("Cache enabled. Checking cache...")
  543. cache_id = f"{session_id}--{self.config.id}"
  544. answer = adapt(
  545. llm_handler=self.llm.chat,
  546. cache_data_convert=gptcache_data_convert,
  547. update_cache_callback=gptcache_update_cache_callback,
  548. session=get_gptcache_session(session_id=cache_id),
  549. input_query=input_query,
  550. contexts=contexts_data_for_llm_query,
  551. config=config,
  552. dry_run=dry_run,
  553. )
  554. else:
  555. answer = self.llm.chat(
  556. input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
  557. )
  558. # add conversation in memory
  559. self.llm.add_history(self.config.id, input_query, answer, session_id=session_id)
  560. # Send anonymous telemetry
  561. self.telemetry.capture(event_name="chat", properties=self._telemetry_props)
  562. if citations:
  563. return answer, contexts
  564. else:
  565. return answer
  566. def set_collection_name(self, name: str):
  567. """
  568. Set the name of the collection. A collection is an isolated space for vectors.
  569. Using `app.db.set_collection_name` method is preferred to this.
  570. :param name: Name of the collection.
  571. :type name: str
  572. """
  573. self.db.set_collection_name(name)
  574. # Create the collection if it does not exist
  575. self.db._get_or_create_collection(name)
  576. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  577. # since the main purpose is the creation.
  578. def reset(self):
  579. """
  580. Resets the database. Deletes all embeddings irreversibly.
  581. `App` does not have to be reinitialized after using this method.
  582. """
  583. self.db.reset()
  584. self.cursor.execute("DELETE FROM data_sources WHERE pipeline_id = ?", (self.config.id,))
  585. self.connection.commit()
  586. self.delete_chat_history()
  587. # Send anonymous telemetry
  588. self.telemetry.capture(event_name="reset", properties=self._telemetry_props)
  589. def get_history(self, num_rounds: int = 10, display_format: bool = True):
  590. return self.llm.memory.get(app_id=self.config.id, num_rounds=num_rounds, display_format=display_format)
  591. def delete_chat_history(self, session_id: str = "default"):
  592. self.llm.memory.delete(app_id=self.config.id, session_id=session_id)
  593. self.llm.update_history(app_id=self.config.id)