main.py 42 KB

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