main.py 40 KB

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