main.py 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. from contextlib import asynccontextmanager
  2. from bs4 import BeautifulSoup
  3. import json
  4. import markdown
  5. import time
  6. import os
  7. import sys
  8. import logging
  9. import aiohttp
  10. import requests
  11. import mimetypes
  12. import shutil
  13. import os
  14. import asyncio
  15. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  16. from fastapi.staticfiles import StaticFiles
  17. from fastapi.responses import JSONResponse
  18. from fastapi import HTTPException
  19. from fastapi.middleware.wsgi import WSGIMiddleware
  20. from fastapi.middleware.cors import CORSMiddleware
  21. from starlette.exceptions import HTTPException as StarletteHTTPException
  22. from starlette.middleware.base import BaseHTTPMiddleware
  23. from starlette.responses import StreamingResponse, Response
  24. from apps.socket.main import app as socket_app
  25. from apps.ollama.main import (
  26. app as ollama_app,
  27. OpenAIChatCompletionForm,
  28. get_all_models as get_ollama_models,
  29. generate_openai_chat_completion as generate_ollama_chat_completion,
  30. )
  31. from apps.openai.main import (
  32. app as openai_app,
  33. get_all_models as get_openai_models,
  34. generate_chat_completion as generate_openai_chat_completion,
  35. )
  36. from apps.audio.main import app as audio_app
  37. from apps.images.main import app as images_app
  38. from apps.rag.main import app as rag_app
  39. from apps.webui.main import app as webui_app
  40. from pydantic import BaseModel
  41. from typing import List, Optional
  42. from apps.webui.models.models import Models, ModelModel
  43. from utils.utils import (
  44. get_admin_user,
  45. get_verified_user,
  46. get_current_user,
  47. get_http_authorization_cred,
  48. )
  49. from apps.rag.utils import rag_messages
  50. from config import (
  51. CONFIG_DATA,
  52. WEBUI_NAME,
  53. WEBUI_URL,
  54. WEBUI_AUTH,
  55. ENV,
  56. VERSION,
  57. CHANGELOG,
  58. FRONTEND_BUILD_DIR,
  59. CACHE_DIR,
  60. STATIC_DIR,
  61. ENABLE_OPENAI_API,
  62. ENABLE_OLLAMA_API,
  63. ENABLE_MODEL_FILTER,
  64. MODEL_FILTER_LIST,
  65. GLOBAL_LOG_LEVEL,
  66. SRC_LOG_LEVELS,
  67. WEBHOOK_URL,
  68. ENABLE_ADMIN_EXPORT,
  69. AppConfig,
  70. WEBUI_BUILD_HASH,
  71. )
  72. from constants import ERROR_MESSAGES
  73. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  74. log = logging.getLogger(__name__)
  75. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  76. class SPAStaticFiles(StaticFiles):
  77. async def get_response(self, path: str, scope):
  78. try:
  79. return await super().get_response(path, scope)
  80. except (HTTPException, StarletteHTTPException) as ex:
  81. if ex.status_code == 404:
  82. return await super().get_response("index.html", scope)
  83. else:
  84. raise ex
  85. print(
  86. rf"""
  87. ___ __ __ _ _ _ ___
  88. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  89. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  90. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  91. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  92. |_|
  93. v{VERSION} - building the best open-source AI user interface.
  94. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  95. https://github.com/open-webui/open-webui
  96. """
  97. )
  98. @asynccontextmanager
  99. async def lifespan(app: FastAPI):
  100. yield
  101. app = FastAPI(
  102. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  103. )
  104. app.state.config = AppConfig()
  105. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  106. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  107. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  108. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  109. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  110. app.state.MODELS = {}
  111. origins = ["*"]
  112. # Custom middleware to add security headers
  113. # class SecurityHeadersMiddleware(BaseHTTPMiddleware):
  114. # async def dispatch(self, request: Request, call_next):
  115. # response: Response = await call_next(request)
  116. # response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
  117. # response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
  118. # return response
  119. # app.add_middleware(SecurityHeadersMiddleware)
  120. class RAGMiddleware(BaseHTTPMiddleware):
  121. async def dispatch(self, request: Request, call_next):
  122. return_citations = False
  123. if request.method == "POST" and (
  124. "/ollama/api/chat" in request.url.path
  125. or "/chat/completions" in request.url.path
  126. ):
  127. log.debug(f"request.url.path: {request.url.path}")
  128. # Read the original request body
  129. body = await request.body()
  130. # Decode body to string
  131. body_str = body.decode("utf-8")
  132. # Parse string to JSON
  133. data = json.loads(body_str) if body_str else {}
  134. return_citations = data.get("citations", False)
  135. if "citations" in data:
  136. del data["citations"]
  137. # Example: Add a new key-value pair or modify existing ones
  138. # data["modified"] = True # Example modification
  139. if "docs" in data:
  140. data = {**data}
  141. data["messages"], citations = rag_messages(
  142. docs=data["docs"],
  143. messages=data["messages"],
  144. template=rag_app.state.config.RAG_TEMPLATE,
  145. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  146. k=rag_app.state.config.TOP_K,
  147. reranking_function=rag_app.state.sentence_transformer_rf,
  148. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  149. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  150. )
  151. del data["docs"]
  152. log.debug(
  153. f"data['messages']: {data['messages']}, citations: {citations}"
  154. )
  155. modified_body_bytes = json.dumps(data).encode("utf-8")
  156. # Replace the request body with the modified one
  157. request._body = modified_body_bytes
  158. # Set custom header to ensure content-length matches new body length
  159. request.headers.__dict__["_list"] = [
  160. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  161. *[
  162. (k, v)
  163. for k, v in request.headers.raw
  164. if k.lower() != b"content-length"
  165. ],
  166. ]
  167. response = await call_next(request)
  168. if return_citations:
  169. # Inject the citations into the response
  170. if isinstance(response, StreamingResponse):
  171. # If it's a streaming response, inject it as SSE event or NDJSON line
  172. content_type = response.headers.get("Content-Type")
  173. if "text/event-stream" in content_type:
  174. return StreamingResponse(
  175. self.openai_stream_wrapper(response.body_iterator, citations),
  176. )
  177. if "application/x-ndjson" in content_type:
  178. return StreamingResponse(
  179. self.ollama_stream_wrapper(response.body_iterator, citations),
  180. )
  181. return response
  182. async def _receive(self, body: bytes):
  183. return {"type": "http.request", "body": body, "more_body": False}
  184. async def openai_stream_wrapper(self, original_generator, citations):
  185. yield f"data: {json.dumps({'citations': citations})}\n\n"
  186. async for data in original_generator:
  187. yield data
  188. async def ollama_stream_wrapper(self, original_generator, citations):
  189. yield f"{json.dumps({'citations': citations})}\n"
  190. async for data in original_generator:
  191. yield data
  192. app.add_middleware(RAGMiddleware)
  193. class PipelineMiddleware(BaseHTTPMiddleware):
  194. async def dispatch(self, request: Request, call_next):
  195. if request.method == "POST" and (
  196. "/ollama/api/chat" in request.url.path
  197. or "/chat/completions" in request.url.path
  198. ):
  199. log.debug(f"request.url.path: {request.url.path}")
  200. # Read the original request body
  201. body = await request.body()
  202. # Decode body to string
  203. body_str = body.decode("utf-8")
  204. # Parse string to JSON
  205. data = json.loads(body_str) if body_str else {}
  206. model_id = data["model"]
  207. filters = [
  208. model
  209. for model in app.state.MODELS.values()
  210. if "pipeline" in model
  211. and "type" in model["pipeline"]
  212. and model["pipeline"]["type"] == "filter"
  213. and (
  214. model["pipeline"]["pipelines"] == ["*"]
  215. or any(
  216. model_id == target_model_id
  217. for target_model_id in model["pipeline"]["pipelines"]
  218. )
  219. )
  220. ]
  221. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  222. user = None
  223. if len(sorted_filters) > 0:
  224. try:
  225. user = get_current_user(
  226. get_http_authorization_cred(
  227. request.headers.get("Authorization")
  228. )
  229. )
  230. user = {"id": user.id, "name": user.name, "role": user.role}
  231. except:
  232. pass
  233. model = app.state.MODELS[model_id]
  234. if "pipeline" in model:
  235. sorted_filters.append(model)
  236. for filter in sorted_filters:
  237. r = None
  238. try:
  239. urlIdx = filter["urlIdx"]
  240. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  241. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  242. if key != "":
  243. headers = {"Authorization": f"Bearer {key}"}
  244. r = requests.post(
  245. f"{url}/{filter['id']}/filter/inlet",
  246. headers=headers,
  247. json={
  248. "user": user,
  249. "body": data,
  250. },
  251. )
  252. r.raise_for_status()
  253. data = r.json()
  254. except Exception as e:
  255. # Handle connection error here
  256. print(f"Connection error: {e}")
  257. if r is not None:
  258. try:
  259. res = r.json()
  260. if "detail" in res:
  261. return JSONResponse(
  262. status_code=r.status_code,
  263. content=res,
  264. )
  265. except:
  266. pass
  267. else:
  268. pass
  269. if "pipeline" not in app.state.MODELS[model_id]:
  270. if "chat_id" in data:
  271. del data["chat_id"]
  272. if "title" in data:
  273. del data["title"]
  274. modified_body_bytes = json.dumps(data).encode("utf-8")
  275. # Replace the request body with the modified one
  276. request._body = modified_body_bytes
  277. # Set custom header to ensure content-length matches new body length
  278. request.headers.__dict__["_list"] = [
  279. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  280. *[
  281. (k, v)
  282. for k, v in request.headers.raw
  283. if k.lower() != b"content-length"
  284. ],
  285. ]
  286. response = await call_next(request)
  287. return response
  288. async def _receive(self, body: bytes):
  289. return {"type": "http.request", "body": body, "more_body": False}
  290. app.add_middleware(PipelineMiddleware)
  291. app.add_middleware(
  292. CORSMiddleware,
  293. allow_origins=origins,
  294. allow_credentials=True,
  295. allow_methods=["*"],
  296. allow_headers=["*"],
  297. )
  298. @app.middleware("http")
  299. async def check_url(request: Request, call_next):
  300. if len(app.state.MODELS) == 0:
  301. await get_all_models()
  302. else:
  303. pass
  304. start_time = int(time.time())
  305. response = await call_next(request)
  306. process_time = int(time.time()) - start_time
  307. response.headers["X-Process-Time"] = str(process_time)
  308. return response
  309. @app.middleware("http")
  310. async def update_embedding_function(request: Request, call_next):
  311. response = await call_next(request)
  312. if "/embedding/update" in request.url.path:
  313. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  314. return response
  315. app.mount("/ws", socket_app)
  316. app.mount("/ollama", ollama_app)
  317. app.mount("/openai", openai_app)
  318. app.mount("/images/api/v1", images_app)
  319. app.mount("/audio/api/v1", audio_app)
  320. app.mount("/rag/api/v1", rag_app)
  321. app.mount("/api/v1", webui_app)
  322. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  323. async def get_all_models():
  324. openai_models = []
  325. ollama_models = []
  326. if app.state.config.ENABLE_OPENAI_API:
  327. openai_models = await get_openai_models()
  328. openai_models = openai_models["data"]
  329. if app.state.config.ENABLE_OLLAMA_API:
  330. ollama_models = await get_ollama_models()
  331. ollama_models = [
  332. {
  333. "id": model["model"],
  334. "name": model["name"],
  335. "object": "model",
  336. "created": int(time.time()),
  337. "owned_by": "ollama",
  338. "ollama": model,
  339. }
  340. for model in ollama_models["models"]
  341. ]
  342. models = openai_models + ollama_models
  343. custom_models = Models.get_all_models()
  344. for custom_model in custom_models:
  345. if custom_model.base_model_id == None:
  346. for model in models:
  347. if (
  348. custom_model.id == model["id"]
  349. or custom_model.id == model["id"].split(":")[0]
  350. ):
  351. model["name"] = custom_model.name
  352. model["info"] = custom_model.model_dump()
  353. else:
  354. owned_by = "openai"
  355. for model in models:
  356. if (
  357. custom_model.base_model_id == model["id"]
  358. or custom_model.base_model_id == model["id"].split(":")[0]
  359. ):
  360. owned_by = model["owned_by"]
  361. break
  362. models.append(
  363. {
  364. "id": custom_model.id,
  365. "name": custom_model.name,
  366. "object": "model",
  367. "created": custom_model.created_at,
  368. "owned_by": owned_by,
  369. "info": custom_model.model_dump(),
  370. "preset": True,
  371. }
  372. )
  373. app.state.MODELS = {model["id"]: model for model in models}
  374. webui_app.state.MODELS = app.state.MODELS
  375. return models
  376. @app.get("/api/models")
  377. async def get_models(user=Depends(get_verified_user)):
  378. models = await get_all_models()
  379. # Filter out filter pipelines
  380. models = [
  381. model
  382. for model in models
  383. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  384. ]
  385. if app.state.config.ENABLE_MODEL_FILTER:
  386. if user.role == "user":
  387. models = list(
  388. filter(
  389. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  390. models,
  391. )
  392. )
  393. return {"data": models}
  394. return {"data": models}
  395. @app.post("/api/chat/completions")
  396. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  397. model_id = form_data["model"]
  398. if model_id not in app.state.MODELS:
  399. raise HTTPException(
  400. status_code=status.HTTP_404_NOT_FOUND,
  401. detail="Model not found",
  402. )
  403. model = app.state.MODELS[model_id]
  404. print(model)
  405. if model["owned_by"] == "ollama":
  406. return await generate_ollama_chat_completion(
  407. OpenAIChatCompletionForm(**form_data), user=user
  408. )
  409. else:
  410. return await generate_openai_chat_completion(form_data, user=user)
  411. @app.post("/api/chat/completed")
  412. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  413. data = form_data
  414. model_id = data["model"]
  415. filters = [
  416. model
  417. for model in app.state.MODELS.values()
  418. if "pipeline" in model
  419. and "type" in model["pipeline"]
  420. and model["pipeline"]["type"] == "filter"
  421. and (
  422. model["pipeline"]["pipelines"] == ["*"]
  423. or any(
  424. model_id == target_model_id
  425. for target_model_id in model["pipeline"]["pipelines"]
  426. )
  427. )
  428. ]
  429. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  430. print(model_id)
  431. if model_id in app.state.MODELS:
  432. model = app.state.MODELS[model_id]
  433. if "pipeline" in model:
  434. sorted_filters = [model] + sorted_filters
  435. for filter in sorted_filters:
  436. r = None
  437. try:
  438. urlIdx = filter["urlIdx"]
  439. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  440. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  441. if key != "":
  442. headers = {"Authorization": f"Bearer {key}"}
  443. r = requests.post(
  444. f"{url}/{filter['id']}/filter/outlet",
  445. headers=headers,
  446. json={
  447. "user": {"id": user.id, "name": user.name, "role": user.role},
  448. "body": data,
  449. },
  450. )
  451. r.raise_for_status()
  452. data = r.json()
  453. except Exception as e:
  454. # Handle connection error here
  455. print(f"Connection error: {e}")
  456. if r is not None:
  457. try:
  458. res = r.json()
  459. if "detail" in res:
  460. return JSONResponse(
  461. status_code=r.status_code,
  462. content=res,
  463. )
  464. except:
  465. pass
  466. else:
  467. pass
  468. return data
  469. @app.get("/api/pipelines/list")
  470. async def get_pipelines_list(user=Depends(get_admin_user)):
  471. responses = await get_openai_models(raw=True)
  472. print(responses)
  473. urlIdxs = [
  474. idx
  475. for idx, response in enumerate(responses)
  476. if response != None and "pipelines" in response
  477. ]
  478. return {
  479. "data": [
  480. {
  481. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  482. "idx": urlIdx,
  483. }
  484. for urlIdx in urlIdxs
  485. ]
  486. }
  487. @app.post("/api/pipelines/upload")
  488. async def upload_pipeline(
  489. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  490. ):
  491. print("upload_pipeline", urlIdx, file.filename)
  492. # Check if the uploaded file is a python file
  493. if not file.filename.endswith(".py"):
  494. raise HTTPException(
  495. status_code=status.HTTP_400_BAD_REQUEST,
  496. detail="Only Python (.py) files are allowed.",
  497. )
  498. upload_folder = f"{CACHE_DIR}/pipelines"
  499. os.makedirs(upload_folder, exist_ok=True)
  500. file_path = os.path.join(upload_folder, file.filename)
  501. try:
  502. # Save the uploaded file
  503. with open(file_path, "wb") as buffer:
  504. shutil.copyfileobj(file.file, buffer)
  505. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  506. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  507. headers = {"Authorization": f"Bearer {key}"}
  508. with open(file_path, "rb") as f:
  509. files = {"file": f}
  510. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  511. r.raise_for_status()
  512. data = r.json()
  513. return {**data}
  514. except Exception as e:
  515. # Handle connection error here
  516. print(f"Connection error: {e}")
  517. detail = "Pipeline not found"
  518. if r is not None:
  519. try:
  520. res = r.json()
  521. if "detail" in res:
  522. detail = res["detail"]
  523. except:
  524. pass
  525. raise HTTPException(
  526. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  527. detail=detail,
  528. )
  529. finally:
  530. # Ensure the file is deleted after the upload is completed or on failure
  531. if os.path.exists(file_path):
  532. os.remove(file_path)
  533. class AddPipelineForm(BaseModel):
  534. url: str
  535. urlIdx: int
  536. @app.post("/api/pipelines/add")
  537. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  538. r = None
  539. try:
  540. urlIdx = form_data.urlIdx
  541. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  542. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  543. headers = {"Authorization": f"Bearer {key}"}
  544. r = requests.post(
  545. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  546. )
  547. r.raise_for_status()
  548. data = r.json()
  549. return {**data}
  550. except Exception as e:
  551. # Handle connection error here
  552. print(f"Connection error: {e}")
  553. detail = "Pipeline not found"
  554. if r is not None:
  555. try:
  556. res = r.json()
  557. if "detail" in res:
  558. detail = res["detail"]
  559. except:
  560. pass
  561. raise HTTPException(
  562. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  563. detail=detail,
  564. )
  565. class DeletePipelineForm(BaseModel):
  566. id: str
  567. urlIdx: int
  568. @app.delete("/api/pipelines/delete")
  569. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  570. r = None
  571. try:
  572. urlIdx = form_data.urlIdx
  573. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  574. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  575. headers = {"Authorization": f"Bearer {key}"}
  576. r = requests.delete(
  577. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  578. )
  579. r.raise_for_status()
  580. data = r.json()
  581. return {**data}
  582. except Exception as e:
  583. # Handle connection error here
  584. print(f"Connection error: {e}")
  585. detail = "Pipeline not found"
  586. if r is not None:
  587. try:
  588. res = r.json()
  589. if "detail" in res:
  590. detail = res["detail"]
  591. except:
  592. pass
  593. raise HTTPException(
  594. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  595. detail=detail,
  596. )
  597. @app.get("/api/pipelines")
  598. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  599. r = None
  600. try:
  601. urlIdx
  602. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  603. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  604. headers = {"Authorization": f"Bearer {key}"}
  605. r = requests.get(f"{url}/pipelines", headers=headers)
  606. r.raise_for_status()
  607. data = r.json()
  608. return {**data}
  609. except Exception as e:
  610. # Handle connection error here
  611. print(f"Connection error: {e}")
  612. detail = "Pipeline not found"
  613. if r is not None:
  614. try:
  615. res = r.json()
  616. if "detail" in res:
  617. detail = res["detail"]
  618. except:
  619. pass
  620. raise HTTPException(
  621. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  622. detail=detail,
  623. )
  624. @app.get("/api/pipelines/{pipeline_id}/valves")
  625. async def get_pipeline_valves(
  626. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  627. ):
  628. models = await get_all_models()
  629. r = None
  630. try:
  631. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  632. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  633. headers = {"Authorization": f"Bearer {key}"}
  634. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  635. r.raise_for_status()
  636. data = r.json()
  637. return {**data}
  638. except Exception as e:
  639. # Handle connection error here
  640. print(f"Connection error: {e}")
  641. detail = "Pipeline not found"
  642. if r is not None:
  643. try:
  644. res = r.json()
  645. if "detail" in res:
  646. detail = res["detail"]
  647. except:
  648. pass
  649. raise HTTPException(
  650. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  651. detail=detail,
  652. )
  653. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  654. async def get_pipeline_valves_spec(
  655. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  656. ):
  657. models = await get_all_models()
  658. r = None
  659. try:
  660. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  661. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  662. headers = {"Authorization": f"Bearer {key}"}
  663. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  664. r.raise_for_status()
  665. data = r.json()
  666. return {**data}
  667. except Exception as e:
  668. # Handle connection error here
  669. print(f"Connection error: {e}")
  670. detail = "Pipeline not found"
  671. if r is not None:
  672. try:
  673. res = r.json()
  674. if "detail" in res:
  675. detail = res["detail"]
  676. except:
  677. pass
  678. raise HTTPException(
  679. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  680. detail=detail,
  681. )
  682. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  683. async def update_pipeline_valves(
  684. urlIdx: Optional[int],
  685. pipeline_id: str,
  686. form_data: dict,
  687. user=Depends(get_admin_user),
  688. ):
  689. models = await get_all_models()
  690. r = None
  691. try:
  692. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  693. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  694. headers = {"Authorization": f"Bearer {key}"}
  695. r = requests.post(
  696. f"{url}/{pipeline_id}/valves/update",
  697. headers=headers,
  698. json={**form_data},
  699. )
  700. r.raise_for_status()
  701. data = r.json()
  702. return {**data}
  703. except Exception as e:
  704. # Handle connection error here
  705. print(f"Connection error: {e}")
  706. detail = "Pipeline not found"
  707. if r is not None:
  708. try:
  709. res = r.json()
  710. if "detail" in res:
  711. detail = res["detail"]
  712. except:
  713. pass
  714. raise HTTPException(
  715. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  716. detail=detail,
  717. )
  718. @app.get("/api/config")
  719. async def get_app_config():
  720. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  721. default_locale = "en-US"
  722. if "ui" in CONFIG_DATA:
  723. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  724. # The Rest of the Function Now Uses the Variables Defined Above
  725. return {
  726. "status": True,
  727. "name": WEBUI_NAME,
  728. "version": VERSION,
  729. "default_locale": default_locale,
  730. "default_models": webui_app.state.config.DEFAULT_MODELS,
  731. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  732. "features": {
  733. "auth": WEBUI_AUTH,
  734. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  735. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  736. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  737. "enable_image_generation": images_app.state.config.ENABLED,
  738. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  739. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  740. },
  741. "audio": {
  742. "tts": {
  743. "engine": audio_app.state.config.TTS_ENGINE,
  744. "voice": audio_app.state.config.TTS_VOICE,
  745. },
  746. "stt": {
  747. "engine": audio_app.state.config.STT_ENGINE,
  748. },
  749. },
  750. }
  751. @app.get("/api/config/model/filter")
  752. async def get_model_filter_config(user=Depends(get_admin_user)):
  753. return {
  754. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  755. "models": app.state.config.MODEL_FILTER_LIST,
  756. }
  757. class ModelFilterConfigForm(BaseModel):
  758. enabled: bool
  759. models: List[str]
  760. @app.post("/api/config/model/filter")
  761. async def update_model_filter_config(
  762. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  763. ):
  764. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  765. app.state.config.MODEL_FILTER_LIST = form_data.models
  766. return {
  767. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  768. "models": app.state.config.MODEL_FILTER_LIST,
  769. }
  770. @app.get("/api/webhook")
  771. async def get_webhook_url(user=Depends(get_admin_user)):
  772. return {
  773. "url": app.state.config.WEBHOOK_URL,
  774. }
  775. class UrlForm(BaseModel):
  776. url: str
  777. @app.post("/api/webhook")
  778. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  779. app.state.config.WEBHOOK_URL = form_data.url
  780. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  781. return {"url": app.state.config.WEBHOOK_URL}
  782. @app.get("/api/version")
  783. async def get_app_config():
  784. return {
  785. "version": VERSION,
  786. }
  787. @app.get("/api/changelog")
  788. async def get_app_changelog():
  789. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  790. @app.get("/api/version/updates")
  791. async def get_app_latest_release_version():
  792. try:
  793. async with aiohttp.ClientSession(trust_env=True) as session:
  794. async with session.get(
  795. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  796. ) as response:
  797. response.raise_for_status()
  798. data = await response.json()
  799. latest_version = data["tag_name"]
  800. return {"current": VERSION, "latest": latest_version[1:]}
  801. except aiohttp.ClientError as e:
  802. raise HTTPException(
  803. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  804. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  805. )
  806. @app.get("/manifest.json")
  807. async def get_manifest_json():
  808. return {
  809. "name": WEBUI_NAME,
  810. "short_name": WEBUI_NAME,
  811. "start_url": "/",
  812. "display": "standalone",
  813. "background_color": "#343541",
  814. "theme_color": "#343541",
  815. "orientation": "portrait-primary",
  816. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  817. }
  818. @app.get("/opensearch.xml")
  819. async def get_opensearch_xml():
  820. xml_content = rf"""
  821. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  822. <ShortName>{WEBUI_NAME}</ShortName>
  823. <Description>Search {WEBUI_NAME}</Description>
  824. <InputEncoding>UTF-8</InputEncoding>
  825. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  826. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  827. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  828. </OpenSearchDescription>
  829. """
  830. return Response(content=xml_content, media_type="application/xml")
  831. @app.get("/health")
  832. async def healthcheck():
  833. return {"status": True}
  834. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  835. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  836. if os.path.exists(FRONTEND_BUILD_DIR):
  837. mimetypes.add_type("text/javascript", ".js")
  838. app.mount(
  839. "/",
  840. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  841. name="spa-static-files",
  842. )
  843. else:
  844. log.warning(
  845. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  846. )