main.py 45 KB

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