main.py 49 KB

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