main.py 43 KB

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