main.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. from bs4 import BeautifulSoup
  2. import json
  3. import markdown
  4. import time
  5. import os
  6. import sys
  7. import logging
  8. import aiohttp
  9. import requests
  10. from fastapi import FastAPI, Request, Depends, status
  11. from fastapi.staticfiles import StaticFiles
  12. from fastapi import HTTPException
  13. from fastapi.middleware.wsgi import WSGIMiddleware
  14. from fastapi.middleware.cors import CORSMiddleware
  15. from starlette.exceptions import HTTPException as StarletteHTTPException
  16. from starlette.middleware.base import BaseHTTPMiddleware
  17. from apps.ollama.main import app as ollama_app
  18. from apps.openai.main import app as openai_app
  19. from apps.litellm.main import (
  20. app as litellm_app,
  21. start_litellm_background,
  22. shutdown_litellm_background,
  23. )
  24. from apps.audio.main import app as audio_app
  25. from apps.images.main import app as images_app
  26. from apps.rag.main import app as rag_app
  27. from apps.web.main import app as webui_app
  28. import asyncio
  29. from pydantic import BaseModel
  30. from typing import List
  31. from utils.utils import get_admin_user
  32. from apps.rag.utils import rag_messages
  33. from config import (
  34. CONFIG_DATA,
  35. WEBUI_NAME,
  36. ENV,
  37. VERSION,
  38. CHANGELOG,
  39. FRONTEND_BUILD_DIR,
  40. CACHE_DIR,
  41. STATIC_DIR,
  42. MODEL_FILTER_ENABLED,
  43. MODEL_FILTER_LIST,
  44. GLOBAL_LOG_LEVEL,
  45. SRC_LOG_LEVELS,
  46. WEBHOOK_URL,
  47. ENABLE_ADMIN_EXPORT,
  48. )
  49. from constants import ERROR_MESSAGES
  50. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  51. log = logging.getLogger(__name__)
  52. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  53. class SPAStaticFiles(StaticFiles):
  54. async def get_response(self, path: str, scope):
  55. try:
  56. return await super().get_response(path, scope)
  57. except (HTTPException, StarletteHTTPException) as ex:
  58. if ex.status_code == 404:
  59. return await super().get_response("index.html", scope)
  60. else:
  61. raise ex
  62. print(
  63. f"""
  64. ___ __ __ _ _ _ ___
  65. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  66. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  67. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  68. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  69. |_|
  70. v{VERSION} - building the best open-source AI user interface.
  71. https://github.com/open-webui/open-webui
  72. """
  73. )
  74. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  75. app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
  76. app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  77. app.state.WEBHOOK_URL = WEBHOOK_URL
  78. origins = ["*"]
  79. class RAGMiddleware(BaseHTTPMiddleware):
  80. async def dispatch(self, request: Request, call_next):
  81. if request.method == "POST" and (
  82. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  83. ):
  84. log.debug(f"request.url.path: {request.url.path}")
  85. # Read the original request body
  86. body = await request.body()
  87. # Decode body to string
  88. body_str = body.decode("utf-8")
  89. # Parse string to JSON
  90. data = json.loads(body_str) if body_str else {}
  91. # Example: Add a new key-value pair or modify existing ones
  92. # data["modified"] = True # Example modification
  93. if "docs" in data:
  94. data = {**data}
  95. data["messages"] = rag_messages(
  96. data["docs"],
  97. data["messages"],
  98. rag_app.state.RAG_TEMPLATE,
  99. rag_app.state.TOP_K,
  100. rag_app.state.RELEVANCE_THRESHOLD,
  101. rag_app.state.RAG_EMBEDDING_ENGINE,
  102. rag_app.state.RAG_EMBEDDING_MODEL,
  103. rag_app.state.sentence_transformer_ef,
  104. rag_app.state.sentence_transformer_rf,
  105. rag_app.state.OPENAI_API_KEY,
  106. rag_app.state.OPENAI_API_BASE_URL,
  107. )
  108. del data["docs"]
  109. log.debug(f"data['messages']: {data['messages']}")
  110. modified_body_bytes = json.dumps(data).encode("utf-8")
  111. # Replace the request body with the modified one
  112. request._body = modified_body_bytes
  113. # Set custom header to ensure content-length matches new body length
  114. request.headers.__dict__["_list"] = [
  115. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  116. *[
  117. (k, v)
  118. for k, v in request.headers.raw
  119. if k.lower() != b"content-length"
  120. ],
  121. ]
  122. response = await call_next(request)
  123. return response
  124. async def _receive(self, body: bytes):
  125. return {"type": "http.request", "body": body, "more_body": False}
  126. app.add_middleware(RAGMiddleware)
  127. app.add_middleware(
  128. CORSMiddleware,
  129. allow_origins=origins,
  130. allow_credentials=True,
  131. allow_methods=["*"],
  132. allow_headers=["*"],
  133. )
  134. @app.middleware("http")
  135. async def check_url(request: Request, call_next):
  136. start_time = int(time.time())
  137. response = await call_next(request)
  138. process_time = int(time.time()) - start_time
  139. response.headers["X-Process-Time"] = str(process_time)
  140. return response
  141. @app.on_event("startup")
  142. async def on_startup():
  143. asyncio.create_task(start_litellm_background())
  144. app.mount("/api/v1", webui_app)
  145. app.mount("/litellm/api", litellm_app)
  146. app.mount("/ollama", ollama_app)
  147. app.mount("/openai/api", openai_app)
  148. app.mount("/images/api/v1", images_app)
  149. app.mount("/audio/api/v1", audio_app)
  150. app.mount("/rag/api/v1", rag_app)
  151. @app.get("/api/config")
  152. async def get_app_config():
  153. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  154. default_locale = "en-US"
  155. if "ui" in CONFIG_DATA:
  156. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  157. # The Rest of the Function Now Uses the Variables Defined Above
  158. return {
  159. "status": True,
  160. "name": WEBUI_NAME,
  161. "version": VERSION,
  162. "default_locale": default_locale,
  163. "images": images_app.state.ENABLED,
  164. "default_models": webui_app.state.DEFAULT_MODELS,
  165. "default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
  166. "trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  167. "admin_export_enabled": ENABLE_ADMIN_EXPORT,
  168. }
  169. @app.get("/api/config/model/filter")
  170. async def get_model_filter_config(user=Depends(get_admin_user)):
  171. return {
  172. "enabled": app.state.MODEL_FILTER_ENABLED,
  173. "models": app.state.MODEL_FILTER_LIST,
  174. }
  175. class ModelFilterConfigForm(BaseModel):
  176. enabled: bool
  177. models: List[str]
  178. @app.post("/api/config/model/filter")
  179. async def update_model_filter_config(
  180. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  181. ):
  182. app.state.MODEL_FILTER_ENABLED = form_data.enabled
  183. app.state.MODEL_FILTER_LIST = form_data.models
  184. ollama_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  185. ollama_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  186. openai_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  187. openai_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  188. litellm_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  189. litellm_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  190. return {
  191. "enabled": app.state.MODEL_FILTER_ENABLED,
  192. "models": app.state.MODEL_FILTER_LIST,
  193. }
  194. @app.get("/api/webhook")
  195. async def get_webhook_url(user=Depends(get_admin_user)):
  196. return {
  197. "url": app.state.WEBHOOK_URL,
  198. }
  199. class UrlForm(BaseModel):
  200. url: str
  201. @app.post("/api/webhook")
  202. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  203. app.state.WEBHOOK_URL = form_data.url
  204. webui_app.state.WEBHOOK_URL = app.state.WEBHOOK_URL
  205. return {
  206. "url": app.state.WEBHOOK_URL,
  207. }
  208. @app.get("/api/version")
  209. async def get_app_config():
  210. return {
  211. "version": VERSION,
  212. }
  213. @app.get("/api/changelog")
  214. async def get_app_changelog():
  215. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  216. @app.get("/api/version/updates")
  217. async def get_app_latest_release_version():
  218. try:
  219. async with aiohttp.ClientSession() as session:
  220. async with session.get(
  221. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  222. ) as response:
  223. response.raise_for_status()
  224. data = await response.json()
  225. latest_version = data["tag_name"]
  226. return {"current": VERSION, "latest": latest_version[1:]}
  227. except aiohttp.ClientError as e:
  228. raise HTTPException(
  229. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  230. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  231. )
  232. @app.get("/manifest.json")
  233. async def get_manifest_json():
  234. return {
  235. "name": WEBUI_NAME,
  236. "short_name": WEBUI_NAME,
  237. "start_url": "/",
  238. "display": "standalone",
  239. "background_color": "#343541",
  240. "theme_color": "#343541",
  241. "orientation": "portrait-primary",
  242. "icons": [{"src": "/favicon.png", "type": "image/png", "sizes": "844x884"}],
  243. }
  244. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  245. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  246. app.mount(
  247. "/",
  248. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  249. name="spa-static-files",
  250. )
  251. @app.on_event("shutdown")
  252. async def shutdown_event():
  253. await shutdown_litellm_background()