main.py 50 KB

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