main.py 55 KB

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