embedchain.py 30 KB

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