embedchain.py 27 KB

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