main.py 49 KB

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