embedchain.py 29 KB

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