main.py 54 KB

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