embedchain.py 26 KB

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