main.py 33 KB

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