main.py 8.9 KB

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