retrieval.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. import json
  2. import logging
  3. import mimetypes
  4. import os
  5. import shutil
  6. import uuid
  7. from datetime import datetime
  8. from pathlib import Path
  9. from typing import Iterator, List, Optional, Sequence, Union
  10. from fastapi import (
  11. Depends,
  12. FastAPI,
  13. File,
  14. Form,
  15. HTTPException,
  16. UploadFile,
  17. Request,
  18. status,
  19. APIRouter,
  20. )
  21. from fastapi.middleware.cors import CORSMiddleware
  22. from fastapi.concurrency import run_in_threadpool
  23. from pydantic import BaseModel
  24. import tiktoken
  25. from langchain.text_splitter import RecursiveCharacterTextSplitter, TokenTextSplitter
  26. from langchain_core.documents import Document
  27. from open_webui.models.files import FileModel, Files
  28. from open_webui.models.knowledge import Knowledges
  29. from open_webui.storage.provider import Storage
  30. from open_webui.retrieval.vector.connector import VECTOR_DB_CLIENT
  31. # Document loaders
  32. from open_webui.retrieval.loaders.main import Loader
  33. from open_webui.retrieval.loaders.youtube import YoutubeLoader
  34. # Web search engines
  35. from open_webui.retrieval.web.main import SearchResult
  36. from open_webui.retrieval.web.utils import get_web_loader
  37. from open_webui.retrieval.web.brave import search_brave
  38. from open_webui.retrieval.web.kagi import search_kagi
  39. from open_webui.retrieval.web.mojeek import search_mojeek
  40. from open_webui.retrieval.web.bocha import search_bocha
  41. from open_webui.retrieval.web.duckduckgo import search_duckduckgo
  42. from open_webui.retrieval.web.google_pse import search_google_pse
  43. from open_webui.retrieval.web.jina_search import search_jina
  44. from open_webui.retrieval.web.searchapi import search_searchapi
  45. from open_webui.retrieval.web.serpapi import search_serpapi
  46. from open_webui.retrieval.web.searxng import search_searxng
  47. from open_webui.retrieval.web.serper import search_serper
  48. from open_webui.retrieval.web.serply import search_serply
  49. from open_webui.retrieval.web.serpstack import search_serpstack
  50. from open_webui.retrieval.web.tavily import search_tavily
  51. from open_webui.retrieval.web.bing import search_bing
  52. from open_webui.retrieval.web.exa import search_exa
  53. from open_webui.retrieval.web.perplexity import search_perplexity
  54. from open_webui.retrieval.web.sougou import search_sougou
  55. from open_webui.retrieval.utils import (
  56. get_embedding_function,
  57. get_model_path,
  58. query_collection,
  59. query_collection_with_hybrid_search,
  60. query_doc,
  61. query_doc_with_hybrid_search,
  62. )
  63. from open_webui.utils.misc import (
  64. calculate_sha256_string,
  65. )
  66. from open_webui.utils.auth import get_admin_user, get_verified_user
  67. from open_webui.config import (
  68. ENV,
  69. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  70. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  71. RAG_RERANKING_MODEL_AUTO_UPDATE,
  72. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  73. UPLOAD_DIR,
  74. DEFAULT_LOCALE,
  75. RAG_EMBEDDING_CONTENT_PREFIX,
  76. RAG_EMBEDDING_QUERY_PREFIX,
  77. )
  78. from open_webui.env import (
  79. SRC_LOG_LEVELS,
  80. DEVICE_TYPE,
  81. DOCKER,
  82. )
  83. from open_webui.constants import ERROR_MESSAGES
  84. log = logging.getLogger(__name__)
  85. log.setLevel(SRC_LOG_LEVELS["RAG"])
  86. ##########################################
  87. #
  88. # Utility functions
  89. #
  90. ##########################################
  91. def get_ef(
  92. engine: str,
  93. embedding_model: str,
  94. auto_update: bool = False,
  95. ):
  96. ef = None
  97. if embedding_model and engine == "":
  98. from sentence_transformers import SentenceTransformer
  99. try:
  100. ef = SentenceTransformer(
  101. get_model_path(embedding_model, auto_update),
  102. device=DEVICE_TYPE,
  103. trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  104. )
  105. except Exception as e:
  106. log.debug(f"Error loading SentenceTransformer: {e}")
  107. return ef
  108. def get_rf(
  109. reranking_model: Optional[str] = None,
  110. auto_update: bool = False,
  111. ):
  112. rf = None
  113. if reranking_model:
  114. if any(model in reranking_model for model in ["jinaai/jina-colbert-v2"]):
  115. try:
  116. from open_webui.retrieval.models.colbert import ColBERT
  117. rf = ColBERT(
  118. get_model_path(reranking_model, auto_update),
  119. env="docker" if DOCKER else None,
  120. )
  121. except Exception as e:
  122. log.error(f"ColBERT: {e}")
  123. raise Exception(ERROR_MESSAGES.DEFAULT(e))
  124. else:
  125. import sentence_transformers
  126. try:
  127. rf = sentence_transformers.CrossEncoder(
  128. get_model_path(reranking_model, auto_update),
  129. device=DEVICE_TYPE,
  130. trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  131. )
  132. except Exception as e:
  133. log.error(f"CrossEncoder: {e}")
  134. raise Exception(ERROR_MESSAGES.DEFAULT("CrossEncoder error"))
  135. return rf
  136. ##########################################
  137. #
  138. # API routes
  139. #
  140. ##########################################
  141. router = APIRouter()
  142. class CollectionNameForm(BaseModel):
  143. collection_name: Optional[str] = None
  144. class ProcessUrlForm(CollectionNameForm):
  145. url: str
  146. class SearchForm(BaseModel):
  147. query: str
  148. @router.get("/")
  149. async def get_status(request: Request):
  150. return {
  151. "status": True,
  152. "chunk_size": request.app.state.config.CHUNK_SIZE,
  153. "chunk_overlap": request.app.state.config.CHUNK_OVERLAP,
  154. "template": request.app.state.config.RAG_TEMPLATE,
  155. "embedding_engine": request.app.state.config.RAG_EMBEDDING_ENGINE,
  156. "embedding_model": request.app.state.config.RAG_EMBEDDING_MODEL,
  157. "reranking_model": request.app.state.config.RAG_RERANKING_MODEL,
  158. "embedding_batch_size": request.app.state.config.RAG_EMBEDDING_BATCH_SIZE,
  159. }
  160. @router.get("/embedding")
  161. async def get_embedding_config(request: Request, user=Depends(get_admin_user)):
  162. return {
  163. "status": True,
  164. "embedding_engine": request.app.state.config.RAG_EMBEDDING_ENGINE,
  165. "embedding_model": request.app.state.config.RAG_EMBEDDING_MODEL,
  166. "embedding_batch_size": request.app.state.config.RAG_EMBEDDING_BATCH_SIZE,
  167. "openai_config": {
  168. "url": request.app.state.config.RAG_OPENAI_API_BASE_URL,
  169. "key": request.app.state.config.RAG_OPENAI_API_KEY,
  170. },
  171. "ollama_config": {
  172. "url": request.app.state.config.RAG_OLLAMA_BASE_URL,
  173. "key": request.app.state.config.RAG_OLLAMA_API_KEY,
  174. },
  175. }
  176. @router.get("/reranking")
  177. async def get_reraanking_config(request: Request, user=Depends(get_admin_user)):
  178. return {
  179. "status": True,
  180. "reranking_model": request.app.state.config.RAG_RERANKING_MODEL,
  181. }
  182. class OpenAIConfigForm(BaseModel):
  183. url: str
  184. key: str
  185. class OllamaConfigForm(BaseModel):
  186. url: str
  187. key: str
  188. class EmbeddingModelUpdateForm(BaseModel):
  189. openai_config: Optional[OpenAIConfigForm] = None
  190. ollama_config: Optional[OllamaConfigForm] = None
  191. embedding_engine: str
  192. embedding_model: str
  193. embedding_batch_size: Optional[int] = 1
  194. @router.post("/embedding/update")
  195. async def update_embedding_config(
  196. request: Request, form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
  197. ):
  198. log.info(
  199. f"Updating embedding model: {request.app.state.config.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
  200. )
  201. try:
  202. request.app.state.config.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
  203. request.app.state.config.RAG_EMBEDDING_MODEL = form_data.embedding_model
  204. if request.app.state.config.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
  205. if form_data.openai_config is not None:
  206. request.app.state.config.RAG_OPENAI_API_BASE_URL = (
  207. form_data.openai_config.url
  208. )
  209. request.app.state.config.RAG_OPENAI_API_KEY = (
  210. form_data.openai_config.key
  211. )
  212. if form_data.ollama_config is not None:
  213. request.app.state.config.RAG_OLLAMA_BASE_URL = (
  214. form_data.ollama_config.url
  215. )
  216. request.app.state.config.RAG_OLLAMA_API_KEY = (
  217. form_data.ollama_config.key
  218. )
  219. request.app.state.config.RAG_EMBEDDING_BATCH_SIZE = (
  220. form_data.embedding_batch_size
  221. )
  222. request.app.state.ef = get_ef(
  223. request.app.state.config.RAG_EMBEDDING_ENGINE,
  224. request.app.state.config.RAG_EMBEDDING_MODEL,
  225. )
  226. request.app.state.EMBEDDING_FUNCTION = get_embedding_function(
  227. request.app.state.config.RAG_EMBEDDING_ENGINE,
  228. request.app.state.config.RAG_EMBEDDING_MODEL,
  229. request.app.state.ef,
  230. (
  231. request.app.state.config.RAG_OPENAI_API_BASE_URL
  232. if request.app.state.config.RAG_EMBEDDING_ENGINE == "openai"
  233. else request.app.state.config.RAG_OLLAMA_BASE_URL
  234. ),
  235. (
  236. request.app.state.config.RAG_OPENAI_API_KEY
  237. if request.app.state.config.RAG_EMBEDDING_ENGINE == "openai"
  238. else request.app.state.config.RAG_OLLAMA_API_KEY
  239. ),
  240. request.app.state.config.RAG_EMBEDDING_BATCH_SIZE,
  241. )
  242. return {
  243. "status": True,
  244. "embedding_engine": request.app.state.config.RAG_EMBEDDING_ENGINE,
  245. "embedding_model": request.app.state.config.RAG_EMBEDDING_MODEL,
  246. "embedding_batch_size": request.app.state.config.RAG_EMBEDDING_BATCH_SIZE,
  247. "openai_config": {
  248. "url": request.app.state.config.RAG_OPENAI_API_BASE_URL,
  249. "key": request.app.state.config.RAG_OPENAI_API_KEY,
  250. },
  251. "ollama_config": {
  252. "url": request.app.state.config.RAG_OLLAMA_BASE_URL,
  253. "key": request.app.state.config.RAG_OLLAMA_API_KEY,
  254. },
  255. }
  256. except Exception as e:
  257. log.exception(f"Problem updating embedding model: {e}")
  258. raise HTTPException(
  259. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  260. detail=ERROR_MESSAGES.DEFAULT(e),
  261. )
  262. class RerankingModelUpdateForm(BaseModel):
  263. reranking_model: str
  264. @router.post("/reranking/update")
  265. async def update_reranking_config(
  266. request: Request, form_data: RerankingModelUpdateForm, user=Depends(get_admin_user)
  267. ):
  268. log.info(
  269. f"Updating reranking model: {request.app.state.config.RAG_RERANKING_MODEL} to {form_data.reranking_model}"
  270. )
  271. try:
  272. request.app.state.config.RAG_RERANKING_MODEL = form_data.reranking_model
  273. try:
  274. request.app.state.rf = get_rf(
  275. request.app.state.config.RAG_RERANKING_MODEL,
  276. True,
  277. )
  278. except Exception as e:
  279. log.error(f"Error loading reranking model: {e}")
  280. request.app.state.config.ENABLE_RAG_HYBRID_SEARCH = False
  281. return {
  282. "status": True,
  283. "reranking_model": request.app.state.config.RAG_RERANKING_MODEL,
  284. }
  285. except Exception as e:
  286. log.exception(f"Problem updating reranking model: {e}")
  287. raise HTTPException(
  288. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  289. detail=ERROR_MESSAGES.DEFAULT(e),
  290. )
  291. @router.get("/config")
  292. async def get_rag_config(request: Request, user=Depends(get_admin_user)):
  293. return {
  294. "status": True,
  295. "pdf_extract_images": request.app.state.config.PDF_EXTRACT_IMAGES,
  296. "RAG_FULL_CONTEXT": request.app.state.config.RAG_FULL_CONTEXT,
  297. "BYPASS_EMBEDDING_AND_RETRIEVAL": request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL,
  298. "enable_google_drive_integration": request.app.state.config.ENABLE_GOOGLE_DRIVE_INTEGRATION,
  299. "enable_onedrive_integration": request.app.state.config.ENABLE_ONEDRIVE_INTEGRATION,
  300. "content_extraction": {
  301. "engine": request.app.state.config.CONTENT_EXTRACTION_ENGINE,
  302. "tika_server_url": request.app.state.config.TIKA_SERVER_URL,
  303. "docling_server_url": request.app.state.config.DOCLING_SERVER_URL,
  304. "document_intelligence_config": {
  305. "endpoint": request.app.state.config.DOCUMENT_INTELLIGENCE_ENDPOINT,
  306. "key": request.app.state.config.DOCUMENT_INTELLIGENCE_KEY,
  307. },
  308. "mistral_ocr_config": {
  309. "api_key": request.app.state.config.MISTRAL_OCR_API_KEY,
  310. },
  311. },
  312. "chunk": {
  313. "text_splitter": request.app.state.config.TEXT_SPLITTER,
  314. "chunk_size": request.app.state.config.CHUNK_SIZE,
  315. "chunk_overlap": request.app.state.config.CHUNK_OVERLAP,
  316. },
  317. "file": {
  318. "max_size": request.app.state.config.FILE_MAX_SIZE,
  319. "max_count": request.app.state.config.FILE_MAX_COUNT,
  320. },
  321. "web": {
  322. "ENABLE_RAG_WEB_SEARCH": request.app.state.config.ENABLE_RAG_WEB_SEARCH,
  323. "search": {
  324. "engine": request.app.state.config.RAG_WEB_SEARCH_ENGINE,
  325. "searxng_query_url": request.app.state.config.SEARXNG_QUERY_URL,
  326. "google_pse_api_key": request.app.state.config.GOOGLE_PSE_API_KEY,
  327. "google_pse_engine_id": request.app.state.config.GOOGLE_PSE_ENGINE_ID,
  328. "brave_search_api_key": request.app.state.config.BRAVE_SEARCH_API_KEY,
  329. "kagi_search_api_key": request.app.state.config.KAGI_SEARCH_API_KEY,
  330. "mojeek_search_api_key": request.app.state.config.MOJEEK_SEARCH_API_KEY,
  331. "bocha_search_api_key": request.app.state.config.BOCHA_SEARCH_API_KEY,
  332. "serpstack_api_key": request.app.state.config.SERPSTACK_API_KEY,
  333. "serpstack_https": request.app.state.config.SERPSTACK_HTTPS,
  334. "serper_api_key": request.app.state.config.SERPER_API_KEY,
  335. "serply_api_key": request.app.state.config.SERPLY_API_KEY,
  336. "tavily_api_key": request.app.state.config.TAVILY_API_KEY,
  337. "searchapi_api_key": request.app.state.config.SEARCHAPI_API_KEY,
  338. "searchapi_engine": request.app.state.config.SEARCHAPI_ENGINE,
  339. "serpapi_api_key": request.app.state.config.SERPAPI_API_KEY,
  340. "serpapi_engine": request.app.state.config.SERPAPI_ENGINE,
  341. "jina_api_key": request.app.state.config.JINA_API_KEY,
  342. "bing_search_v7_endpoint": request.app.state.config.BING_SEARCH_V7_ENDPOINT,
  343. "bing_search_v7_subscription_key": request.app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY,
  344. "exa_api_key": request.app.state.config.EXA_API_KEY,
  345. "perplexity_api_key": request.app.state.config.PERPLEXITY_API_KEY,
  346. "sougou_api_sid": request.app.state.config.SOUGOU_API_SID,
  347. "sougou_api_sk": request.app.state.config.SOUGOU_API_SK,
  348. "result_count": request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  349. "concurrent_requests": request.app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  350. "domain_filter_list": request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  351. },
  352. "loader": {
  353. "engine": request.app.state.config.RAG_WEB_LOADER_ENGINE,
  354. "enable_ssl_verification": request.app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  355. "trust_env": request.app.state.config.RAG_WEB_SEARCH_TRUST_ENV,
  356. "bypass_embedding_and_retrieval": request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL,
  357. "playwright_ws_uri": request.app.state.config.PLAYWRIGHT_WS_URI,
  358. "playwright_timeout": request.app.state.config.PLAYWRIGHT_TIMEOUT,
  359. "firecrawl_api_key": request.app.state.config.FIRECRAWL_API_KEY,
  360. "firecrawl_api_base_url": request.app.state.config.FIRECRAWL_API_BASE_URL,
  361. "tavily_api_key": request.app.state.config.TAVILY_API_KEY,
  362. "tavily_extract_depth": request.app.state.config.TAVILY_EXTRACT_DEPTH,
  363. "youtube": {
  364. "language": request.app.state.config.YOUTUBE_LOADER_LANGUAGE,
  365. "proxy_url": request.app.state.config.YOUTUBE_LOADER_PROXY_URL,
  366. "translation": request.app.state.YOUTUBE_LOADER_TRANSLATION,
  367. },
  368. },
  369. },
  370. }
  371. class FileConfig(BaseModel):
  372. max_size: Optional[int] = None
  373. max_count: Optional[int] = None
  374. class DocumentIntelligenceConfigForm(BaseModel):
  375. endpoint: str
  376. key: str
  377. class MistralOCRConfigForm(BaseModel):
  378. api_key: str
  379. class ContentExtractionConfig(BaseModel):
  380. engine: str = ""
  381. tika_server_url: Optional[str] = None
  382. docling_server_url: Optional[str] = None
  383. document_intelligence_config: Optional[DocumentIntelligenceConfigForm] = None
  384. mistral_ocr_config: Optional[MistralOCRConfigForm] = None
  385. class ChunkParamUpdateForm(BaseModel):
  386. text_splitter: Optional[str] = None
  387. chunk_size: int
  388. chunk_overlap: int
  389. class YoutubeLoaderConfig(BaseModel):
  390. language: list[str]
  391. translation: Optional[str] = None
  392. proxy_url: str = ""
  393. class WebSearchConfig(BaseModel):
  394. engine: Optional[str] = None
  395. searxng_query_url: Optional[str] = None
  396. google_pse_api_key: Optional[str] = None
  397. google_pse_engine_id: Optional[str] = None
  398. brave_search_api_key: Optional[str] = None
  399. kagi_search_api_key: Optional[str] = None
  400. mojeek_search_api_key: Optional[str] = None
  401. bocha_search_api_key: Optional[str] = None
  402. serpstack_api_key: Optional[str] = None
  403. serpstack_https: Optional[bool] = None
  404. serper_api_key: Optional[str] = None
  405. serply_api_key: Optional[str] = None
  406. tavily_api_key: Optional[str] = None
  407. searchapi_api_key: Optional[str] = None
  408. searchapi_engine: Optional[str] = None
  409. serpapi_api_key: Optional[str] = None
  410. serpapi_engine: Optional[str] = None
  411. jina_api_key: Optional[str] = None
  412. bing_search_v7_endpoint: Optional[str] = None
  413. bing_search_v7_subscription_key: Optional[str] = None
  414. exa_api_key: Optional[str] = None
  415. perplexity_api_key: Optional[str] = None
  416. sougou_api_sid: Optional[str] = None
  417. sougou_api_sk: Optional[str] = None
  418. result_count: Optional[int] = None
  419. concurrent_requests: Optional[int] = None
  420. domain_filter_list: Optional[List[str]] = []
  421. class WebLoaderConfig(BaseModel):
  422. engine: Optional[str] = None
  423. enable_ssl_verification: Optional[bool] = None
  424. trust_env: Optional[bool] = None
  425. bypass_embedding_and_retrieval: Optional[bool] = None
  426. playwright_ws_uri: Optional[str] = None
  427. playwright_timeout: Optional[int] = None
  428. firecrawl_api_key: Optional[str] = None
  429. firecrawl_api_base_url: Optional[str] = None
  430. tavily_api_key: Optional[str] = None
  431. tavily_extract_depth: Optional[str] = None
  432. youtube: Optional[YoutubeLoaderConfig] = None
  433. class WebConfig(BaseModel):
  434. ENABLE_RAG_WEB_SEARCH: Optional[bool] = None
  435. search: WebSearchConfig
  436. loader: WebLoaderConfig
  437. class ConfigUpdateForm(BaseModel):
  438. RAG_FULL_CONTEXT: Optional[bool] = None
  439. BYPASS_EMBEDDING_AND_RETRIEVAL: Optional[bool] = None
  440. pdf_extract_images: Optional[bool] = None
  441. enable_google_drive_integration: Optional[bool] = None
  442. enable_onedrive_integration: Optional[bool] = None
  443. file: Optional[FileConfig] = None
  444. content_extraction: Optional[ContentExtractionConfig] = None
  445. chunk: Optional[ChunkParamUpdateForm] = None
  446. web: Optional[WebConfig] = None
  447. @router.post("/config/update")
  448. async def update_rag_config(
  449. request: Request, form_data: ConfigUpdateForm, user=Depends(get_admin_user)
  450. ):
  451. request.app.state.config.PDF_EXTRACT_IMAGES = (
  452. form_data.pdf_extract_images
  453. if form_data.pdf_extract_images is not None
  454. else request.app.state.config.PDF_EXTRACT_IMAGES
  455. )
  456. request.app.state.config.RAG_FULL_CONTEXT = (
  457. form_data.RAG_FULL_CONTEXT
  458. if form_data.RAG_FULL_CONTEXT is not None
  459. else request.app.state.config.RAG_FULL_CONTEXT
  460. )
  461. request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL = (
  462. form_data.BYPASS_EMBEDDING_AND_RETRIEVAL
  463. if form_data.BYPASS_EMBEDDING_AND_RETRIEVAL is not None
  464. else request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
  465. )
  466. request.app.state.config.ENABLE_GOOGLE_DRIVE_INTEGRATION = (
  467. form_data.enable_google_drive_integration
  468. if form_data.enable_google_drive_integration is not None
  469. else request.app.state.config.ENABLE_GOOGLE_DRIVE_INTEGRATION
  470. )
  471. request.app.state.config.ENABLE_ONEDRIVE_INTEGRATION = (
  472. form_data.enable_onedrive_integration
  473. if form_data.enable_onedrive_integration is not None
  474. else request.app.state.config.ENABLE_ONEDRIVE_INTEGRATION
  475. )
  476. if form_data.file is not None:
  477. request.app.state.config.FILE_MAX_SIZE = form_data.file.max_size
  478. request.app.state.config.FILE_MAX_COUNT = form_data.file.max_count
  479. if form_data.content_extraction is not None:
  480. log.info(
  481. f"Updating content extraction: {request.app.state.config.CONTENT_EXTRACTION_ENGINE} to {form_data.content_extraction.engine}"
  482. )
  483. request.app.state.config.CONTENT_EXTRACTION_ENGINE = (
  484. form_data.content_extraction.engine
  485. )
  486. request.app.state.config.TIKA_SERVER_URL = (
  487. form_data.content_extraction.tika_server_url
  488. )
  489. request.app.state.config.DOCLING_SERVER_URL = (
  490. form_data.content_extraction.docling_server_url
  491. )
  492. if form_data.content_extraction.document_intelligence_config is not None:
  493. request.app.state.config.DOCUMENT_INTELLIGENCE_ENDPOINT = (
  494. form_data.content_extraction.document_intelligence_config.endpoint
  495. )
  496. request.app.state.config.DOCUMENT_INTELLIGENCE_KEY = (
  497. form_data.content_extraction.document_intelligence_config.key
  498. )
  499. if form_data.content_extraction.mistral_ocr_config is not None:
  500. request.app.state.config.MISTRAL_OCR_API_KEY = (
  501. form_data.content_extraction.mistral_ocr_config.api_key
  502. )
  503. if form_data.chunk is not None:
  504. request.app.state.config.TEXT_SPLITTER = form_data.chunk.text_splitter
  505. request.app.state.config.CHUNK_SIZE = form_data.chunk.chunk_size
  506. request.app.state.config.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
  507. if form_data.web is not None:
  508. request.app.state.config.ENABLE_RAG_WEB_SEARCH = (
  509. form_data.web.ENABLE_RAG_WEB_SEARCH
  510. )
  511. request.app.state.config.RAG_WEB_SEARCH_ENGINE = form_data.web.search.engine
  512. request.app.state.config.SEARXNG_QUERY_URL = (
  513. form_data.web.search.searxng_query_url
  514. )
  515. request.app.state.config.GOOGLE_PSE_API_KEY = (
  516. form_data.web.search.google_pse_api_key
  517. )
  518. request.app.state.config.GOOGLE_PSE_ENGINE_ID = (
  519. form_data.web.search.google_pse_engine_id
  520. )
  521. request.app.state.config.BRAVE_SEARCH_API_KEY = (
  522. form_data.web.search.brave_search_api_key
  523. )
  524. request.app.state.config.KAGI_SEARCH_API_KEY = (
  525. form_data.web.search.kagi_search_api_key
  526. )
  527. request.app.state.config.MOJEEK_SEARCH_API_KEY = (
  528. form_data.web.search.mojeek_search_api_key
  529. )
  530. request.app.state.config.BOCHA_SEARCH_API_KEY = (
  531. form_data.web.search.bocha_search_api_key
  532. )
  533. request.app.state.config.SERPSTACK_API_KEY = (
  534. form_data.web.search.serpstack_api_key
  535. )
  536. request.app.state.config.SERPSTACK_HTTPS = form_data.web.search.serpstack_https
  537. request.app.state.config.SERPER_API_KEY = form_data.web.search.serper_api_key
  538. request.app.state.config.SERPLY_API_KEY = form_data.web.search.serply_api_key
  539. request.app.state.config.TAVILY_API_KEY = form_data.web.search.tavily_api_key
  540. request.app.state.config.SEARCHAPI_API_KEY = (
  541. form_data.web.search.searchapi_api_key
  542. )
  543. request.app.state.config.SEARCHAPI_ENGINE = (
  544. form_data.web.search.searchapi_engine
  545. )
  546. request.app.state.config.SERPAPI_API_KEY = form_data.web.search.serpapi_api_key
  547. request.app.state.config.SERPAPI_ENGINE = form_data.web.search.serpapi_engine
  548. request.app.state.config.JINA_API_KEY = form_data.web.search.jina_api_key
  549. request.app.state.config.BING_SEARCH_V7_ENDPOINT = (
  550. form_data.web.search.bing_search_v7_endpoint
  551. )
  552. request.app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY = (
  553. form_data.web.search.bing_search_v7_subscription_key
  554. )
  555. request.app.state.config.EXA_API_KEY = form_data.web.search.exa_api_key
  556. request.app.state.config.PERPLEXITY_API_KEY = (
  557. form_data.web.search.perplexity_api_key
  558. )
  559. request.app.state.config.SOUGOU_API_SID = form_data.web.search.sougou_api_sid
  560. request.app.state.config.SOUGOU_API_SK = form_data.web.search.sougou_api_sk
  561. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = (
  562. form_data.web.search.result_count
  563. )
  564. request.app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = (
  565. form_data.web.search.concurrent_requests
  566. )
  567. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST = (
  568. form_data.web.search.domain_filter_list
  569. )
  570. request.app.state.config.RAG_WEB_LOADER_ENGINE = form_data.web.loader.engine
  571. request.app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
  572. # Note: When UI "Bypass SSL verification for Websites"=True then ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION=False
  573. form_data.web.loader.enable_ssl_verification
  574. )
  575. request.app.state.config.RAG_WEB_SEARCH_TRUST_ENV = (
  576. form_data.web.loader.trust_env
  577. )
  578. request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL = (
  579. form_data.web.loader.bypass_embedding_and_retrieval
  580. )
  581. request.app.state.config.PLAYWRIGHT_WS_URI = (
  582. form_data.web.loader.playwright_ws_uri
  583. )
  584. request.app.state.config.PLAYWRIGHT_TIMEOUT = (
  585. form_data.web.loader.playwright_timeout
  586. )
  587. request.app.state.config.FIRECRAWL_API_KEY = (
  588. form_data.web.loader.firecrawl_api_key
  589. )
  590. request.app.state.config.FIRECRAWL_API_BASE_URL = (
  591. form_data.web.loader.firecrawl_api_base_url
  592. )
  593. request.app.state.config.TAVILY_API_KEY = form_data.web.loader.tavily_api_key
  594. request.app.state.config.TAVILY_EXTRACT_DEPTH = (
  595. form_data.web.loader.tavily_extract_depth
  596. )
  597. request.app.state.config.YOUTUBE_LOADER_LANGUAGE = (
  598. form_data.web.loader.youtube.language
  599. )
  600. request.app.state.config.YOUTUBE_LOADER_PROXY_URL = (
  601. form_data.web.loader.youtube.proxy_url
  602. )
  603. request.app.state.YOUTUBE_LOADER_TRANSLATION = (
  604. form_data.web.loader.youtube.translation
  605. )
  606. return {
  607. "status": True,
  608. "pdf_extract_images": request.app.state.config.PDF_EXTRACT_IMAGES,
  609. "RAG_FULL_CONTEXT": request.app.state.config.RAG_FULL_CONTEXT,
  610. "BYPASS_EMBEDDING_AND_RETRIEVAL": request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL,
  611. "file": {
  612. "max_size": request.app.state.config.FILE_MAX_SIZE,
  613. "max_count": request.app.state.config.FILE_MAX_COUNT,
  614. },
  615. "content_extraction": {
  616. "engine": request.app.state.config.CONTENT_EXTRACTION_ENGINE,
  617. "tika_server_url": request.app.state.config.TIKA_SERVER_URL,
  618. "docling_server_url": request.app.state.config.DOCLING_SERVER_URL,
  619. "document_intelligence_config": {
  620. "endpoint": request.app.state.config.DOCUMENT_INTELLIGENCE_ENDPOINT,
  621. "key": request.app.state.config.DOCUMENT_INTELLIGENCE_KEY,
  622. },
  623. "mistral_ocr_config": {
  624. "api_key": request.app.state.config.MISTRAL_OCR_API_KEY,
  625. },
  626. },
  627. "chunk": {
  628. "text_splitter": request.app.state.config.TEXT_SPLITTER,
  629. "chunk_size": request.app.state.config.CHUNK_SIZE,
  630. "chunk_overlap": request.app.state.config.CHUNK_OVERLAP,
  631. },
  632. "web": {
  633. "ENABLE_RAG_WEB_SEARCH": request.app.state.config.ENABLE_RAG_WEB_SEARCH,
  634. "search": {
  635. "engine": request.app.state.config.RAG_WEB_SEARCH_ENGINE,
  636. "searxng_query_url": request.app.state.config.SEARXNG_QUERY_URL,
  637. "google_pse_api_key": request.app.state.config.GOOGLE_PSE_API_KEY,
  638. "google_pse_engine_id": request.app.state.config.GOOGLE_PSE_ENGINE_ID,
  639. "brave_search_api_key": request.app.state.config.BRAVE_SEARCH_API_KEY,
  640. "kagi_search_api_key": request.app.state.config.KAGI_SEARCH_API_KEY,
  641. "mojeek_search_api_key": request.app.state.config.MOJEEK_SEARCH_API_KEY,
  642. "bocha_search_api_key": request.app.state.config.BOCHA_SEARCH_API_KEY,
  643. "serpstack_api_key": request.app.state.config.SERPSTACK_API_KEY,
  644. "serpstack_https": request.app.state.config.SERPSTACK_HTTPS,
  645. "serper_api_key": request.app.state.config.SERPER_API_KEY,
  646. "serply_api_key": request.app.state.config.SERPLY_API_KEY,
  647. "tavily_api_key": request.app.state.config.TAVILY_API_KEY,
  648. "searchapi_api_key": request.app.state.config.SEARCHAPI_API_KEY,
  649. "searchapi_engine": request.app.state.config.SEARCHAPI_ENGINE,
  650. "serpapi_api_key": request.app.state.config.SERPAPI_API_KEY,
  651. "serpapi_engine": request.app.state.config.SERPAPI_ENGINE,
  652. "jina_api_key": request.app.state.config.JINA_API_KEY,
  653. "bing_search_v7_endpoint": request.app.state.config.BING_SEARCH_V7_ENDPOINT,
  654. "bing_search_v7_subscription_key": request.app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY,
  655. "exa_api_key": request.app.state.config.EXA_API_KEY,
  656. "perplexity_api_key": request.app.state.config.PERPLEXITY_API_KEY,
  657. "sougou_api_sid": request.app.state.config.SOUGOU_API_SID,
  658. "sougou_api_sk": request.app.state.config.SOUGOU_API_SK,
  659. "result_count": request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  660. "concurrent_requests": request.app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  661. "domain_filter_list": request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  662. },
  663. "loader": {
  664. "engine": request.app.state.config.RAG_WEB_LOADER_ENGINE,
  665. "enable_ssl_verification": request.app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  666. "trust_env": request.app.state.config.RAG_WEB_SEARCH_TRUST_ENV,
  667. "bypass_embedding_and_retrieval": request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL,
  668. "playwright_ws_uri": request.app.state.config.PLAYWRIGHT_WS_URI,
  669. "playwright_timeout": request.app.state.config.PLAYWRIGHT_TIMEOUT,
  670. "firecrawl_api_key": request.app.state.config.FIRECRAWL_API_KEY,
  671. "firecrawl_api_base_url": request.app.state.config.FIRECRAWL_API_BASE_URL,
  672. "tavily_api_key": request.app.state.config.TAVILY_API_KEY,
  673. "tavily_extract_depth": request.app.state.config.TAVILY_EXTRACT_DEPTH,
  674. "youtube": {
  675. "language": request.app.state.config.YOUTUBE_LOADER_LANGUAGE,
  676. "proxy_url": request.app.state.config.YOUTUBE_LOADER_PROXY_URL,
  677. "translation": request.app.state.YOUTUBE_LOADER_TRANSLATION,
  678. },
  679. },
  680. },
  681. }
  682. @router.get("/template")
  683. async def get_rag_template(request: Request, user=Depends(get_verified_user)):
  684. return {
  685. "status": True,
  686. "template": request.app.state.config.RAG_TEMPLATE,
  687. }
  688. @router.get("/query/settings")
  689. async def get_query_settings(request: Request, user=Depends(get_admin_user)):
  690. return {
  691. "status": True,
  692. "template": request.app.state.config.RAG_TEMPLATE,
  693. "k": request.app.state.config.TOP_K,
  694. "k_reranker": request.app.state.config.TOP_K_RERANKER,
  695. "r": request.app.state.config.RELEVANCE_THRESHOLD,
  696. "hybrid": request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  697. }
  698. class QuerySettingsForm(BaseModel):
  699. k: Optional[int] = None
  700. k_reranker: Optional[int] = None
  701. r: Optional[float] = None
  702. template: Optional[str] = None
  703. hybrid: Optional[bool] = None
  704. @router.post("/query/settings/update")
  705. async def update_query_settings(
  706. request: Request, form_data: QuerySettingsForm, user=Depends(get_admin_user)
  707. ):
  708. request.app.state.config.RAG_TEMPLATE = form_data.template
  709. request.app.state.config.TOP_K = form_data.k if form_data.k else 4
  710. request.app.state.config.TOP_K_RERANKER = form_data.k_reranker or 4
  711. request.app.state.config.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
  712. request.app.state.config.ENABLE_RAG_HYBRID_SEARCH = (
  713. form_data.hybrid if form_data.hybrid else False
  714. )
  715. if not request.app.state.config.ENABLE_RAG_HYBRID_SEARCH:
  716. request.app.state.rf = None
  717. return {
  718. "status": True,
  719. "template": request.app.state.config.RAG_TEMPLATE,
  720. "k": request.app.state.config.TOP_K,
  721. "k_reranker": request.app.state.config.TOP_K_RERANKER,
  722. "r": request.app.state.config.RELEVANCE_THRESHOLD,
  723. "hybrid": request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  724. }
  725. ####################################
  726. #
  727. # Document process and retrieval
  728. #
  729. ####################################
  730. def save_docs_to_vector_db(
  731. request: Request,
  732. docs,
  733. collection_name,
  734. metadata: Optional[dict] = None,
  735. overwrite: bool = False,
  736. split: bool = True,
  737. add: bool = False,
  738. user=None,
  739. ) -> bool:
  740. def _get_docs_info(docs: list[Document]) -> str:
  741. docs_info = set()
  742. # Trying to select relevant metadata identifying the document.
  743. for doc in docs:
  744. metadata = getattr(doc, "metadata", {})
  745. doc_name = metadata.get("name", "")
  746. if not doc_name:
  747. doc_name = metadata.get("title", "")
  748. if not doc_name:
  749. doc_name = metadata.get("source", "")
  750. if doc_name:
  751. docs_info.add(doc_name)
  752. return ", ".join(docs_info)
  753. log.info(
  754. f"save_docs_to_vector_db: document {_get_docs_info(docs)} {collection_name}"
  755. )
  756. # Check if entries with the same hash (metadata.hash) already exist
  757. if metadata and "hash" in metadata:
  758. result = VECTOR_DB_CLIENT.query(
  759. collection_name=collection_name,
  760. filter={"hash": metadata["hash"]},
  761. )
  762. if result is not None:
  763. existing_doc_ids = result.ids[0]
  764. if existing_doc_ids:
  765. log.info(f"Document with hash {metadata['hash']} already exists")
  766. raise ValueError(ERROR_MESSAGES.DUPLICATE_CONTENT)
  767. if split:
  768. if request.app.state.config.TEXT_SPLITTER in ["", "character"]:
  769. text_splitter = RecursiveCharacterTextSplitter(
  770. chunk_size=request.app.state.config.CHUNK_SIZE,
  771. chunk_overlap=request.app.state.config.CHUNK_OVERLAP,
  772. add_start_index=True,
  773. )
  774. elif request.app.state.config.TEXT_SPLITTER == "token":
  775. log.info(
  776. f"Using token text splitter: {request.app.state.config.TIKTOKEN_ENCODING_NAME}"
  777. )
  778. tiktoken.get_encoding(str(request.app.state.config.TIKTOKEN_ENCODING_NAME))
  779. text_splitter = TokenTextSplitter(
  780. encoding_name=str(request.app.state.config.TIKTOKEN_ENCODING_NAME),
  781. chunk_size=request.app.state.config.CHUNK_SIZE,
  782. chunk_overlap=request.app.state.config.CHUNK_OVERLAP,
  783. add_start_index=True,
  784. )
  785. else:
  786. raise ValueError(ERROR_MESSAGES.DEFAULT("Invalid text splitter"))
  787. docs = text_splitter.split_documents(docs)
  788. if len(docs) == 0:
  789. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  790. texts = [doc.page_content for doc in docs]
  791. metadatas = [
  792. {
  793. **doc.metadata,
  794. **(metadata if metadata else {}),
  795. "embedding_config": json.dumps(
  796. {
  797. "engine": request.app.state.config.RAG_EMBEDDING_ENGINE,
  798. "model": request.app.state.config.RAG_EMBEDDING_MODEL,
  799. }
  800. ),
  801. }
  802. for doc in docs
  803. ]
  804. # ChromaDB does not like datetime formats
  805. # for meta-data so convert them to string.
  806. for metadata in metadatas:
  807. for key, value in metadata.items():
  808. if (
  809. isinstance(value, datetime)
  810. or isinstance(value, list)
  811. or isinstance(value, dict)
  812. ):
  813. metadata[key] = str(value)
  814. try:
  815. if VECTOR_DB_CLIENT.has_collection(collection_name=collection_name):
  816. log.info(f"collection {collection_name} already exists")
  817. if overwrite:
  818. VECTOR_DB_CLIENT.delete_collection(collection_name=collection_name)
  819. log.info(f"deleting existing collection {collection_name}")
  820. elif add is False:
  821. log.info(
  822. f"collection {collection_name} already exists, overwrite is False and add is False"
  823. )
  824. return True
  825. log.info(f"adding to collection {collection_name}")
  826. embedding_function = get_embedding_function(
  827. request.app.state.config.RAG_EMBEDDING_ENGINE,
  828. request.app.state.config.RAG_EMBEDDING_MODEL,
  829. request.app.state.ef,
  830. (
  831. request.app.state.config.RAG_OPENAI_API_BASE_URL
  832. if request.app.state.config.RAG_EMBEDDING_ENGINE == "openai"
  833. else request.app.state.config.RAG_OLLAMA_BASE_URL
  834. ),
  835. (
  836. request.app.state.config.RAG_OPENAI_API_KEY
  837. if request.app.state.config.RAG_EMBEDDING_ENGINE == "openai"
  838. else request.app.state.config.RAG_OLLAMA_API_KEY
  839. ),
  840. request.app.state.config.RAG_EMBEDDING_BATCH_SIZE,
  841. )
  842. embeddings = embedding_function(
  843. list(map(lambda x: x.replace("\n", " "), texts)),
  844. prefix=RAG_EMBEDDING_CONTENT_PREFIX,
  845. user=user,
  846. )
  847. items = [
  848. {
  849. "id": str(uuid.uuid4()),
  850. "text": text,
  851. "vector": embeddings[idx],
  852. "metadata": metadatas[idx],
  853. }
  854. for idx, text in enumerate(texts)
  855. ]
  856. VECTOR_DB_CLIENT.insert(
  857. collection_name=collection_name,
  858. items=items,
  859. )
  860. return True
  861. except Exception as e:
  862. log.exception(e)
  863. raise e
  864. class ProcessFileForm(BaseModel):
  865. file_id: str
  866. content: Optional[str] = None
  867. collection_name: Optional[str] = None
  868. @router.post("/process/file")
  869. def process_file(
  870. request: Request,
  871. form_data: ProcessFileForm,
  872. user=Depends(get_verified_user),
  873. ):
  874. try:
  875. file = Files.get_file_by_id(form_data.file_id)
  876. collection_name = form_data.collection_name
  877. if collection_name is None:
  878. collection_name = f"file-{file.id}"
  879. if form_data.content:
  880. # Update the content in the file
  881. # Usage: /files/{file_id}/data/content/update, /files/ (audio file upload pipeline)
  882. try:
  883. # /files/{file_id}/data/content/update
  884. VECTOR_DB_CLIENT.delete_collection(collection_name=f"file-{file.id}")
  885. except:
  886. # Audio file upload pipeline
  887. pass
  888. docs = [
  889. Document(
  890. page_content=form_data.content.replace("<br/>", "\n"),
  891. metadata={
  892. **file.meta,
  893. "name": file.filename,
  894. "created_by": file.user_id,
  895. "file_id": file.id,
  896. "source": file.filename,
  897. },
  898. )
  899. ]
  900. text_content = form_data.content
  901. elif form_data.collection_name:
  902. # Check if the file has already been processed and save the content
  903. # Usage: /knowledge/{id}/file/add, /knowledge/{id}/file/update
  904. result = VECTOR_DB_CLIENT.query(
  905. collection_name=f"file-{file.id}", filter={"file_id": file.id}
  906. )
  907. if result is not None and len(result.ids[0]) > 0:
  908. docs = [
  909. Document(
  910. page_content=result.documents[0][idx],
  911. metadata=result.metadatas[0][idx],
  912. )
  913. for idx, id in enumerate(result.ids[0])
  914. ]
  915. else:
  916. docs = [
  917. Document(
  918. page_content=file.data.get("content", ""),
  919. metadata={
  920. **file.meta,
  921. "name": file.filename,
  922. "created_by": file.user_id,
  923. "file_id": file.id,
  924. "source": file.filename,
  925. },
  926. )
  927. ]
  928. text_content = file.data.get("content", "")
  929. else:
  930. # Process the file and save the content
  931. # Usage: /files/
  932. file_path = file.path
  933. if file_path:
  934. file_path = Storage.get_file(file_path)
  935. loader = Loader(
  936. engine=request.app.state.config.CONTENT_EXTRACTION_ENGINE,
  937. TIKA_SERVER_URL=request.app.state.config.TIKA_SERVER_URL,
  938. DOCLING_SERVER_URL=request.app.state.config.DOCLING_SERVER_URL,
  939. PDF_EXTRACT_IMAGES=request.app.state.config.PDF_EXTRACT_IMAGES,
  940. DOCUMENT_INTELLIGENCE_ENDPOINT=request.app.state.config.DOCUMENT_INTELLIGENCE_ENDPOINT,
  941. DOCUMENT_INTELLIGENCE_KEY=request.app.state.config.DOCUMENT_INTELLIGENCE_KEY,
  942. MISTRAL_OCR_API_KEY=request.app.state.config.MISTRAL_OCR_API_KEY,
  943. )
  944. docs = loader.load(
  945. file.filename, file.meta.get("content_type"), file_path
  946. )
  947. docs = [
  948. Document(
  949. page_content=doc.page_content,
  950. metadata={
  951. **doc.metadata,
  952. "name": file.filename,
  953. "created_by": file.user_id,
  954. "file_id": file.id,
  955. "source": file.filename,
  956. },
  957. )
  958. for doc in docs
  959. ]
  960. else:
  961. docs = [
  962. Document(
  963. page_content=file.data.get("content", ""),
  964. metadata={
  965. **file.meta,
  966. "name": file.filename,
  967. "created_by": file.user_id,
  968. "file_id": file.id,
  969. "source": file.filename,
  970. },
  971. )
  972. ]
  973. text_content = " ".join([doc.page_content for doc in docs])
  974. log.debug(f"text_content: {text_content}")
  975. Files.update_file_data_by_id(
  976. file.id,
  977. {"content": text_content},
  978. )
  979. hash = calculate_sha256_string(text_content)
  980. Files.update_file_hash_by_id(file.id, hash)
  981. if not request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL:
  982. try:
  983. result = save_docs_to_vector_db(
  984. request,
  985. docs=docs,
  986. collection_name=collection_name,
  987. metadata={
  988. "file_id": file.id,
  989. "name": file.filename,
  990. "hash": hash,
  991. },
  992. add=(True if form_data.collection_name else False),
  993. user=user,
  994. )
  995. if result:
  996. Files.update_file_metadata_by_id(
  997. file.id,
  998. {
  999. "collection_name": collection_name,
  1000. },
  1001. )
  1002. return {
  1003. "status": True,
  1004. "collection_name": collection_name,
  1005. "filename": file.filename,
  1006. "content": text_content,
  1007. }
  1008. except Exception as e:
  1009. raise e
  1010. else:
  1011. return {
  1012. "status": True,
  1013. "collection_name": None,
  1014. "filename": file.filename,
  1015. "content": text_content,
  1016. }
  1017. except Exception as e:
  1018. log.exception(e)
  1019. if "No pandoc was found" in str(e):
  1020. raise HTTPException(
  1021. status_code=status.HTTP_400_BAD_REQUEST,
  1022. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  1023. )
  1024. else:
  1025. raise HTTPException(
  1026. status_code=status.HTTP_400_BAD_REQUEST,
  1027. detail=str(e),
  1028. )
  1029. class ProcessTextForm(BaseModel):
  1030. name: str
  1031. content: str
  1032. collection_name: Optional[str] = None
  1033. @router.post("/process/text")
  1034. def process_text(
  1035. request: Request,
  1036. form_data: ProcessTextForm,
  1037. user=Depends(get_verified_user),
  1038. ):
  1039. collection_name = form_data.collection_name
  1040. if collection_name is None:
  1041. collection_name = calculate_sha256_string(form_data.content)
  1042. docs = [
  1043. Document(
  1044. page_content=form_data.content,
  1045. metadata={"name": form_data.name, "created_by": user.id},
  1046. )
  1047. ]
  1048. text_content = form_data.content
  1049. log.debug(f"text_content: {text_content}")
  1050. result = save_docs_to_vector_db(request, docs, collection_name, user=user)
  1051. if result:
  1052. return {
  1053. "status": True,
  1054. "collection_name": collection_name,
  1055. "content": text_content,
  1056. }
  1057. else:
  1058. raise HTTPException(
  1059. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1060. detail=ERROR_MESSAGES.DEFAULT(),
  1061. )
  1062. @router.post("/process/youtube")
  1063. def process_youtube_video(
  1064. request: Request, form_data: ProcessUrlForm, user=Depends(get_verified_user)
  1065. ):
  1066. try:
  1067. collection_name = form_data.collection_name
  1068. if not collection_name:
  1069. collection_name = calculate_sha256_string(form_data.url)[:63]
  1070. loader = YoutubeLoader(
  1071. form_data.url,
  1072. language=request.app.state.config.YOUTUBE_LOADER_LANGUAGE,
  1073. proxy_url=request.app.state.config.YOUTUBE_LOADER_PROXY_URL,
  1074. )
  1075. docs = loader.load()
  1076. content = " ".join([doc.page_content for doc in docs])
  1077. log.debug(f"text_content: {content}")
  1078. save_docs_to_vector_db(
  1079. request, docs, collection_name, overwrite=True, user=user
  1080. )
  1081. return {
  1082. "status": True,
  1083. "collection_name": collection_name,
  1084. "filename": form_data.url,
  1085. "file": {
  1086. "data": {
  1087. "content": content,
  1088. },
  1089. "meta": {
  1090. "name": form_data.url,
  1091. },
  1092. },
  1093. }
  1094. except Exception as e:
  1095. log.exception(e)
  1096. raise HTTPException(
  1097. status_code=status.HTTP_400_BAD_REQUEST,
  1098. detail=ERROR_MESSAGES.DEFAULT(e),
  1099. )
  1100. @router.post("/process/web")
  1101. def process_web(
  1102. request: Request, form_data: ProcessUrlForm, user=Depends(get_verified_user)
  1103. ):
  1104. try:
  1105. collection_name = form_data.collection_name
  1106. if not collection_name:
  1107. collection_name = calculate_sha256_string(form_data.url)[:63]
  1108. loader = get_web_loader(
  1109. form_data.url,
  1110. verify_ssl=request.app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  1111. requests_per_second=request.app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  1112. )
  1113. docs = loader.load()
  1114. content = " ".join([doc.page_content for doc in docs])
  1115. log.debug(f"text_content: {content}")
  1116. if not request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL:
  1117. save_docs_to_vector_db(
  1118. request, docs, collection_name, overwrite=True, user=user
  1119. )
  1120. else:
  1121. collection_name = None
  1122. return {
  1123. "status": True,
  1124. "collection_name": collection_name,
  1125. "filename": form_data.url,
  1126. "file": {
  1127. "data": {
  1128. "content": content,
  1129. },
  1130. "meta": {
  1131. "name": form_data.url,
  1132. "source": form_data.url,
  1133. },
  1134. },
  1135. }
  1136. except Exception as e:
  1137. log.exception(e)
  1138. raise HTTPException(
  1139. status_code=status.HTTP_400_BAD_REQUEST,
  1140. detail=ERROR_MESSAGES.DEFAULT(e),
  1141. )
  1142. def search_web(request: Request, engine: str, query: str) -> list[SearchResult]:
  1143. """Search the web using a search engine and return the results as a list of SearchResult objects.
  1144. Will look for a search engine API key in environment variables in the following order:
  1145. - SEARXNG_QUERY_URL
  1146. - GOOGLE_PSE_API_KEY + GOOGLE_PSE_ENGINE_ID
  1147. - BRAVE_SEARCH_API_KEY
  1148. - KAGI_SEARCH_API_KEY
  1149. - MOJEEK_SEARCH_API_KEY
  1150. - BOCHA_SEARCH_API_KEY
  1151. - SERPSTACK_API_KEY
  1152. - SERPER_API_KEY
  1153. - SERPLY_API_KEY
  1154. - TAVILY_API_KEY
  1155. - EXA_API_KEY
  1156. - PERPLEXITY_API_KEY
  1157. - SOUGOU_API_SID + SOUGOU_API_SK
  1158. - SEARCHAPI_API_KEY + SEARCHAPI_ENGINE (by default `google`)
  1159. - SERPAPI_API_KEY + SERPAPI_ENGINE (by default `google`)
  1160. Args:
  1161. query (str): The query to search for
  1162. """
  1163. # TODO: add playwright to search the web
  1164. if engine == "searxng":
  1165. if request.app.state.config.SEARXNG_QUERY_URL:
  1166. return search_searxng(
  1167. request.app.state.config.SEARXNG_QUERY_URL,
  1168. query,
  1169. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1170. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1171. )
  1172. else:
  1173. raise Exception("No SEARXNG_QUERY_URL found in environment variables")
  1174. elif engine == "google_pse":
  1175. if (
  1176. request.app.state.config.GOOGLE_PSE_API_KEY
  1177. and request.app.state.config.GOOGLE_PSE_ENGINE_ID
  1178. ):
  1179. return search_google_pse(
  1180. request.app.state.config.GOOGLE_PSE_API_KEY,
  1181. request.app.state.config.GOOGLE_PSE_ENGINE_ID,
  1182. query,
  1183. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1184. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1185. )
  1186. else:
  1187. raise Exception(
  1188. "No GOOGLE_PSE_API_KEY or GOOGLE_PSE_ENGINE_ID found in environment variables"
  1189. )
  1190. elif engine == "brave":
  1191. if request.app.state.config.BRAVE_SEARCH_API_KEY:
  1192. return search_brave(
  1193. request.app.state.config.BRAVE_SEARCH_API_KEY,
  1194. query,
  1195. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1196. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1197. )
  1198. else:
  1199. raise Exception("No BRAVE_SEARCH_API_KEY found in environment variables")
  1200. elif engine == "kagi":
  1201. if request.app.state.config.KAGI_SEARCH_API_KEY:
  1202. return search_kagi(
  1203. request.app.state.config.KAGI_SEARCH_API_KEY,
  1204. query,
  1205. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1206. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1207. )
  1208. else:
  1209. raise Exception("No KAGI_SEARCH_API_KEY found in environment variables")
  1210. elif engine == "mojeek":
  1211. if request.app.state.config.MOJEEK_SEARCH_API_KEY:
  1212. return search_mojeek(
  1213. request.app.state.config.MOJEEK_SEARCH_API_KEY,
  1214. query,
  1215. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1216. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1217. )
  1218. else:
  1219. raise Exception("No MOJEEK_SEARCH_API_KEY found in environment variables")
  1220. elif engine == "bocha":
  1221. if request.app.state.config.BOCHA_SEARCH_API_KEY:
  1222. return search_bocha(
  1223. request.app.state.config.BOCHA_SEARCH_API_KEY,
  1224. query,
  1225. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1226. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1227. )
  1228. else:
  1229. raise Exception("No BOCHA_SEARCH_API_KEY found in environment variables")
  1230. elif engine == "serpstack":
  1231. if request.app.state.config.SERPSTACK_API_KEY:
  1232. return search_serpstack(
  1233. request.app.state.config.SERPSTACK_API_KEY,
  1234. query,
  1235. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1236. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1237. https_enabled=request.app.state.config.SERPSTACK_HTTPS,
  1238. )
  1239. else:
  1240. raise Exception("No SERPSTACK_API_KEY found in environment variables")
  1241. elif engine == "serper":
  1242. if request.app.state.config.SERPER_API_KEY:
  1243. return search_serper(
  1244. request.app.state.config.SERPER_API_KEY,
  1245. query,
  1246. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1247. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1248. )
  1249. else:
  1250. raise Exception("No SERPER_API_KEY found in environment variables")
  1251. elif engine == "serply":
  1252. if request.app.state.config.SERPLY_API_KEY:
  1253. return search_serply(
  1254. request.app.state.config.SERPLY_API_KEY,
  1255. query,
  1256. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1257. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1258. )
  1259. else:
  1260. raise Exception("No SERPLY_API_KEY found in environment variables")
  1261. elif engine == "duckduckgo":
  1262. return search_duckduckgo(
  1263. query,
  1264. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1265. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1266. )
  1267. elif engine == "tavily":
  1268. if request.app.state.config.TAVILY_API_KEY:
  1269. return search_tavily(
  1270. request.app.state.config.TAVILY_API_KEY,
  1271. query,
  1272. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1273. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1274. )
  1275. else:
  1276. raise Exception("No TAVILY_API_KEY found in environment variables")
  1277. elif engine == "searchapi":
  1278. if request.app.state.config.SEARCHAPI_API_KEY:
  1279. return search_searchapi(
  1280. request.app.state.config.SEARCHAPI_API_KEY,
  1281. request.app.state.config.SEARCHAPI_ENGINE,
  1282. query,
  1283. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1284. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1285. )
  1286. else:
  1287. raise Exception("No SEARCHAPI_API_KEY found in environment variables")
  1288. elif engine == "serpapi":
  1289. if request.app.state.config.SERPAPI_API_KEY:
  1290. return search_serpapi(
  1291. request.app.state.config.SERPAPI_API_KEY,
  1292. request.app.state.config.SERPAPI_ENGINE,
  1293. query,
  1294. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1295. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1296. )
  1297. else:
  1298. raise Exception("No SERPAPI_API_KEY found in environment variables")
  1299. elif engine == "jina":
  1300. return search_jina(
  1301. request.app.state.config.JINA_API_KEY,
  1302. query,
  1303. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1304. )
  1305. elif engine == "bing":
  1306. return search_bing(
  1307. request.app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY,
  1308. request.app.state.config.BING_SEARCH_V7_ENDPOINT,
  1309. str(DEFAULT_LOCALE),
  1310. query,
  1311. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1312. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1313. )
  1314. elif engine == "exa":
  1315. return search_exa(
  1316. request.app.state.config.EXA_API_KEY,
  1317. query,
  1318. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1319. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1320. )
  1321. elif engine == "perplexity":
  1322. return search_perplexity(
  1323. request.app.state.config.PERPLEXITY_API_KEY,
  1324. query,
  1325. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1326. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1327. )
  1328. elif engine == 'sougou':
  1329. if request.app.state.config.SOUGOU_API_SID and request.app.state.config.SOUGOU_API_SK:
  1330. return search_sougou(
  1331. request.app.state.config.SOUGOU_API_SID,
  1332. request.app.state.config.SOUGOU_API_SK,
  1333. query,
  1334. request.app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  1335. request.app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  1336. )
  1337. else:
  1338. raise Exception("No SOUGOU_API_SID or SOUGOU_API_SK found in environment variables")
  1339. else:
  1340. raise Exception("No search engine API key found in environment variables")
  1341. @router.post("/process/web/search")
  1342. async def process_web_search(
  1343. request: Request, form_data: SearchForm, user=Depends(get_verified_user)
  1344. ):
  1345. try:
  1346. logging.info(
  1347. f"trying to web search with {request.app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query}"
  1348. )
  1349. web_results = search_web(
  1350. request, request.app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query
  1351. )
  1352. except Exception as e:
  1353. log.exception(e)
  1354. raise HTTPException(
  1355. status_code=status.HTTP_400_BAD_REQUEST,
  1356. detail=ERROR_MESSAGES.WEB_SEARCH_ERROR(e),
  1357. )
  1358. log.debug(f"web_results: {web_results}")
  1359. try:
  1360. urls = [result.link for result in web_results]
  1361. loader = get_web_loader(
  1362. urls,
  1363. verify_ssl=request.app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  1364. requests_per_second=request.app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  1365. trust_env=request.app.state.config.RAG_WEB_SEARCH_TRUST_ENV,
  1366. )
  1367. docs = await loader.aload()
  1368. urls = [
  1369. doc.metadata["source"] for doc in docs
  1370. ] # only keep URLs which could be retrieved
  1371. if request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL:
  1372. return {
  1373. "status": True,
  1374. "collection_name": None,
  1375. "filenames": urls,
  1376. "docs": [
  1377. {
  1378. "content": doc.page_content,
  1379. "metadata": doc.metadata,
  1380. }
  1381. for doc in docs
  1382. ],
  1383. "loaded_count": len(docs),
  1384. }
  1385. else:
  1386. collection_names = []
  1387. for doc_idx, doc in enumerate(docs):
  1388. collection_name = f"web-search-{calculate_sha256_string(form_data.query + '-' + urls[doc_idx])}"[
  1389. :63
  1390. ]
  1391. collection_names.append(collection_name)
  1392. await run_in_threadpool(
  1393. save_docs_to_vector_db,
  1394. request,
  1395. [doc],
  1396. collection_name,
  1397. overwrite=True,
  1398. user=user,
  1399. )
  1400. return {
  1401. "status": True,
  1402. "collection_names": collection_names,
  1403. "filenames": urls,
  1404. "loaded_count": len(docs),
  1405. }
  1406. except Exception as e:
  1407. log.exception(e)
  1408. raise HTTPException(
  1409. status_code=status.HTTP_400_BAD_REQUEST,
  1410. detail=ERROR_MESSAGES.DEFAULT(e),
  1411. )
  1412. class QueryDocForm(BaseModel):
  1413. collection_name: str
  1414. query: str
  1415. k: Optional[int] = None
  1416. k_reranker: Optional[int] = None
  1417. r: Optional[float] = None
  1418. hybrid: Optional[bool] = None
  1419. @router.post("/query/doc")
  1420. def query_doc_handler(
  1421. request: Request,
  1422. form_data: QueryDocForm,
  1423. user=Depends(get_verified_user),
  1424. ):
  1425. try:
  1426. if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH:
  1427. collection_results = {}
  1428. collection_results[form_data.collection_name] = VECTOR_DB_CLIENT.get(
  1429. collection_name=form_data.collection_name
  1430. )
  1431. return query_doc_with_hybrid_search(
  1432. collection_name=form_data.collection_name,
  1433. collection_result=collection_results[form_data.collection_name],
  1434. query=form_data.query,
  1435. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  1436. query, prefix=prefix, user=user
  1437. ),
  1438. k=form_data.k if form_data.k else request.app.state.config.TOP_K,
  1439. reranking_function=request.app.state.rf,
  1440. k_reranker=form_data.k_reranker
  1441. or request.app.state.config.TOP_K_RERANKER,
  1442. r=(
  1443. form_data.r
  1444. if form_data.r
  1445. else request.app.state.config.RELEVANCE_THRESHOLD
  1446. ),
  1447. user=user,
  1448. )
  1449. else:
  1450. return query_doc(
  1451. collection_name=form_data.collection_name,
  1452. query_embedding=request.app.state.EMBEDDING_FUNCTION(
  1453. form_data.query, prefix=RAG_EMBEDDING_QUERY_PREFIX, user=user
  1454. ),
  1455. k=form_data.k if form_data.k else request.app.state.config.TOP_K,
  1456. user=user,
  1457. )
  1458. except Exception as e:
  1459. log.exception(e)
  1460. raise HTTPException(
  1461. status_code=status.HTTP_400_BAD_REQUEST,
  1462. detail=ERROR_MESSAGES.DEFAULT(e),
  1463. )
  1464. class QueryCollectionsForm(BaseModel):
  1465. collection_names: list[str]
  1466. query: str
  1467. k: Optional[int] = None
  1468. k_reranker: Optional[int] = None
  1469. r: Optional[float] = None
  1470. hybrid: Optional[bool] = None
  1471. @router.post("/query/collection")
  1472. def query_collection_handler(
  1473. request: Request,
  1474. form_data: QueryCollectionsForm,
  1475. user=Depends(get_verified_user),
  1476. ):
  1477. try:
  1478. if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH:
  1479. return query_collection_with_hybrid_search(
  1480. collection_names=form_data.collection_names,
  1481. queries=[form_data.query],
  1482. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  1483. query, prefix=prefix, user=user
  1484. ),
  1485. k=form_data.k if form_data.k else request.app.state.config.TOP_K,
  1486. reranking_function=request.app.state.rf,
  1487. k_reranker=form_data.k_reranker
  1488. or request.app.state.config.TOP_K_RERANKER,
  1489. r=(
  1490. form_data.r
  1491. if form_data.r
  1492. else request.app.state.config.RELEVANCE_THRESHOLD
  1493. ),
  1494. )
  1495. else:
  1496. return query_collection(
  1497. collection_names=form_data.collection_names,
  1498. queries=[form_data.query],
  1499. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  1500. query, prefix=prefix, user=user
  1501. ),
  1502. k=form_data.k if form_data.k else request.app.state.config.TOP_K,
  1503. )
  1504. except Exception as e:
  1505. log.exception(e)
  1506. raise HTTPException(
  1507. status_code=status.HTTP_400_BAD_REQUEST,
  1508. detail=ERROR_MESSAGES.DEFAULT(e),
  1509. )
  1510. ####################################
  1511. #
  1512. # Vector DB operations
  1513. #
  1514. ####################################
  1515. class DeleteForm(BaseModel):
  1516. collection_name: str
  1517. file_id: str
  1518. @router.post("/delete")
  1519. def delete_entries_from_collection(form_data: DeleteForm, user=Depends(get_admin_user)):
  1520. try:
  1521. if VECTOR_DB_CLIENT.has_collection(collection_name=form_data.collection_name):
  1522. file = Files.get_file_by_id(form_data.file_id)
  1523. hash = file.hash
  1524. VECTOR_DB_CLIENT.delete(
  1525. collection_name=form_data.collection_name,
  1526. metadata={"hash": hash},
  1527. )
  1528. return {"status": True}
  1529. else:
  1530. return {"status": False}
  1531. except Exception as e:
  1532. log.exception(e)
  1533. return {"status": False}
  1534. @router.post("/reset/db")
  1535. def reset_vector_db(user=Depends(get_admin_user)):
  1536. VECTOR_DB_CLIENT.reset()
  1537. Knowledges.delete_all_knowledge()
  1538. @router.post("/reset/uploads")
  1539. def reset_upload_dir(user=Depends(get_admin_user)) -> bool:
  1540. folder = f"{UPLOAD_DIR}"
  1541. try:
  1542. # Check if the directory exists
  1543. if os.path.exists(folder):
  1544. # Iterate over all the files and directories in the specified directory
  1545. for filename in os.listdir(folder):
  1546. file_path = os.path.join(folder, filename)
  1547. try:
  1548. if os.path.isfile(file_path) or os.path.islink(file_path):
  1549. os.unlink(file_path) # Remove the file or link
  1550. elif os.path.isdir(file_path):
  1551. shutil.rmtree(file_path) # Remove the directory
  1552. except Exception as e:
  1553. log.exception(f"Failed to delete {file_path}. Reason: {e}")
  1554. else:
  1555. log.warning(f"The directory {folder} does not exist")
  1556. except Exception as e:
  1557. log.exception(f"Failed to process the directory {folder}. Reason: {e}")
  1558. return True
  1559. if ENV == "dev":
  1560. @router.get("/ef/{text}")
  1561. async def get_embeddings(request: Request, text: Optional[str] = "Hello World!"):
  1562. return {
  1563. "result": request.app.state.EMBEDDING_FUNCTION(
  1564. text, prefix=RAG_EMBEDDING_QUERY_PREFIX
  1565. )
  1566. }
  1567. class BatchProcessFilesForm(BaseModel):
  1568. files: List[FileModel]
  1569. collection_name: str
  1570. class BatchProcessFilesResult(BaseModel):
  1571. file_id: str
  1572. status: str
  1573. error: Optional[str] = None
  1574. class BatchProcessFilesResponse(BaseModel):
  1575. results: List[BatchProcessFilesResult]
  1576. errors: List[BatchProcessFilesResult]
  1577. @router.post("/process/files/batch")
  1578. def process_files_batch(
  1579. request: Request,
  1580. form_data: BatchProcessFilesForm,
  1581. user=Depends(get_verified_user),
  1582. ) -> BatchProcessFilesResponse:
  1583. """
  1584. Process a batch of files and save them to the vector database.
  1585. """
  1586. results: List[BatchProcessFilesResult] = []
  1587. errors: List[BatchProcessFilesResult] = []
  1588. collection_name = form_data.collection_name
  1589. # Prepare all documents first
  1590. all_docs: List[Document] = []
  1591. for file in form_data.files:
  1592. try:
  1593. text_content = file.data.get("content", "")
  1594. docs: List[Document] = [
  1595. Document(
  1596. page_content=text_content.replace("<br/>", "\n"),
  1597. metadata={
  1598. **file.meta,
  1599. "name": file.filename,
  1600. "created_by": file.user_id,
  1601. "file_id": file.id,
  1602. "source": file.filename,
  1603. },
  1604. )
  1605. ]
  1606. hash = calculate_sha256_string(text_content)
  1607. Files.update_file_hash_by_id(file.id, hash)
  1608. Files.update_file_data_by_id(file.id, {"content": text_content})
  1609. all_docs.extend(docs)
  1610. results.append(BatchProcessFilesResult(file_id=file.id, status="prepared"))
  1611. except Exception as e:
  1612. log.error(f"process_files_batch: Error processing file {file.id}: {str(e)}")
  1613. errors.append(
  1614. BatchProcessFilesResult(file_id=file.id, status="failed", error=str(e))
  1615. )
  1616. # Save all documents in one batch
  1617. if all_docs:
  1618. try:
  1619. save_docs_to_vector_db(
  1620. request=request,
  1621. docs=all_docs,
  1622. collection_name=collection_name,
  1623. add=True,
  1624. user=user,
  1625. )
  1626. # Update all files with collection name
  1627. for result in results:
  1628. Files.update_file_metadata_by_id(
  1629. result.file_id, {"collection_name": collection_name}
  1630. )
  1631. result.status = "completed"
  1632. except Exception as e:
  1633. log.error(
  1634. f"process_files_batch: Error saving documents to vector DB: {str(e)}"
  1635. )
  1636. for result in results:
  1637. result.status = "failed"
  1638. errors.append(
  1639. BatchProcessFilesResult(file_id=result.file_id, error=str(e))
  1640. )
  1641. return BatchProcessFilesResponse(results=results, errors=errors)