embedchain.py 29 KB

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