main.py 47 KB

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