main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 import HTTPException
  18. from fastapi.middleware.wsgi import WSGIMiddleware
  19. from fastapi.middleware.cors import CORSMiddleware
  20. from starlette.exceptions import HTTPException as StarletteHTTPException
  21. from starlette.middleware.base import BaseHTTPMiddleware
  22. from starlette.middleware.sessions import SessionMiddleware
  23. from starlette.responses import StreamingResponse, Response, RedirectResponse
  24. from apps.ollama.main import app as ollama_app, get_all_models as get_ollama_models
  25. from apps.openai.main import app as openai_app, get_all_models as get_openai_models
  26. from apps.audio.main import app as audio_app
  27. from apps.images.main import app as images_app
  28. from apps.rag.main import app as rag_app
  29. from apps.webui.main import app as webui_app
  30. import asyncio
  31. from pydantic import BaseModel
  32. from typing import List, Optional
  33. from apps.webui.models.auths import Auths
  34. from apps.webui.models.models import Models
  35. from apps.webui.models.users import Users
  36. from utils.misc import parse_duration
  37. from utils.utils import (
  38. get_admin_user,
  39. get_verified_user,
  40. get_password_hash,
  41. create_token,
  42. )
  43. from apps.rag.utils import rag_messages
  44. from config import (
  45. CONFIG_DATA,
  46. WEBUI_NAME,
  47. WEBUI_URL,
  48. WEBUI_AUTH,
  49. ENV,
  50. VERSION,
  51. CHANGELOG,
  52. FRONTEND_BUILD_DIR,
  53. CACHE_DIR,
  54. STATIC_DIR,
  55. ENABLE_OPENAI_API,
  56. ENABLE_OLLAMA_API,
  57. ENABLE_MODEL_FILTER,
  58. MODEL_FILTER_LIST,
  59. GLOBAL_LOG_LEVEL,
  60. SRC_LOG_LEVELS,
  61. WEBHOOK_URL,
  62. ENABLE_ADMIN_EXPORT,
  63. AppConfig,
  64. OAUTH_PROVIDERS,
  65. ENABLE_OAUTH_SIGNUP,
  66. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  67. WEBUI_SECRET_KEY,
  68. )
  69. from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  70. from utils.webhook import post_webhook
  71. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  72. log = logging.getLogger(__name__)
  73. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  74. class SPAStaticFiles(StaticFiles):
  75. async def get_response(self, path: str, scope):
  76. try:
  77. return await super().get_response(path, scope)
  78. except (HTTPException, StarletteHTTPException) as ex:
  79. if ex.status_code == 404:
  80. return await super().get_response("index.html", scope)
  81. else:
  82. raise ex
  83. print(
  84. rf"""
  85. ___ __ __ _ _ _ ___
  86. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  87. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  88. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  89. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  90. |_|
  91. v{VERSION} - building the best open-source AI user interface.
  92. https://github.com/open-webui/open-webui
  93. """
  94. )
  95. @asynccontextmanager
  96. async def lifespan(app: FastAPI):
  97. yield
  98. app = FastAPI(
  99. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  100. )
  101. app.state.config = AppConfig()
  102. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  103. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  104. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  105. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  106. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  107. app.state.MODELS = {}
  108. origins = ["*"]
  109. # Custom middleware to add security headers
  110. # class SecurityHeadersMiddleware(BaseHTTPMiddleware):
  111. # async def dispatch(self, request: Request, call_next):
  112. # response: Response = await call_next(request)
  113. # response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
  114. # response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
  115. # return response
  116. # app.add_middleware(SecurityHeadersMiddleware)
  117. class RAGMiddleware(BaseHTTPMiddleware):
  118. async def dispatch(self, request: Request, call_next):
  119. return_citations = False
  120. if request.method == "POST" and (
  121. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  122. ):
  123. log.debug(f"request.url.path: {request.url.path}")
  124. # Read the original request body
  125. body = await request.body()
  126. # Decode body to string
  127. body_str = body.decode("utf-8")
  128. # Parse string to JSON
  129. data = json.loads(body_str) if body_str else {}
  130. return_citations = data.get("citations", False)
  131. if "citations" in data:
  132. del data["citations"]
  133. # Example: Add a new key-value pair or modify existing ones
  134. # data["modified"] = True # Example modification
  135. if "docs" in data:
  136. data = {**data}
  137. data["messages"], citations = rag_messages(
  138. docs=data["docs"],
  139. messages=data["messages"],
  140. template=rag_app.state.config.RAG_TEMPLATE,
  141. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  142. k=rag_app.state.config.TOP_K,
  143. reranking_function=rag_app.state.sentence_transformer_rf,
  144. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  145. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  146. )
  147. del data["docs"]
  148. log.debug(
  149. f"data['messages']: {data['messages']}, citations: {citations}"
  150. )
  151. modified_body_bytes = json.dumps(data).encode("utf-8")
  152. # Replace the request body with the modified one
  153. request._body = modified_body_bytes
  154. # Set custom header to ensure content-length matches new body length
  155. request.headers.__dict__["_list"] = [
  156. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  157. *[
  158. (k, v)
  159. for k, v in request.headers.raw
  160. if k.lower() != b"content-length"
  161. ],
  162. ]
  163. response = await call_next(request)
  164. if return_citations:
  165. # Inject the citations into the response
  166. if isinstance(response, StreamingResponse):
  167. # If it's a streaming response, inject it as SSE event or NDJSON line
  168. content_type = response.headers.get("Content-Type")
  169. if "text/event-stream" in content_type:
  170. return StreamingResponse(
  171. self.openai_stream_wrapper(response.body_iterator, citations),
  172. )
  173. if "application/x-ndjson" in content_type:
  174. return StreamingResponse(
  175. self.ollama_stream_wrapper(response.body_iterator, citations),
  176. )
  177. return response
  178. async def _receive(self, body: bytes):
  179. return {"type": "http.request", "body": body, "more_body": False}
  180. async def openai_stream_wrapper(self, original_generator, citations):
  181. yield f"data: {json.dumps({'citations': citations})}\n\n"
  182. async for data in original_generator:
  183. yield data
  184. async def ollama_stream_wrapper(self, original_generator, citations):
  185. yield f"{json.dumps({'citations': citations})}\n"
  186. async for data in original_generator:
  187. yield data
  188. app.add_middleware(RAGMiddleware)
  189. app.add_middleware(
  190. CORSMiddleware,
  191. allow_origins=origins,
  192. allow_credentials=True,
  193. allow_methods=["*"],
  194. allow_headers=["*"],
  195. )
  196. @app.middleware("http")
  197. async def check_url(request: Request, call_next):
  198. if len(app.state.MODELS) == 0:
  199. await get_all_models()
  200. else:
  201. pass
  202. start_time = int(time.time())
  203. response = await call_next(request)
  204. process_time = int(time.time()) - start_time
  205. response.headers["X-Process-Time"] = str(process_time)
  206. return response
  207. @app.middleware("http")
  208. async def update_embedding_function(request: Request, call_next):
  209. response = await call_next(request)
  210. if "/embedding/update" in request.url.path:
  211. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  212. return response
  213. app.mount("/ollama", ollama_app)
  214. app.mount("/openai", openai_app)
  215. app.mount("/images/api/v1", images_app)
  216. app.mount("/audio/api/v1", audio_app)
  217. app.mount("/rag/api/v1", rag_app)
  218. app.mount("/api/v1", webui_app)
  219. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  220. async def get_all_models():
  221. openai_models = []
  222. ollama_models = []
  223. if app.state.config.ENABLE_OPENAI_API:
  224. openai_models = await get_openai_models()
  225. openai_models = openai_models["data"]
  226. if app.state.config.ENABLE_OLLAMA_API:
  227. ollama_models = await get_ollama_models()
  228. ollama_models = [
  229. {
  230. "id": model["model"],
  231. "name": model["name"],
  232. "object": "model",
  233. "created": int(time.time()),
  234. "owned_by": "ollama",
  235. "ollama": model,
  236. }
  237. for model in ollama_models["models"]
  238. ]
  239. models = openai_models + ollama_models
  240. custom_models = Models.get_all_models()
  241. for custom_model in custom_models:
  242. if custom_model.base_model_id == None:
  243. for model in models:
  244. if (
  245. custom_model.id == model["id"]
  246. or custom_model.id == model["id"].split(":")[0]
  247. ):
  248. model["name"] = custom_model.name
  249. model["info"] = custom_model.model_dump()
  250. else:
  251. owned_by = "openai"
  252. for model in models:
  253. if (
  254. custom_model.base_model_id == model["id"]
  255. or custom_model.base_model_id == model["id"].split(":")[0]
  256. ):
  257. owned_by = model["owned_by"]
  258. break
  259. models.append(
  260. {
  261. "id": custom_model.id,
  262. "name": custom_model.name,
  263. "object": "model",
  264. "created": custom_model.created_at,
  265. "owned_by": owned_by,
  266. "info": custom_model.model_dump(),
  267. "preset": True,
  268. }
  269. )
  270. app.state.MODELS = {model["id"]: model for model in models}
  271. webui_app.state.MODELS = app.state.MODELS
  272. return models
  273. @app.get("/api/models")
  274. async def get_models(user=Depends(get_verified_user)):
  275. models = await get_all_models()
  276. if app.state.config.ENABLE_MODEL_FILTER:
  277. if user.role == "user":
  278. models = list(
  279. filter(
  280. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  281. models,
  282. )
  283. )
  284. return {"data": models}
  285. return {"data": models}
  286. @app.get("/api/config")
  287. async def get_app_config():
  288. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  289. default_locale = "en-US"
  290. if "ui" in CONFIG_DATA:
  291. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  292. # The Rest of the Function Now Uses the Variables Defined Above
  293. return {
  294. "status": True,
  295. "name": WEBUI_NAME,
  296. "version": VERSION,
  297. "auth": WEBUI_AUTH,
  298. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  299. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  300. "enable_image_generation": images_app.state.config.ENABLED,
  301. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  302. "default_locale": default_locale,
  303. "default_models": webui_app.state.config.DEFAULT_MODELS,
  304. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  305. "trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  306. "oauth": {
  307. "providers": {
  308. name: config.get("name", name)
  309. for name, config in OAUTH_PROVIDERS.items()
  310. }
  311. },
  312. }
  313. @app.get("/api/config/model/filter")
  314. async def get_model_filter_config(user=Depends(get_admin_user)):
  315. return {
  316. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  317. "models": app.state.config.MODEL_FILTER_LIST,
  318. }
  319. class ModelFilterConfigForm(BaseModel):
  320. enabled: bool
  321. models: List[str]
  322. @app.post("/api/config/model/filter")
  323. async def update_model_filter_config(
  324. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  325. ):
  326. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  327. app.state.config.MODEL_FILTER_LIST = form_data.models
  328. return {
  329. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  330. "models": app.state.config.MODEL_FILTER_LIST,
  331. }
  332. @app.get("/api/webhook")
  333. async def get_webhook_url(user=Depends(get_admin_user)):
  334. return {
  335. "url": app.state.config.WEBHOOK_URL,
  336. }
  337. class UrlForm(BaseModel):
  338. url: str
  339. @app.post("/api/webhook")
  340. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  341. app.state.config.WEBHOOK_URL = form_data.url
  342. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  343. return {
  344. "url": app.state.config.WEBHOOK_URL,
  345. }
  346. @app.get("/api/version")
  347. async def get_app_config():
  348. return {
  349. "version": VERSION,
  350. }
  351. @app.get("/api/changelog")
  352. async def get_app_changelog():
  353. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  354. @app.get("/api/version/updates")
  355. async def get_app_latest_release_version():
  356. try:
  357. async with aiohttp.ClientSession() as session:
  358. async with session.get(
  359. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  360. ) as response:
  361. response.raise_for_status()
  362. data = await response.json()
  363. latest_version = data["tag_name"]
  364. return {"current": VERSION, "latest": latest_version[1:]}
  365. except aiohttp.ClientError as e:
  366. raise HTTPException(
  367. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  368. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  369. )
  370. ############################
  371. # OAuth Login & Callback
  372. ############################
  373. oauth = OAuth()
  374. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  375. oauth.register(
  376. name=provider_name,
  377. client_id=provider_config["client_id"],
  378. client_secret=provider_config["client_secret"],
  379. server_metadata_url=provider_config["server_metadata_url"],
  380. client_kwargs={
  381. "scope": provider_config["scope"],
  382. },
  383. )
  384. # SessionMiddleware is used by authlib for oauth
  385. if len(OAUTH_PROVIDERS) > 0:
  386. app.add_middleware(
  387. SessionMiddleware, secret_key=WEBUI_SECRET_KEY, session_cookie="oui-session"
  388. )
  389. @app.get("/oauth/{provider}/login")
  390. async def oauth_login(provider: str, request: Request):
  391. if provider not in OAUTH_PROVIDERS:
  392. raise HTTPException(404)
  393. redirect_uri = request.url_for("oauth_callback", provider=provider)
  394. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  395. @app.get("/oauth/{provider}/callback")
  396. async def oauth_callback(provider: str, request: Request):
  397. if provider not in OAUTH_PROVIDERS:
  398. raise HTTPException(404)
  399. client = oauth.create_client(provider)
  400. token = await client.authorize_access_token(request)
  401. user_data: UserInfo = token["userinfo"]
  402. sub = user_data.get("sub")
  403. if not sub:
  404. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  405. provider_sub = f"{provider}@{sub}"
  406. # Check if the user exists
  407. user = Users.get_user_by_oauth_sub(provider_sub)
  408. if not user:
  409. # If the user does not exist, check if merging is enabled
  410. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  411. # Check if the user exists by email
  412. email = user_data.get("email", "").lower()
  413. if not email:
  414. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  415. user = Users.get_user_by_email(user_data.get("email", "").lower(), True)
  416. if user:
  417. # Update the user with the new oauth sub
  418. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  419. if not user:
  420. # If the user does not exist, check if signups are enabled
  421. if ENABLE_OAUTH_SIGNUP.value:
  422. user = Auths.insert_new_auth(
  423. email=user_data.get("email", "").lower(),
  424. password=get_password_hash(
  425. str(uuid.uuid4())
  426. ), # Random password, not used
  427. name=user_data.get("name", "User"),
  428. profile_image_url=user_data.get("picture", "/user.png"),
  429. role=webui_app.state.config.DEFAULT_USER_ROLE,
  430. oauth_sub=provider_sub,
  431. )
  432. if webui_app.state.config.WEBHOOK_URL:
  433. post_webhook(
  434. webui_app.state.config.WEBHOOK_URL,
  435. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  436. {
  437. "action": "signup",
  438. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  439. "user": user.model_dump_json(exclude_none=True),
  440. },
  441. )
  442. else:
  443. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  444. jwt_token = create_token(
  445. data={"id": user.id},
  446. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  447. )
  448. # Redirect back to the frontend with the JWT token
  449. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  450. return RedirectResponse(url=redirect_url)
  451. @app.get("/manifest.json")
  452. async def get_manifest_json():
  453. return {
  454. "name": WEBUI_NAME,
  455. "short_name": WEBUI_NAME,
  456. "start_url": "/",
  457. "display": "standalone",
  458. "background_color": "#343541",
  459. "theme_color": "#343541",
  460. "orientation": "portrait-primary",
  461. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  462. }
  463. @app.get("/opensearch.xml")
  464. async def get_opensearch_xml():
  465. xml_content = rf"""
  466. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  467. <ShortName>{WEBUI_NAME}</ShortName>
  468. <Description>Search {WEBUI_NAME}</Description>
  469. <InputEncoding>UTF-8</InputEncoding>
  470. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  471. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  472. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  473. </OpenSearchDescription>
  474. """
  475. return Response(content=xml_content, media_type="application/xml")
  476. @app.get("/health")
  477. async def healthcheck():
  478. return {"status": True}
  479. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  480. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  481. if os.path.exists(FRONTEND_BUILD_DIR):
  482. mimetypes.add_type("text/javascript", ".js")
  483. app.mount(
  484. "/",
  485. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  486. name="spa-static-files",
  487. )
  488. else:
  489. log.warning(
  490. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  491. )