main.py 55 KB

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