main.py 16 KB

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