main.py 40 KB

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