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