embedchain.py 27 KB

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