main.py 53 KB

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