embedchain.py 27 KB

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