main.py 13 KB

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