main.py 50 KB

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