embedchain.py 29 KB

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