main.py 50 KB

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