embedchain.py 27 KB

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