main.py 42 KB

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