main.py 8.7 KB

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