embedchain.py 29 KB

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