main.py 45 KB

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