main.py 53 KB

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