main.py 38 KB

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