main.py 43 KB

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