main.py 41 KB

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