main.py 47 KB

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