main.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. from fastapi import (
  2. FastAPI,
  3. Depends,
  4. HTTPException,
  5. status,
  6. UploadFile,
  7. File,
  8. Form,
  9. )
  10. from fastapi.middleware.cors import CORSMiddleware
  11. import os, shutil, logging, re
  12. from pathlib import Path
  13. from typing import List, Union, Sequence
  14. from chromadb.utils.batch_utils import create_batches
  15. from langchain_community.document_loaders import (
  16. WebBaseLoader,
  17. TextLoader,
  18. PyPDFLoader,
  19. CSVLoader,
  20. BSHTMLLoader,
  21. Docx2txtLoader,
  22. UnstructuredEPubLoader,
  23. UnstructuredWordDocumentLoader,
  24. UnstructuredMarkdownLoader,
  25. UnstructuredXMLLoader,
  26. UnstructuredRSTLoader,
  27. UnstructuredExcelLoader,
  28. UnstructuredPowerPointLoader,
  29. YoutubeLoader,
  30. )
  31. from langchain.text_splitter import RecursiveCharacterTextSplitter
  32. import validators
  33. import urllib.parse
  34. import socket
  35. from pydantic import BaseModel
  36. from typing import Optional
  37. import mimetypes
  38. import uuid
  39. import json
  40. import sentence_transformers
  41. from apps.webui.models.documents import (
  42. Documents,
  43. DocumentForm,
  44. DocumentResponse,
  45. )
  46. from apps.rag.utils import (
  47. get_model_path,
  48. get_embedding_function,
  49. query_doc,
  50. query_doc_with_hybrid_search,
  51. query_collection,
  52. query_collection_with_hybrid_search,
  53. )
  54. from apps.rag.search.brave import search_brave
  55. from apps.rag.search.google_pse import search_google_pse
  56. from apps.rag.search.main import SearchResult
  57. from apps.rag.search.searxng import search_searxng
  58. from apps.rag.search.serper import search_serper
  59. from apps.rag.search.serpstack import search_serpstack
  60. from utils.misc import (
  61. calculate_sha256,
  62. calculate_sha256_string,
  63. sanitize_filename,
  64. extract_folders_after_data_docs,
  65. )
  66. from utils.utils import get_current_user, get_admin_user
  67. from config import (
  68. ENV,
  69. SRC_LOG_LEVELS,
  70. UPLOAD_DIR,
  71. DOCS_DIR,
  72. RAG_TOP_K,
  73. RAG_RELEVANCE_THRESHOLD,
  74. RAG_EMBEDDING_ENGINE,
  75. RAG_EMBEDDING_MODEL,
  76. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  77. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  78. ENABLE_RAG_HYBRID_SEARCH,
  79. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  80. RAG_RERANKING_MODEL,
  81. PDF_EXTRACT_IMAGES,
  82. RAG_RERANKING_MODEL_AUTO_UPDATE,
  83. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  84. RAG_OPENAI_API_BASE_URL,
  85. RAG_OPENAI_API_KEY,
  86. DEVICE_TYPE,
  87. CHROMA_CLIENT,
  88. CHUNK_SIZE,
  89. CHUNK_OVERLAP,
  90. RAG_TEMPLATE,
  91. ENABLE_RAG_LOCAL_WEB_FETCH,
  92. YOUTUBE_LOADER_LANGUAGE,
  93. ENABLE_RAG_WEB_SEARCH,
  94. RAG_WEB_SEARCH_ENGINE,
  95. SEARXNG_QUERY_URL,
  96. GOOGLE_PSE_API_KEY,
  97. GOOGLE_PSE_ENGINE_ID,
  98. BRAVE_SEARCH_API_KEY,
  99. SERPSTACK_API_KEY,
  100. SERPSTACK_HTTPS,
  101. SERPER_API_KEY,
  102. RAG_WEB_SEARCH_RESULT_COUNT,
  103. RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  104. AppConfig,
  105. )
  106. from constants import ERROR_MESSAGES
  107. log = logging.getLogger(__name__)
  108. log.setLevel(SRC_LOG_LEVELS["RAG"])
  109. app = FastAPI()
  110. app.state.config = AppConfig()
  111. app.state.config.TOP_K = RAG_TOP_K
  112. app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
  113. app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
  114. app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
  115. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
  116. )
  117. app.state.config.CHUNK_SIZE = CHUNK_SIZE
  118. app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
  119. app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
  120. app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  121. app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
  122. app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
  123. app.state.config.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
  124. app.state.config.OPENAI_API_KEY = RAG_OPENAI_API_KEY
  125. app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
  126. app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
  127. app.state.YOUTUBE_LOADER_TRANSLATION = None
  128. app.state.config.ENABLE_RAG_WEB_SEARCH = ENABLE_RAG_WEB_SEARCH
  129. app.state.config.RAG_WEB_SEARCH_ENGINE = RAG_WEB_SEARCH_ENGINE
  130. app.state.config.SEARXNG_QUERY_URL = SEARXNG_QUERY_URL
  131. app.state.config.GOOGLE_PSE_API_KEY = GOOGLE_PSE_API_KEY
  132. app.state.config.GOOGLE_PSE_ENGINE_ID = GOOGLE_PSE_ENGINE_ID
  133. app.state.config.BRAVE_SEARCH_API_KEY = BRAVE_SEARCH_API_KEY
  134. app.state.config.SERPSTACK_API_KEY = SERPSTACK_API_KEY
  135. app.state.config.SERPSTACK_HTTPS = SERPSTACK_HTTPS
  136. app.state.config.SERPER_API_KEY = SERPER_API_KEY
  137. app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = RAG_WEB_SEARCH_RESULT_COUNT
  138. app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = RAG_WEB_SEARCH_CONCURRENT_REQUESTS
  139. def update_embedding_model(
  140. embedding_model: str,
  141. update_model: bool = False,
  142. ):
  143. if embedding_model and app.state.config.RAG_EMBEDDING_ENGINE == "":
  144. app.state.sentence_transformer_ef = sentence_transformers.SentenceTransformer(
  145. get_model_path(embedding_model, update_model),
  146. device=DEVICE_TYPE,
  147. trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  148. )
  149. else:
  150. app.state.sentence_transformer_ef = None
  151. def update_reranking_model(
  152. reranking_model: str,
  153. update_model: bool = False,
  154. ):
  155. if reranking_model:
  156. app.state.sentence_transformer_rf = sentence_transformers.CrossEncoder(
  157. get_model_path(reranking_model, update_model),
  158. device=DEVICE_TYPE,
  159. trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  160. )
  161. else:
  162. app.state.sentence_transformer_rf = None
  163. update_embedding_model(
  164. app.state.config.RAG_EMBEDDING_MODEL,
  165. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  166. )
  167. update_reranking_model(
  168. app.state.config.RAG_RERANKING_MODEL,
  169. RAG_RERANKING_MODEL_AUTO_UPDATE,
  170. )
  171. app.state.EMBEDDING_FUNCTION = get_embedding_function(
  172. app.state.config.RAG_EMBEDDING_ENGINE,
  173. app.state.config.RAG_EMBEDDING_MODEL,
  174. app.state.sentence_transformer_ef,
  175. app.state.config.OPENAI_API_KEY,
  176. app.state.config.OPENAI_API_BASE_URL,
  177. )
  178. origins = ["*"]
  179. app.add_middleware(
  180. CORSMiddleware,
  181. allow_origins=origins,
  182. allow_credentials=True,
  183. allow_methods=["*"],
  184. allow_headers=["*"],
  185. )
  186. class CollectionNameForm(BaseModel):
  187. collection_name: Optional[str] = "test"
  188. class UrlForm(CollectionNameForm):
  189. url: str
  190. class SearchForm(CollectionNameForm):
  191. query: str
  192. @app.get("/")
  193. async def get_status():
  194. return {
  195. "status": True,
  196. "chunk_size": app.state.config.CHUNK_SIZE,
  197. "chunk_overlap": app.state.config.CHUNK_OVERLAP,
  198. "template": app.state.config.RAG_TEMPLATE,
  199. "embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
  200. "embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
  201. "reranking_model": app.state.config.RAG_RERANKING_MODEL,
  202. }
  203. @app.get("/embedding")
  204. async def get_embedding_config(user=Depends(get_admin_user)):
  205. return {
  206. "status": True,
  207. "embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
  208. "embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
  209. "openai_config": {
  210. "url": app.state.config.OPENAI_API_BASE_URL,
  211. "key": app.state.config.OPENAI_API_KEY,
  212. },
  213. }
  214. @app.get("/reranking")
  215. async def get_reraanking_config(user=Depends(get_admin_user)):
  216. return {
  217. "status": True,
  218. "reranking_model": app.state.config.RAG_RERANKING_MODEL,
  219. }
  220. class OpenAIConfigForm(BaseModel):
  221. url: str
  222. key: str
  223. class EmbeddingModelUpdateForm(BaseModel):
  224. openai_config: Optional[OpenAIConfigForm] = None
  225. embedding_engine: str
  226. embedding_model: str
  227. @app.post("/embedding/update")
  228. async def update_embedding_config(
  229. form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
  230. ):
  231. log.info(
  232. f"Updating embedding model: {app.state.config.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
  233. )
  234. try:
  235. app.state.config.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
  236. app.state.config.RAG_EMBEDDING_MODEL = form_data.embedding_model
  237. if app.state.config.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
  238. if form_data.openai_config != None:
  239. app.state.config.OPENAI_API_BASE_URL = form_data.openai_config.url
  240. app.state.config.OPENAI_API_KEY = form_data.openai_config.key
  241. update_embedding_model(app.state.config.RAG_EMBEDDING_MODEL)
  242. app.state.EMBEDDING_FUNCTION = get_embedding_function(
  243. app.state.config.RAG_EMBEDDING_ENGINE,
  244. app.state.config.RAG_EMBEDDING_MODEL,
  245. app.state.sentence_transformer_ef,
  246. app.state.config.OPENAI_API_KEY,
  247. app.state.config.OPENAI_API_BASE_URL,
  248. )
  249. return {
  250. "status": True,
  251. "embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
  252. "embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
  253. "openai_config": {
  254. "url": app.state.config.OPENAI_API_BASE_URL,
  255. "key": app.state.config.OPENAI_API_KEY,
  256. },
  257. }
  258. except Exception as e:
  259. log.exception(f"Problem updating embedding model: {e}")
  260. raise HTTPException(
  261. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  262. detail=ERROR_MESSAGES.DEFAULT(e),
  263. )
  264. class RerankingModelUpdateForm(BaseModel):
  265. reranking_model: str
  266. @app.post("/reranking/update")
  267. async def update_reranking_config(
  268. form_data: RerankingModelUpdateForm, user=Depends(get_admin_user)
  269. ):
  270. log.info(
  271. f"Updating reranking model: {app.state.config.RAG_RERANKING_MODEL} to {form_data.reranking_model}"
  272. )
  273. try:
  274. app.state.config.RAG_RERANKING_MODEL = form_data.reranking_model
  275. update_reranking_model(app.state.config.RAG_RERANKING_MODEL), True
  276. return {
  277. "status": True,
  278. "reranking_model": app.state.config.RAG_RERANKING_MODEL,
  279. }
  280. except Exception as e:
  281. log.exception(f"Problem updating reranking model: {e}")
  282. raise HTTPException(
  283. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  284. detail=ERROR_MESSAGES.DEFAULT(e),
  285. )
  286. @app.get("/config")
  287. async def get_rag_config(user=Depends(get_admin_user)):
  288. return {
  289. "status": True,
  290. "pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
  291. "chunk": {
  292. "chunk_size": app.state.config.CHUNK_SIZE,
  293. "chunk_overlap": app.state.config.CHUNK_OVERLAP,
  294. },
  295. "youtube": {
  296. "language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
  297. "translation": app.state.YOUTUBE_LOADER_TRANSLATION,
  298. },
  299. "web": {
  300. "ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  301. "search": {
  302. "enable": app.state.config.ENABLE_RAG_WEB_SEARCH,
  303. "engine": app.state.config.RAG_WEB_SEARCH_ENGINE,
  304. "searxng_query_url": app.state.config.SEARXNG_QUERY_URL,
  305. "google_pse_api_key": app.state.config.GOOGLE_PSE_API_KEY,
  306. "google_pse_engine_id": app.state.config.GOOGLE_PSE_ENGINE_ID,
  307. "brave_search_api_key": app.state.config.BRAVE_SEARCH_API_KEY,
  308. "serpstack_api_key": app.state.config.SERPSTACK_API_KEY,
  309. "serpstack_https": app.state.config.SERPSTACK_HTTPS,
  310. "serper_api_key": app.state.config.SERPER_API_KEY,
  311. "result_count": app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  312. "concurrent_requests": app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  313. },
  314. },
  315. }
  316. class ChunkParamUpdateForm(BaseModel):
  317. chunk_size: int
  318. chunk_overlap: int
  319. class YoutubeLoaderConfig(BaseModel):
  320. language: List[str]
  321. translation: Optional[str] = None
  322. class WebSearchConfig(BaseModel):
  323. enable: bool
  324. engine: Optional[str] = None
  325. searxng_query_url: Optional[str] = None
  326. google_pse_api_key: Optional[str] = None
  327. google_pse_engine_id: Optional[str] = None
  328. brave_search_api_key: Optional[str] = None
  329. serpstack_api_key: Optional[str] = None
  330. serpstack_https: Optional[bool] = None
  331. serper_api_key: Optional[str] = None
  332. result_count: Optional[int] = None
  333. concurrent_requests: Optional[int] = None
  334. class WebConfig(BaseModel):
  335. search: WebSearchConfig
  336. web_loader_ssl_verification: Optional[bool] = None
  337. class ConfigUpdateForm(BaseModel):
  338. pdf_extract_images: Optional[bool] = None
  339. chunk: Optional[ChunkParamUpdateForm] = None
  340. youtube: Optional[YoutubeLoaderConfig] = None
  341. web: Optional[WebConfig] = None
  342. @app.post("/config/update")
  343. async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
  344. app.state.config.PDF_EXTRACT_IMAGES = (
  345. form_data.pdf_extract_images
  346. if form_data.pdf_extract_images is not None
  347. else app.state.config.PDF_EXTRACT_IMAGES
  348. )
  349. if form_data.chunk is not None:
  350. app.state.config.CHUNK_SIZE = form_data.chunk.chunk_size
  351. app.state.config.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
  352. if form_data.youtube is not None:
  353. app.state.config.YOUTUBE_LOADER_LANGUAGE = form_data.youtube.language
  354. app.state.YOUTUBE_LOADER_TRANSLATION = form_data.youtube.translation
  355. if form_data.web is not None:
  356. app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
  357. form_data.web.web_loader_ssl_verification
  358. )
  359. app.state.config.ENABLE_RAG_WEB_SEARCH = form_data.web.search.enable
  360. app.state.config.RAG_WEB_SEARCH_ENGINE = form_data.web.search.engine
  361. app.state.config.SEARXNG_QUERY_URL = form_data.web.search.searxng_query_url
  362. app.state.config.GOOGLE_PSE_API_KEY = form_data.web.search.google_pse_api_key
  363. app.state.config.GOOGLE_PSE_ENGINE_ID = (
  364. form_data.web.search.google_pse_engine_id
  365. )
  366. app.state.config.BRAVE_SEARCH_API_KEY = (
  367. form_data.web.search.brave_search_api_key
  368. )
  369. app.state.config.SERPSTACK_API_KEY = form_data.web.search.serpstack_api_key
  370. app.state.config.SERPSTACK_HTTPS = form_data.web.search.serpstack_https
  371. app.state.config.SERPER_API_KEY = form_data.web.search.serper_api_key
  372. app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = form_data.web.search.result_count
  373. app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = (
  374. form_data.web.search.concurrent_requests
  375. )
  376. return {
  377. "status": True,
  378. "pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
  379. "chunk": {
  380. "chunk_size": app.state.config.CHUNK_SIZE,
  381. "chunk_overlap": app.state.config.CHUNK_OVERLAP,
  382. },
  383. "youtube": {
  384. "language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
  385. "translation": app.state.YOUTUBE_LOADER_TRANSLATION,
  386. },
  387. "web": {
  388. "ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  389. "search": {
  390. "enable": app.state.config.ENABLE_RAG_WEB_SEARCH,
  391. "engine": app.state.config.RAG_WEB_SEARCH_ENGINE,
  392. "searxng_query_url": app.state.config.SEARXNG_QUERY_URL,
  393. "google_pse_api_key": app.state.config.GOOGLE_PSE_API_KEY,
  394. "google_pse_engine_id": app.state.config.GOOGLE_PSE_ENGINE_ID,
  395. "brave_search_api_key": app.state.config.BRAVE_SEARCH_API_KEY,
  396. "serpstack_api_key": app.state.config.SERPSTACK_API_KEY,
  397. "serpstack_https": app.state.config.SERPSTACK_HTTPS,
  398. "serper_api_key": app.state.config.SERPER_API_KEY,
  399. "result_count": app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
  400. "concurrent_requests": app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  401. },
  402. },
  403. }
  404. @app.get("/template")
  405. async def get_rag_template(user=Depends(get_current_user)):
  406. return {
  407. "status": True,
  408. "template": app.state.config.RAG_TEMPLATE,
  409. }
  410. @app.get("/query/settings")
  411. async def get_query_settings(user=Depends(get_admin_user)):
  412. return {
  413. "status": True,
  414. "template": app.state.config.RAG_TEMPLATE,
  415. "k": app.state.config.TOP_K,
  416. "r": app.state.config.RELEVANCE_THRESHOLD,
  417. "hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  418. }
  419. class QuerySettingsForm(BaseModel):
  420. k: Optional[int] = None
  421. r: Optional[float] = None
  422. template: Optional[str] = None
  423. hybrid: Optional[bool] = None
  424. @app.post("/query/settings/update")
  425. async def update_query_settings(
  426. form_data: QuerySettingsForm, user=Depends(get_admin_user)
  427. ):
  428. app.state.config.RAG_TEMPLATE = (
  429. form_data.template if form_data.template else RAG_TEMPLATE
  430. )
  431. app.state.config.TOP_K = form_data.k if form_data.k else 4
  432. app.state.config.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
  433. app.state.config.ENABLE_RAG_HYBRID_SEARCH = (
  434. form_data.hybrid if form_data.hybrid else False
  435. )
  436. return {
  437. "status": True,
  438. "template": app.state.config.RAG_TEMPLATE,
  439. "k": app.state.config.TOP_K,
  440. "r": app.state.config.RELEVANCE_THRESHOLD,
  441. "hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  442. }
  443. class QueryDocForm(BaseModel):
  444. collection_name: str
  445. query: str
  446. k: Optional[int] = None
  447. r: Optional[float] = None
  448. hybrid: Optional[bool] = None
  449. @app.post("/query/doc")
  450. def query_doc_handler(
  451. form_data: QueryDocForm,
  452. user=Depends(get_current_user),
  453. ):
  454. try:
  455. if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
  456. return query_doc_with_hybrid_search(
  457. collection_name=form_data.collection_name,
  458. query=form_data.query,
  459. embedding_function=app.state.EMBEDDING_FUNCTION,
  460. k=form_data.k if form_data.k else app.state.config.TOP_K,
  461. reranking_function=app.state.sentence_transformer_rf,
  462. r=(
  463. form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
  464. ),
  465. )
  466. else:
  467. return query_doc(
  468. collection_name=form_data.collection_name,
  469. query=form_data.query,
  470. embedding_function=app.state.EMBEDDING_FUNCTION,
  471. k=form_data.k if form_data.k else app.state.config.TOP_K,
  472. )
  473. except Exception as e:
  474. log.exception(e)
  475. raise HTTPException(
  476. status_code=status.HTTP_400_BAD_REQUEST,
  477. detail=ERROR_MESSAGES.DEFAULT(e),
  478. )
  479. class QueryCollectionsForm(BaseModel):
  480. collection_names: List[str]
  481. query: str
  482. k: Optional[int] = None
  483. r: Optional[float] = None
  484. hybrid: Optional[bool] = None
  485. @app.post("/query/collection")
  486. def query_collection_handler(
  487. form_data: QueryCollectionsForm,
  488. user=Depends(get_current_user),
  489. ):
  490. try:
  491. if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
  492. return query_collection_with_hybrid_search(
  493. collection_names=form_data.collection_names,
  494. query=form_data.query,
  495. embedding_function=app.state.EMBEDDING_FUNCTION,
  496. k=form_data.k if form_data.k else app.state.config.TOP_K,
  497. reranking_function=app.state.sentence_transformer_rf,
  498. r=(
  499. form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
  500. ),
  501. )
  502. else:
  503. return query_collection(
  504. collection_names=form_data.collection_names,
  505. query=form_data.query,
  506. embedding_function=app.state.EMBEDDING_FUNCTION,
  507. k=form_data.k if form_data.k else app.state.config.TOP_K,
  508. )
  509. except Exception as e:
  510. log.exception(e)
  511. raise HTTPException(
  512. status_code=status.HTTP_400_BAD_REQUEST,
  513. detail=ERROR_MESSAGES.DEFAULT(e),
  514. )
  515. @app.post("/youtube")
  516. def store_youtube_video(form_data: UrlForm, user=Depends(get_current_user)):
  517. try:
  518. loader = YoutubeLoader.from_youtube_url(
  519. form_data.url,
  520. add_video_info=True,
  521. language=app.state.config.YOUTUBE_LOADER_LANGUAGE,
  522. translation=app.state.YOUTUBE_LOADER_TRANSLATION,
  523. )
  524. data = loader.load()
  525. collection_name = form_data.collection_name
  526. if collection_name == "":
  527. collection_name = calculate_sha256_string(form_data.url)[:63]
  528. store_data_in_vector_db(data, collection_name, overwrite=True)
  529. return {
  530. "status": True,
  531. "collection_name": collection_name,
  532. "filename": form_data.url,
  533. }
  534. except Exception as e:
  535. log.exception(e)
  536. raise HTTPException(
  537. status_code=status.HTTP_400_BAD_REQUEST,
  538. detail=ERROR_MESSAGES.DEFAULT(e),
  539. )
  540. @app.post("/web")
  541. def store_web(form_data: UrlForm, user=Depends(get_current_user)):
  542. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  543. try:
  544. loader = get_web_loader(
  545. form_data.url,
  546. verify_ssl=app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  547. )
  548. data = loader.load()
  549. collection_name = form_data.collection_name
  550. if collection_name == "":
  551. collection_name = calculate_sha256_string(form_data.url)[:63]
  552. store_data_in_vector_db(data, collection_name, overwrite=True)
  553. return {
  554. "status": True,
  555. "collection_name": collection_name,
  556. "filename": form_data.url,
  557. }
  558. except Exception as e:
  559. log.exception(e)
  560. raise HTTPException(
  561. status_code=status.HTTP_400_BAD_REQUEST,
  562. detail=ERROR_MESSAGES.DEFAULT(e),
  563. )
  564. def get_web_loader(url: Union[str, Sequence[str]], verify_ssl: bool = True):
  565. # Check if the URL is valid
  566. if not validate_url(url):
  567. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  568. return WebBaseLoader(
  569. url,
  570. verify_ssl=verify_ssl,
  571. requests_per_second=RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  572. continue_on_failure=True,
  573. )
  574. def validate_url(url: Union[str, Sequence[str]]):
  575. if isinstance(url, str):
  576. if isinstance(validators.url(url), validators.ValidationError):
  577. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  578. if not ENABLE_RAG_LOCAL_WEB_FETCH:
  579. # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
  580. parsed_url = urllib.parse.urlparse(url)
  581. # Get IPv4 and IPv6 addresses
  582. ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
  583. # Check if any of the resolved addresses are private
  584. # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
  585. for ip in ipv4_addresses:
  586. if validators.ipv4(ip, private=True):
  587. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  588. for ip in ipv6_addresses:
  589. if validators.ipv6(ip, private=True):
  590. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  591. return True
  592. elif isinstance(url, Sequence):
  593. return all(validate_url(u) for u in url)
  594. else:
  595. return False
  596. def resolve_hostname(hostname):
  597. # Get address information
  598. addr_info = socket.getaddrinfo(hostname, None)
  599. # Extract IP addresses from address information
  600. ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
  601. ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
  602. return ipv4_addresses, ipv6_addresses
  603. def search_web(engine: str, query: str) -> list[SearchResult]:
  604. """Search the web using a search engine and return the results as a list of SearchResult objects.
  605. Will look for a search engine API key in environment variables in the following order:
  606. - SEARXNG_QUERY_URL
  607. - GOOGLE_PSE_API_KEY + GOOGLE_PSE_ENGINE_ID
  608. - BRAVE_SEARCH_API_KEY
  609. - SERPSTACK_API_KEY
  610. - SERPER_API_KEY
  611. Args:
  612. query (str): The query to search for
  613. """
  614. # TODO: add playwright to search the web
  615. if engine == "searxng":
  616. if app.state.config.SEARXNG_QUERY_URL:
  617. return search_searxng(app.state.config.SEARXNG_QUERY_URL, query)
  618. else:
  619. raise Exception("No SEARXNG_QUERY_URL found in environment variables")
  620. elif engine == "google_pse":
  621. if (
  622. app.state.config.GOOGLE_PSE_API_KEY
  623. and app.state.config.GOOGLE_PSE_ENGINE_ID
  624. ):
  625. return search_google_pse(
  626. app.state.config.GOOGLE_PSE_API_KEY,
  627. app.state.config.GOOGLE_PSE_ENGINE_ID,
  628. query,
  629. )
  630. else:
  631. raise Exception(
  632. "No GOOGLE_PSE_API_KEY or GOOGLE_PSE_ENGINE_ID found in environment variables"
  633. )
  634. elif engine == "brave":
  635. if app.state.config.BRAVE_SEARCH_API_KEY:
  636. return search_brave(app.state.config.BRAVE_SEARCH_API_KEY, query)
  637. else:
  638. raise Exception("No BRAVE_SEARCH_API_KEY found in environment variables")
  639. elif engine == "serpstack":
  640. if app.state.config.SERPSTACK_API_KEY:
  641. return search_serpstack(
  642. app.state.config.SERPSTACK_API_KEY,
  643. query,
  644. https_enabled=app.state.config.SERPSTACK_HTTPS,
  645. )
  646. else:
  647. raise Exception("No SERPSTACK_API_KEY found in environment variables")
  648. elif engine == "serper":
  649. if app.state.config.SERPER_API_KEY:
  650. return search_serper(app.state.config.SERPER_API_KEY, query)
  651. else:
  652. raise Exception("No SERPER_API_KEY found in environment variables")
  653. else:
  654. raise Exception("No search engine API key found in environment variables")
  655. @app.post("/web/search")
  656. def store_web_search(form_data: SearchForm, user=Depends(get_current_user)):
  657. try:
  658. web_results = search_web(
  659. app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query
  660. )
  661. except Exception as e:
  662. log.exception(e)
  663. print(e)
  664. raise HTTPException(
  665. status_code=status.HTTP_400_BAD_REQUEST,
  666. detail=ERROR_MESSAGES.WEB_SEARCH_ERROR(e),
  667. )
  668. try:
  669. urls = [result.link for result in web_results]
  670. loader = get_web_loader(urls)
  671. data = loader.load()
  672. collection_name = form_data.collection_name
  673. if collection_name == "":
  674. collection_name = calculate_sha256_string(form_data.query)[:63]
  675. store_data_in_vector_db(data, collection_name, overwrite=True)
  676. return {
  677. "status": True,
  678. "collection_name": collection_name,
  679. "filenames": urls,
  680. }
  681. except Exception as e:
  682. log.exception(e)
  683. raise HTTPException(
  684. status_code=status.HTTP_400_BAD_REQUEST,
  685. detail=ERROR_MESSAGES.DEFAULT(e),
  686. )
  687. def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
  688. text_splitter = RecursiveCharacterTextSplitter(
  689. chunk_size=app.state.config.CHUNK_SIZE,
  690. chunk_overlap=app.state.config.CHUNK_OVERLAP,
  691. add_start_index=True,
  692. )
  693. docs = text_splitter.split_documents(data)
  694. if len(docs) > 0:
  695. log.info(f"store_data_in_vector_db {docs}")
  696. return store_docs_in_vector_db(docs, collection_name, overwrite), None
  697. else:
  698. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  699. def store_text_in_vector_db(
  700. text, metadata, collection_name, overwrite: bool = False
  701. ) -> bool:
  702. text_splitter = RecursiveCharacterTextSplitter(
  703. chunk_size=app.state.config.CHUNK_SIZE,
  704. chunk_overlap=app.state.config.CHUNK_OVERLAP,
  705. add_start_index=True,
  706. )
  707. docs = text_splitter.create_documents([text], metadatas=[metadata])
  708. return store_docs_in_vector_db(docs, collection_name, overwrite)
  709. def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
  710. log.info(f"store_docs_in_vector_db {docs} {collection_name}")
  711. texts = [doc.page_content for doc in docs]
  712. metadatas = [doc.metadata for doc in docs]
  713. try:
  714. if overwrite:
  715. for collection in CHROMA_CLIENT.list_collections():
  716. if collection_name == collection.name:
  717. log.info(f"deleting existing collection {collection_name}")
  718. CHROMA_CLIENT.delete_collection(name=collection_name)
  719. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  720. embedding_func = get_embedding_function(
  721. app.state.config.RAG_EMBEDDING_ENGINE,
  722. app.state.config.RAG_EMBEDDING_MODEL,
  723. app.state.sentence_transformer_ef,
  724. app.state.config.OPENAI_API_KEY,
  725. app.state.config.OPENAI_API_BASE_URL,
  726. )
  727. embedding_texts = list(map(lambda x: x.replace("\n", " "), texts))
  728. embeddings = embedding_func(embedding_texts)
  729. for batch in create_batches(
  730. api=CHROMA_CLIENT,
  731. ids=[str(uuid.uuid4()) for _ in texts],
  732. metadatas=metadatas,
  733. embeddings=embeddings,
  734. documents=texts,
  735. ):
  736. collection.add(*batch)
  737. return True
  738. except Exception as e:
  739. log.exception(e)
  740. if e.__class__.__name__ == "UniqueConstraintError":
  741. return True
  742. return False
  743. def get_loader(filename: str, file_content_type: str, file_path: str):
  744. file_ext = filename.split(".")[-1].lower()
  745. known_type = True
  746. known_source_ext = [
  747. "go",
  748. "py",
  749. "java",
  750. "sh",
  751. "bat",
  752. "ps1",
  753. "cmd",
  754. "js",
  755. "ts",
  756. "css",
  757. "cpp",
  758. "hpp",
  759. "h",
  760. "c",
  761. "cs",
  762. "sql",
  763. "log",
  764. "ini",
  765. "pl",
  766. "pm",
  767. "r",
  768. "dart",
  769. "dockerfile",
  770. "env",
  771. "php",
  772. "hs",
  773. "hsc",
  774. "lua",
  775. "nginxconf",
  776. "conf",
  777. "m",
  778. "mm",
  779. "plsql",
  780. "perl",
  781. "rb",
  782. "rs",
  783. "db2",
  784. "scala",
  785. "bash",
  786. "swift",
  787. "vue",
  788. "svelte",
  789. ]
  790. if file_ext == "pdf":
  791. loader = PyPDFLoader(
  792. file_path, extract_images=app.state.config.PDF_EXTRACT_IMAGES
  793. )
  794. elif file_ext == "csv":
  795. loader = CSVLoader(file_path)
  796. elif file_ext == "rst":
  797. loader = UnstructuredRSTLoader(file_path, mode="elements")
  798. elif file_ext == "xml":
  799. loader = UnstructuredXMLLoader(file_path)
  800. elif file_ext in ["htm", "html"]:
  801. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  802. elif file_ext == "md":
  803. loader = UnstructuredMarkdownLoader(file_path)
  804. elif file_content_type == "application/epub+zip":
  805. loader = UnstructuredEPubLoader(file_path)
  806. elif (
  807. file_content_type
  808. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  809. or file_ext in ["doc", "docx"]
  810. ):
  811. loader = Docx2txtLoader(file_path)
  812. elif file_content_type in [
  813. "application/vnd.ms-excel",
  814. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  815. ] or file_ext in ["xls", "xlsx"]:
  816. loader = UnstructuredExcelLoader(file_path)
  817. elif file_content_type in [
  818. "application/vnd.ms-powerpoint",
  819. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  820. ] or file_ext in ["ppt", "pptx"]:
  821. loader = UnstructuredPowerPointLoader(file_path)
  822. elif file_ext in known_source_ext or (
  823. file_content_type and file_content_type.find("text/") >= 0
  824. ):
  825. loader = TextLoader(file_path, autodetect_encoding=True)
  826. else:
  827. loader = TextLoader(file_path, autodetect_encoding=True)
  828. known_type = False
  829. return loader, known_type
  830. @app.post("/doc")
  831. def store_doc(
  832. collection_name: Optional[str] = Form(None),
  833. file: UploadFile = File(...),
  834. user=Depends(get_current_user),
  835. ):
  836. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  837. log.info(f"file.content_type: {file.content_type}")
  838. try:
  839. unsanitized_filename = file.filename
  840. filename = os.path.basename(unsanitized_filename)
  841. file_path = f"{UPLOAD_DIR}/{filename}"
  842. contents = file.file.read()
  843. with open(file_path, "wb") as f:
  844. f.write(contents)
  845. f.close()
  846. f = open(file_path, "rb")
  847. if collection_name == None:
  848. collection_name = calculate_sha256(f)[:63]
  849. f.close()
  850. loader, known_type = get_loader(filename, file.content_type, file_path)
  851. data = loader.load()
  852. try:
  853. result = store_data_in_vector_db(data, collection_name)
  854. if result:
  855. return {
  856. "status": True,
  857. "collection_name": collection_name,
  858. "filename": filename,
  859. "known_type": known_type,
  860. }
  861. except Exception as e:
  862. raise HTTPException(
  863. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  864. detail=e,
  865. )
  866. except Exception as e:
  867. log.exception(e)
  868. if "No pandoc was found" in str(e):
  869. raise HTTPException(
  870. status_code=status.HTTP_400_BAD_REQUEST,
  871. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  872. )
  873. else:
  874. raise HTTPException(
  875. status_code=status.HTTP_400_BAD_REQUEST,
  876. detail=ERROR_MESSAGES.DEFAULT(e),
  877. )
  878. class TextRAGForm(BaseModel):
  879. name: str
  880. content: str
  881. collection_name: Optional[str] = None
  882. @app.post("/text")
  883. def store_text(
  884. form_data: TextRAGForm,
  885. user=Depends(get_current_user),
  886. ):
  887. collection_name = form_data.collection_name
  888. if collection_name == None:
  889. collection_name = calculate_sha256_string(form_data.content)
  890. result = store_text_in_vector_db(
  891. form_data.content,
  892. metadata={"name": form_data.name, "created_by": user.id},
  893. collection_name=collection_name,
  894. )
  895. if result:
  896. return {"status": True, "collection_name": collection_name}
  897. else:
  898. raise HTTPException(
  899. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  900. detail=ERROR_MESSAGES.DEFAULT(),
  901. )
  902. @app.get("/scan")
  903. def scan_docs_dir(user=Depends(get_admin_user)):
  904. for path in Path(DOCS_DIR).rglob("./**/*"):
  905. try:
  906. if path.is_file() and not path.name.startswith("."):
  907. tags = extract_folders_after_data_docs(path)
  908. filename = path.name
  909. file_content_type = mimetypes.guess_type(path)
  910. f = open(path, "rb")
  911. collection_name = calculate_sha256(f)[:63]
  912. f.close()
  913. loader, known_type = get_loader(
  914. filename, file_content_type[0], str(path)
  915. )
  916. data = loader.load()
  917. try:
  918. result = store_data_in_vector_db(data, collection_name)
  919. if result:
  920. sanitized_filename = sanitize_filename(filename)
  921. doc = Documents.get_doc_by_name(sanitized_filename)
  922. if doc == None:
  923. doc = Documents.insert_new_doc(
  924. user.id,
  925. DocumentForm(
  926. **{
  927. "name": sanitized_filename,
  928. "title": filename,
  929. "collection_name": collection_name,
  930. "filename": filename,
  931. "content": (
  932. json.dumps(
  933. {
  934. "tags": list(
  935. map(
  936. lambda name: {"name": name},
  937. tags,
  938. )
  939. )
  940. }
  941. )
  942. if len(tags)
  943. else "{}"
  944. ),
  945. }
  946. ),
  947. )
  948. except Exception as e:
  949. log.exception(e)
  950. pass
  951. except Exception as e:
  952. log.exception(e)
  953. return True
  954. @app.get("/reset/db")
  955. def reset_vector_db(user=Depends(get_admin_user)):
  956. CHROMA_CLIENT.reset()
  957. @app.get("/reset")
  958. def reset(user=Depends(get_admin_user)) -> bool:
  959. folder = f"{UPLOAD_DIR}"
  960. for filename in os.listdir(folder):
  961. file_path = os.path.join(folder, filename)
  962. try:
  963. if os.path.isfile(file_path) or os.path.islink(file_path):
  964. os.unlink(file_path)
  965. elif os.path.isdir(file_path):
  966. shutil.rmtree(file_path)
  967. except Exception as e:
  968. log.error("Failed to delete %s. Reason: %s" % (file_path, e))
  969. try:
  970. CHROMA_CLIENT.reset()
  971. except Exception as e:
  972. log.exception(e)
  973. return True
  974. if ENV == "dev":
  975. @app.get("/ef")
  976. async def get_embeddings():
  977. return {"result": app.state.EMBEDDING_FUNCTION("hello world")}
  978. @app.get("/ef/{text}")
  979. async def get_embeddings_text(text: str):
  980. return {"result": app.state.EMBEDDING_FUNCTION(text)}