main.py 50 KB

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