main.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. from bs4 import BeautifulSoup
  2. import json
  3. import markdown
  4. import time
  5. import os
  6. import sys
  7. import requests
  8. from fastapi import FastAPI, Request, Depends, status
  9. from fastapi.staticfiles import StaticFiles
  10. from fastapi import HTTPException
  11. from fastapi.responses import JSONResponse
  12. from fastapi.middleware.wsgi import WSGIMiddleware
  13. from fastapi.middleware.cors import CORSMiddleware
  14. from starlette.exceptions import HTTPException as StarletteHTTPException
  15. from litellm.proxy.proxy_server import ProxyConfig, initialize
  16. from litellm.proxy.proxy_server import app as litellm_app
  17. from apps.ollama.main import app as ollama_app
  18. from apps.openai.main import app as openai_app
  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 config import WEBUI_NAME, ENV, VERSION, CHANGELOG, FRONTEND_BUILD_DIR
  24. from constants import ERROR_MESSAGES
  25. from utils.utils import get_http_authorization_cred, get_current_user
  26. class SPAStaticFiles(StaticFiles):
  27. async def get_response(self, path: str, scope):
  28. try:
  29. return await super().get_response(path, scope)
  30. except (HTTPException, StarletteHTTPException) as ex:
  31. if ex.status_code == 404:
  32. return await super().get_response("index.html", scope)
  33. else:
  34. raise ex
  35. proxy_config = ProxyConfig()
  36. async def config():
  37. router, model_list, general_settings = await proxy_config.load_config(
  38. router=None, config_file_path="./data/litellm/config.yaml"
  39. )
  40. await initialize(config="./data/litellm/config.yaml", telemetry=False)
  41. async def startup():
  42. await config()
  43. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  44. origins = ["*"]
  45. app.add_middleware(
  46. CORSMiddleware,
  47. allow_origins=origins,
  48. allow_credentials=True,
  49. allow_methods=["*"],
  50. allow_headers=["*"],
  51. )
  52. @app.on_event("startup")
  53. async def on_startup():
  54. await startup()
  55. @app.middleware("http")
  56. async def check_url(request: Request, call_next):
  57. start_time = int(time.time())
  58. response = await call_next(request)
  59. process_time = int(time.time()) - start_time
  60. response.headers["X-Process-Time"] = str(process_time)
  61. return response
  62. @litellm_app.middleware("http")
  63. async def auth_middleware(request: Request, call_next):
  64. auth_header = request.headers.get("Authorization", "")
  65. if ENV != "dev":
  66. try:
  67. user = get_current_user(get_http_authorization_cred(auth_header))
  68. print(user)
  69. except Exception as e:
  70. return JSONResponse(status_code=400, content={"detail": str(e)})
  71. response = await call_next(request)
  72. return response
  73. app.mount("/api/v1", webui_app)
  74. app.mount("/litellm/api", litellm_app)
  75. app.mount("/ollama", ollama_app)
  76. app.mount("/openai/api", openai_app)
  77. app.mount("/images/api/v1", images_app)
  78. app.mount("/audio/api/v1", audio_app)
  79. app.mount("/rag/api/v1", rag_app)
  80. @app.get("/api/config")
  81. async def get_app_config():
  82. return {
  83. "status": True,
  84. "name": WEBUI_NAME,
  85. "version": VERSION,
  86. "images": images_app.state.ENABLED,
  87. "default_models": webui_app.state.DEFAULT_MODELS,
  88. "default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
  89. }
  90. @app.get("/api/version")
  91. async def get_app_config():
  92. return {
  93. "version": VERSION,
  94. }
  95. @app.get("/api/changelog")
  96. async def get_app_changelog():
  97. return CHANGELOG
  98. @app.get("/api/version/updates")
  99. async def get_app_latest_release_version():
  100. try:
  101. response = requests.get(
  102. f"https://api.github.com/repos/open-webui/open-webui/releases/latest"
  103. )
  104. response.raise_for_status()
  105. latest_version = response.json()["tag_name"]
  106. return {"current": VERSION, "latest": latest_version[1:]}
  107. except Exception as e:
  108. raise HTTPException(
  109. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  110. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  111. )
  112. app.mount("/static", StaticFiles(directory="static"), name="static")
  113. app.mount(
  114. "/",
  115. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  116. name="spa-static-files",
  117. )