main.py 42 KB

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