main.py 45 KB

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