main.py 48 KB

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