main.py 54 KB

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