main.py 54 KB

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