retrieval.py 62 KB

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