embedchain.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. import hashlib
  2. import json
  3. import logging
  4. from typing import Any, Optional, Union
  5. from dotenv import load_dotenv
  6. from langchain.docstore.document import Document
  7. from embedchain.cache import adapt, get_gptcache_session, gptcache_data_convert, gptcache_update_cache_callback
  8. from embedchain.chunkers.base_chunker import BaseChunker
  9. from embedchain.config import AddConfig, BaseLlmConfig, ChunkerConfig
  10. from embedchain.config.base_app_config import BaseAppConfig
  11. from embedchain.core.db.models import DataSource
  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, IndirectDataType, SpecialDataType
  18. from embedchain.utils.misc import detect_datatype, is_valid_json_string
  19. from embedchain.vectordb.base import BaseVectorDB
  20. load_dotenv()
  21. class EmbedChain(JSONSerializable):
  22. def __init__(
  23. self,
  24. config: BaseAppConfig,
  25. llm: BaseLlm,
  26. db: BaseVectorDB = None,
  27. embedder: BaseEmbedder = None,
  28. system_prompt: Optional[str] = None,
  29. ):
  30. """
  31. Initializes the EmbedChain instance, sets up a vector DB client and
  32. creates a collection.
  33. :param config: Configuration just for the app, not the db or llm or embedder.
  34. :type config: BaseAppConfig
  35. :param llm: Instance of the LLM you want to use.
  36. :type llm: BaseLlm
  37. :param db: Instance of the Database to use, defaults to None
  38. :type db: BaseVectorDB, optional
  39. :param embedder: instance of the embedder to use, defaults to None
  40. :type embedder: BaseEmbedder, optional
  41. :param system_prompt: System prompt to use in the llm query, defaults to None
  42. :type system_prompt: Optional[str], optional
  43. :raises ValueError: No database or embedder provided.
  44. """
  45. self.config = config
  46. self.cache_config = None
  47. # Llm
  48. self.llm = llm
  49. # Database has support for config assignment for backwards compatibility
  50. if db is None and (not hasattr(self.config, "db") or self.config.db is None):
  51. raise ValueError("App requires Database.")
  52. self.db = db or self.config.db
  53. # Embedder
  54. if embedder is None:
  55. raise ValueError("App requires Embedder.")
  56. self.embedder = embedder
  57. # Initialize database
  58. self.db._set_embedder(self.embedder)
  59. self.db._initialize()
  60. # Set collection name from app config for backwards compatibility.
  61. if config.collection_name:
  62. self.db.set_collection_name(config.collection_name)
  63. # Add variables that are "shortcuts"
  64. if system_prompt:
  65. self.llm.config.system_prompt = system_prompt
  66. # Fetch the history from the database if exists
  67. self.llm.update_history(app_id=self.config.id)
  68. # Attributes that aren't subclass related.
  69. self.user_asks = []
  70. self.chunker: Optional[ChunkerConfig] = None
  71. @property
  72. def collect_metrics(self):
  73. return self.config.collect_metrics
  74. @collect_metrics.setter
  75. def collect_metrics(self, value):
  76. if not isinstance(value, bool):
  77. raise ValueError(f"Boolean value expected but got {type(value)}.")
  78. self.config.collect_metrics = value
  79. @property
  80. def online(self):
  81. return self.llm.online
  82. @online.setter
  83. def online(self, value):
  84. if not isinstance(value, bool):
  85. raise ValueError(f"Boolean value expected but got {type(value)}.")
  86. self.llm.online = value
  87. def add(
  88. self,
  89. source: Any,
  90. data_type: Optional[DataType] = None,
  91. metadata: Optional[dict[str, Any]] = None,
  92. config: Optional[AddConfig] = None,
  93. dry_run=False,
  94. loader: Optional[BaseLoader] = None,
  95. chunker: Optional[BaseChunker] = None,
  96. **kwargs: Optional[dict[str, Any]],
  97. ):
  98. """
  99. Adds the data from the given URL to the vector db.
  100. Loads the data, chunks it, create embedding for each chunk
  101. and then stores the embedding to vector database.
  102. :param source: The data to embed, can be a URL, local file or raw content, depending on the data type.
  103. :type source: Any
  104. :param data_type: Automatically detected, but can be forced with this argument. The type of the data to add,
  105. defaults to None
  106. :type data_type: Optional[DataType], optional
  107. :param metadata: Metadata associated with the data source., defaults to None
  108. :type metadata: Optional[dict[str, Any]], optional
  109. :param config: The `AddConfig` instance to use as configuration options., defaults to None
  110. :type config: Optional[AddConfig], optional
  111. :raises ValueError: Invalid data type
  112. :param dry_run: Optional. A dry run displays the chunks to ensure that the loader and chunker work as intended.
  113. deafaults to False
  114. :return: source_hash, a md5-hash of the source, in hexadecimal representation.
  115. :rtype: str
  116. """
  117. if config is not None:
  118. pass
  119. elif self.chunker is not None:
  120. config = AddConfig(chunker=self.chunker)
  121. else:
  122. config = AddConfig()
  123. try:
  124. DataType(source)
  125. logging.warning(
  126. 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
  127. )
  128. logging.warning(
  129. "Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
  130. )
  131. source, data_type = data_type, source
  132. except ValueError:
  133. pass
  134. if data_type:
  135. try:
  136. data_type = DataType(data_type)
  137. except ValueError:
  138. logging.info(
  139. 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
  140. )
  141. data_type = DataType.CUSTOM
  142. if not data_type:
  143. data_type = detect_datatype(source)
  144. # `source_hash` is the md5 hash of the source argument
  145. source_hash = hashlib.md5(str(source).encode("utf-8")).hexdigest()
  146. self.user_asks.append([source, data_type.value, metadata])
  147. data_formatter = DataFormatter(data_type, config, loader, chunker)
  148. documents, metadatas, _ids, new_chunks = self._load_and_embed(
  149. data_formatter.loader, data_formatter.chunker, source, metadata, source_hash, config, dry_run, **kwargs
  150. )
  151. if data_type in {DataType.DOCS_SITE}:
  152. self.is_docs_site_instance = True
  153. # Insert the data into the 'ec_data_sources' table
  154. self.db_session.add(
  155. DataSource(
  156. hash=source_hash,
  157. app_id=self.config.id,
  158. type=data_type.value,
  159. value=source,
  160. metadata=json.dumps(metadata),
  161. )
  162. )
  163. try:
  164. self.db_session.commit()
  165. except Exception as e:
  166. logging.error(f"Error adding data source: {e}")
  167. self.db_session.rollback()
  168. if dry_run:
  169. data_chunks_info = {"chunks": documents, "metadata": metadatas, "count": len(documents), "type": data_type}
  170. logging.debug(f"Dry run info : {data_chunks_info}")
  171. return data_chunks_info
  172. # Send anonymous telemetry
  173. if self.config.collect_metrics:
  174. # it's quicker to check the variable twice than to count words when they won't be submitted.
  175. word_count = data_formatter.chunker.get_word_count(documents)
  176. # Send anonymous telemetry
  177. event_properties = {
  178. **self._telemetry_props,
  179. "data_type": data_type.value,
  180. "word_count": word_count,
  181. "chunks_count": new_chunks,
  182. }
  183. self.telemetry.capture(event_name="add", properties=event_properties)
  184. return source_hash
  185. def _get_existing_doc_id(self, chunker: BaseChunker, src: Any):
  186. """
  187. Get id of existing document for a given source, based on the data type
  188. """
  189. # Find existing embeddings for the source
  190. # Depending on the data type, existing embeddings are checked for.
  191. if chunker.data_type.value in [item.value for item in DirectDataType]:
  192. # DirectDataTypes can't be updated.
  193. # Think of a text:
  194. # Either it's the same, then it won't change, so it's not an update.
  195. # Or it's different, then it will be added as a new text.
  196. return None
  197. elif chunker.data_type.value in [item.value for item in IndirectDataType]:
  198. # These types have an indirect source reference
  199. # As long as the reference is the same, they can be updated.
  200. where = {"url": src}
  201. if chunker.data_type == DataType.JSON and is_valid_json_string(src):
  202. url = hashlib.sha256((src).encode("utf-8")).hexdigest()
  203. where = {"url": url}
  204. if self.config.id is not None:
  205. where.update({"app_id": self.config.id})
  206. existing_embeddings = self.db.get(
  207. where=where,
  208. limit=1,
  209. )
  210. if len(existing_embeddings.get("metadatas", [])) > 0:
  211. return existing_embeddings["metadatas"][0]["doc_id"]
  212. else:
  213. return None
  214. elif chunker.data_type.value in [item.value for item in SpecialDataType]:
  215. # These types don't contain indirect references.
  216. # Through custom logic, they can be attributed to a source and be updated.
  217. if chunker.data_type == DataType.QNA_PAIR:
  218. # QNA_PAIRs update the answer if the question already exists.
  219. where = {"question": src[0]}
  220. if self.config.id is not None:
  221. where.update({"app_id": self.config.id})
  222. existing_embeddings = self.db.get(
  223. where=where,
  224. limit=1,
  225. )
  226. if len(existing_embeddings.get("metadatas", [])) > 0:
  227. return existing_embeddings["metadatas"][0]["doc_id"]
  228. else:
  229. return None
  230. else:
  231. raise NotImplementedError(
  232. f"SpecialDataType {chunker.data_type} must have a custom logic to check for existing data"
  233. )
  234. else:
  235. raise TypeError(
  236. f"{chunker.data_type} is type {type(chunker.data_type)}. "
  237. "When it should be DirectDataType, IndirectDataType or SpecialDataType."
  238. )
  239. def _load_and_embed(
  240. self,
  241. loader: BaseLoader,
  242. chunker: BaseChunker,
  243. src: Any,
  244. metadata: Optional[dict[str, Any]] = None,
  245. source_hash: Optional[str] = None,
  246. add_config: Optional[AddConfig] = None,
  247. dry_run=False,
  248. **kwargs: Optional[dict[str, Any]],
  249. ):
  250. """
  251. Loads the data from the given URL, chunks it, and adds it to database.
  252. :param loader: The loader to use to load the data.
  253. :param chunker: The chunker to use to chunk the data.
  254. :param src: The data to be handled by the loader. Can be a URL for
  255. remote sources or local content for local loaders.
  256. :param metadata: Optional. Metadata associated with the data source.
  257. :param source_hash: Hexadecimal hash of the source.
  258. :param dry_run: Optional. A dry run returns chunks and doesn't update DB.
  259. :type dry_run: bool, defaults to False
  260. :return: (list) documents (embedded text), (list) metadata, (list) ids, (int) number of chunks
  261. """
  262. existing_doc_id = self._get_existing_doc_id(chunker=chunker, src=src)
  263. app_id = self.config.id if self.config is not None else None
  264. # Create chunks
  265. embeddings_data = chunker.create_chunks(loader, src, app_id=app_id, config=add_config.chunker)
  266. # spread chunking results
  267. documents = embeddings_data["documents"]
  268. metadatas = embeddings_data["metadatas"]
  269. ids = embeddings_data["ids"]
  270. new_doc_id = embeddings_data["doc_id"]
  271. if existing_doc_id and existing_doc_id == new_doc_id:
  272. print("Doc content has not changed. Skipping creating chunks and embeddings")
  273. return [], [], [], 0
  274. # this means that doc content has changed.
  275. if existing_doc_id and existing_doc_id != new_doc_id:
  276. print("Doc content has changed. Recomputing chunks and embeddings intelligently.")
  277. self.db.delete({"doc_id": existing_doc_id})
  278. # get existing ids, and discard doc if any common id exist.
  279. where = {"url": src}
  280. if chunker.data_type == DataType.JSON and is_valid_json_string(src):
  281. url = hashlib.sha256((src).encode("utf-8")).hexdigest()
  282. where = {"url": url}
  283. # if data type is qna_pair, we check for question
  284. if chunker.data_type == DataType.QNA_PAIR:
  285. where = {"question": src[0]}
  286. if self.config.id is not None:
  287. where["app_id"] = self.config.id
  288. db_result = self.db.get(ids=ids, where=where) # optional filter
  289. existing_ids = set(db_result["ids"])
  290. if len(existing_ids):
  291. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  292. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  293. if not data_dict:
  294. src_copy = src
  295. if len(src_copy) > 50:
  296. src_copy = src[:50] + "..."
  297. print(f"All data from {src_copy} already exists in the database.")
  298. # Make sure to return a matching return type
  299. return [], [], [], 0
  300. ids = list(data_dict.keys())
  301. documents, metadatas = zip(*data_dict.values())
  302. # Loop though all metadatas and add extras.
  303. new_metadatas = []
  304. for m in metadatas:
  305. # Add app id in metadatas so that they can be queried on later
  306. if self.config.id:
  307. m["app_id"] = self.config.id
  308. # Add hashed source
  309. m["hash"] = source_hash
  310. # Note: Metadata is the function argument
  311. if metadata:
  312. # Spread whatever is in metadata into the new object.
  313. m.update(metadata)
  314. new_metadatas.append(m)
  315. metadatas = new_metadatas
  316. if dry_run:
  317. return list(documents), metadatas, ids, 0
  318. # Count before, to calculate a delta in the end.
  319. chunks_before_addition = self.db.count()
  320. # Filter out empty documents and ensure they meet the API requirements
  321. valid_documents = [doc for doc in documents if doc and isinstance(doc, str)]
  322. documents = valid_documents
  323. # Chunk documents into batches of 2048 and handle each batch
  324. # helps wigth large loads of embeddings that hit OpenAI limits
  325. document_batches = [documents[i : i + 2048] for i in range(0, len(documents), 2048)]
  326. for batch in document_batches:
  327. try:
  328. # Add only valid batches
  329. if batch:
  330. self.db.add(documents=batch, metadatas=metadatas, ids=ids, **kwargs)
  331. except Exception as e:
  332. print(f"Failed to add batch due to a bad request: {e}")
  333. # Handle the error, e.g., by logging, retrying, or skipping
  334. pass
  335. count_new_chunks = self.db.count() - chunks_before_addition
  336. print(f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}")
  337. return list(documents), metadatas, ids, count_new_chunks
  338. @staticmethod
  339. def _format_result(results):
  340. return [
  341. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  342. for result in zip(
  343. results["documents"][0],
  344. results["metadatas"][0],
  345. results["distances"][0],
  346. )
  347. ]
  348. def _retrieve_from_database(
  349. self,
  350. input_query: str,
  351. config: Optional[BaseLlmConfig] = None,
  352. where=None,
  353. citations: bool = False,
  354. **kwargs: Optional[dict[str, Any]],
  355. ) -> Union[list[tuple[str, str, str]], list[str]]:
  356. """
  357. Queries the vector database based on the given input query.
  358. Gets relevant doc based on the query
  359. :param input_query: The query to use.
  360. :type input_query: str
  361. :param config: The query configuration, defaults to None
  362. :type config: Optional[BaseLlmConfig], optional
  363. :param where: A dictionary of key-value pairs to filter the database results, defaults to None
  364. :type where: _type_, optional
  365. :param citations: A boolean to indicate if db should fetch citation source
  366. :type citations: bool
  367. :return: List of contents of the document that matched your query
  368. :rtype: list[str]
  369. """
  370. query_config = config or self.llm.config
  371. if where is not None:
  372. where = where
  373. else:
  374. where = {}
  375. if query_config is not None and query_config.where is not None:
  376. where = query_config.where
  377. if self.config.id is not None:
  378. where.update({"app_id": self.config.id})
  379. contexts = self.db.query(
  380. input_query=input_query,
  381. n_results=query_config.number_documents,
  382. where=where,
  383. citations=citations,
  384. **kwargs,
  385. )
  386. return contexts
  387. def query(
  388. self,
  389. input_query: str,
  390. config: BaseLlmConfig = None,
  391. dry_run=False,
  392. where: Optional[dict] = None,
  393. citations: bool = False,
  394. **kwargs: dict[str, Any],
  395. ) -> Union[tuple[str, list[tuple[str, dict]]], str]:
  396. """
  397. Queries the vector database based on the given input query.
  398. Gets relevant doc based on the query and then passes it to an
  399. LLM as context to get the answer.
  400. :param input_query: The query to use.
  401. :type input_query: str
  402. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  403. To persistently use a config, declare it during app init., defaults to None
  404. :type config: Optional[BaseLlmConfig], optional
  405. :param dry_run: A dry run does everything except send the resulting prompt to
  406. the LLM. The purpose is to test the prompt, not the response., defaults to False
  407. :type dry_run: bool, optional
  408. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  409. :type where: Optional[dict[str, str]], optional
  410. :param kwargs: To read more params for the query function. Ex. we use citations boolean
  411. param to return context along with the answer
  412. :type kwargs: dict[str, Any]
  413. :return: The answer to the query, with citations if the citation flag is True
  414. or the dry run result
  415. :rtype: str, if citations is False, otherwise tuple[str, list[tuple[str,str,str]]]
  416. """
  417. contexts = self._retrieve_from_database(
  418. input_query=input_query, config=config, where=where, citations=citations, **kwargs
  419. )
  420. if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
  421. contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
  422. else:
  423. contexts_data_for_llm_query = contexts
  424. if self.cache_config is not None:
  425. logging.info("Cache enabled. Checking cache...")
  426. answer = adapt(
  427. llm_handler=self.llm.query,
  428. cache_data_convert=gptcache_data_convert,
  429. update_cache_callback=gptcache_update_cache_callback,
  430. session=get_gptcache_session(session_id=self.config.id),
  431. input_query=input_query,
  432. contexts=contexts_data_for_llm_query,
  433. config=config,
  434. dry_run=dry_run,
  435. )
  436. else:
  437. answer = self.llm.query(
  438. input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
  439. )
  440. # Send anonymous telemetry
  441. self.telemetry.capture(event_name="query", properties=self._telemetry_props)
  442. if citations:
  443. return answer, contexts
  444. else:
  445. return answer
  446. def chat(
  447. self,
  448. input_query: str,
  449. config: Optional[BaseLlmConfig] = None,
  450. dry_run=False,
  451. session_id: str = "default",
  452. where: Optional[dict[str, str]] = None,
  453. citations: bool = False,
  454. **kwargs: dict[str, Any],
  455. ) -> Union[tuple[str, list[tuple[str, dict]]], str]:
  456. """
  457. Queries the vector database on the given input query.
  458. Gets relevant doc based on the query and then passes it to an
  459. LLM as context to get the answer.
  460. Maintains the whole conversation in memory.
  461. :param input_query: The query to use.
  462. :type input_query: str
  463. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  464. To persistently use a config, declare it during app init., defaults to None
  465. :type config: Optional[BaseLlmConfig], optional
  466. :param dry_run: A dry run does everything except send the resulting prompt to
  467. the LLM. The purpose is to test the prompt, not the response., defaults to False
  468. :type dry_run: bool, optional
  469. :param session_id: The session id to use for chat history, defaults to 'default'.
  470. :type session_id: Optional[str], optional
  471. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  472. :type where: Optional[dict[str, str]], optional
  473. :param kwargs: To read more params for the query function. Ex. we use citations boolean
  474. param to return context along with the answer
  475. :type kwargs: dict[str, Any]
  476. :return: The answer to the query, with citations if the citation flag is True
  477. or the dry run result
  478. :rtype: str, if citations is False, otherwise tuple[str, list[tuple[str,str,str]]]
  479. """
  480. contexts = self._retrieve_from_database(
  481. input_query=input_query, config=config, where=where, citations=citations, **kwargs
  482. )
  483. if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
  484. contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
  485. else:
  486. contexts_data_for_llm_query = contexts
  487. # Update the history beforehand so that we can handle multiple chat sessions in the same python session
  488. self.llm.update_history(app_id=self.config.id, session_id=session_id)
  489. if self.cache_config is not None:
  490. logging.info("Cache enabled. Checking cache...")
  491. cache_id = f"{session_id}--{self.config.id}"
  492. answer = adapt(
  493. llm_handler=self.llm.chat,
  494. cache_data_convert=gptcache_data_convert,
  495. update_cache_callback=gptcache_update_cache_callback,
  496. session=get_gptcache_session(session_id=cache_id),
  497. input_query=input_query,
  498. contexts=contexts_data_for_llm_query,
  499. config=config,
  500. dry_run=dry_run,
  501. )
  502. else:
  503. answer = self.llm.chat(
  504. input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
  505. )
  506. # add conversation in memory
  507. self.llm.add_history(self.config.id, input_query, answer, session_id=session_id)
  508. # Send anonymous telemetry
  509. self.telemetry.capture(event_name="chat", properties=self._telemetry_props)
  510. if citations:
  511. return answer, contexts
  512. else:
  513. return answer
  514. def search(self, query, num_documents=3, where=None, raw_filter=None):
  515. """
  516. Search for similar documents related to the query in the vector database.
  517. Args:
  518. query (str): The query to use.
  519. num_documents (int, optional): Number of similar documents to fetch. Defaults to 3.
  520. where (dict[str, any], optional): Filter criteria for the search.
  521. raw_filter (dict[str, any], optional): Advanced raw filter criteria for the search.
  522. Raises:
  523. ValueError: If both `raw_filter` and `where` are used simultaneously.
  524. Returns:
  525. list[dict]: A list of dictionaries, each containing the 'context' and 'metadata' of a document.
  526. """
  527. # Send anonymous telemetry
  528. self.telemetry.capture(event_name="search", properties=self._telemetry_props)
  529. if raw_filter and where:
  530. raise ValueError("You can't use both `raw_filter` and `where` together.")
  531. filter_type = "raw_filter" if raw_filter else "where"
  532. filter_criteria = raw_filter if raw_filter else where
  533. params = {
  534. "input_query": query,
  535. "n_results": num_documents,
  536. "citations": True,
  537. "app_id": self.config.id,
  538. filter_type: filter_criteria,
  539. }
  540. return [{"context": c[0], "metadata": c[1]} for c in self.db.query(**params)]
  541. def set_collection_name(self, name: str):
  542. """
  543. Set the name of the collection. A collection is an isolated space for vectors.
  544. Using `app.db.set_collection_name` method is preferred to this.
  545. :param name: Name of the collection.
  546. :type name: str
  547. """
  548. self.db.set_collection_name(name)
  549. # Create the collection if it does not exist
  550. self.db._get_or_create_collection(name)
  551. # TODO: Check whether it is necessary to assign to the `self.collection` attribute,
  552. # since the main purpose is the creation.
  553. def reset(self):
  554. """
  555. Resets the database. Deletes all embeddings irreversibly.
  556. `App` does not have to be reinitialized after using this method.
  557. """
  558. try:
  559. self.db_session.query(DataSource).filter_by(app_id=self.config.id).delete()
  560. self.db_session.commit()
  561. except Exception as e:
  562. logging.error(f"Error deleting chat history: {e}")
  563. self.db_session.rollback()
  564. return None
  565. self.db.reset()
  566. self.delete_all_chat_history(app_id=self.config.id)
  567. # Send anonymous telemetry
  568. self.telemetry.capture(event_name="reset", properties=self._telemetry_props)
  569. def get_history(
  570. self,
  571. num_rounds: int = 10,
  572. display_format: bool = True,
  573. session_id: Optional[str] = "default",
  574. fetch_all: bool = False,
  575. ):
  576. history = self.llm.memory.get(
  577. app_id=self.config.id,
  578. session_id=session_id,
  579. num_rounds=num_rounds,
  580. display_format=display_format,
  581. fetch_all=fetch_all,
  582. )
  583. return history
  584. def delete_session_chat_history(self, session_id: str = "default"):
  585. self.llm.memory.delete(app_id=self.config.id, session_id=session_id)
  586. self.llm.update_history(app_id=self.config.id)
  587. def delete_all_chat_history(self, app_id: str):
  588. self.llm.memory.delete(app_id=app_id)
  589. self.llm.update_history(app_id=app_id)
  590. def delete(self, source_id: str):
  591. """
  592. Deletes the data from the database.
  593. :param source_hash: The hash of the source.
  594. :type source_hash: str
  595. """
  596. self.db.delete(where={"hash": source_id})
  597. logging.info(f"Successfully deleted {source_id}")
  598. # Send anonymous telemetry
  599. if self.config.collect_metrics:
  600. self.telemetry.capture(event_name="delete", properties=self._telemetry_props)