embedchain.py 27 KB

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