main.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. WEBUI_NAME,
  29. ENV,
  30. VERSION,
  31. CHANGELOG,
  32. FRONTEND_BUILD_DIR,
  33. MODEL_FILTER_ENABLED,
  34. MODEL_FILTER_LIST,
  35. GLOBAL_LOG_LEVEL,
  36. SRC_LOG_LEVELS,
  37. WEBHOOK_URL,
  38. )
  39. from constants import ERROR_MESSAGES
  40. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  41. log = logging.getLogger(__name__)
  42. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  43. class SPAStaticFiles(StaticFiles):
  44. async def get_response(self, path: str, scope):
  45. try:
  46. return await super().get_response(path, scope)
  47. except (HTTPException, StarletteHTTPException) as ex:
  48. if ex.status_code == 404:
  49. return await super().get_response("index.html", scope)
  50. else:
  51. raise ex
  52. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  53. app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
  54. app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  55. app.state.WEBHOOK_URL = WEBHOOK_URL
  56. origins = ["*"]
  57. class RAGMiddleware(BaseHTTPMiddleware):
  58. async def dispatch(self, request: Request, call_next):
  59. if request.method == "POST" and (
  60. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  61. ):
  62. log.debug(f"request.url.path: {request.url.path}")
  63. # Read the original request body
  64. body = await request.body()
  65. # Decode body to string
  66. body_str = body.decode("utf-8")
  67. # Parse string to JSON
  68. data = json.loads(body_str) if body_str else {}
  69. # Example: Add a new key-value pair or modify existing ones
  70. # data["modified"] = True # Example modification
  71. if "docs" in data:
  72. data = {**data}
  73. data["messages"] = rag_messages(
  74. data["docs"],
  75. data["messages"],
  76. rag_app.state.RAG_TEMPLATE,
  77. rag_app.state.TOP_K,
  78. rag_app.state.sentence_transformer_ef,
  79. )
  80. del data["docs"]
  81. log.debug(f"data['messages']: {data['messages']}")
  82. modified_body_bytes = json.dumps(data).encode("utf-8")
  83. # Replace the request body with the modified one
  84. request._body = modified_body_bytes
  85. # Set custom header to ensure content-length matches new body length
  86. request.headers.__dict__["_list"] = [
  87. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  88. *[
  89. (k, v)
  90. for k, v in request.headers.raw
  91. if k.lower() != b"content-length"
  92. ],
  93. ]
  94. response = await call_next(request)
  95. return response
  96. async def _receive(self, body: bytes):
  97. return {"type": "http.request", "body": body, "more_body": False}
  98. app.add_middleware(RAGMiddleware)
  99. app.add_middleware(
  100. CORSMiddleware,
  101. allow_origins=origins,
  102. allow_credentials=True,
  103. allow_methods=["*"],
  104. allow_headers=["*"],
  105. )
  106. @app.middleware("http")
  107. async def check_url(request: Request, call_next):
  108. start_time = int(time.time())
  109. response = await call_next(request)
  110. process_time = int(time.time()) - start_time
  111. response.headers["X-Process-Time"] = str(process_time)
  112. return response
  113. @app.on_event("startup")
  114. async def on_startup():
  115. await litellm_app_startup()
  116. app.mount("/api/v1", webui_app)
  117. app.mount("/litellm/api", litellm_app)
  118. app.mount("/ollama", ollama_app)
  119. app.mount("/openai/api", openai_app)
  120. app.mount("/images/api/v1", images_app)
  121. app.mount("/audio/api/v1", audio_app)
  122. app.mount("/rag/api/v1", rag_app)
  123. @app.get("/api/config")
  124. async def get_app_config():
  125. return {
  126. "status": True,
  127. "name": WEBUI_NAME,
  128. "version": VERSION,
  129. "images": images_app.state.ENABLED,
  130. "default_models": webui_app.state.DEFAULT_MODELS,
  131. "default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
  132. "trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  133. }
  134. @app.get("/api/config/model/filter")
  135. async def get_model_filter_config(user=Depends(get_admin_user)):
  136. return {
  137. "enabled": app.state.MODEL_FILTER_ENABLED,
  138. "models": app.state.MODEL_FILTER_LIST,
  139. }
  140. class ModelFilterConfigForm(BaseModel):
  141. enabled: bool
  142. models: List[str]
  143. @app.post("/api/config/model/filter")
  144. async def update_model_filter_config(
  145. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  146. ):
  147. app.state.MODEL_FILTER_ENABLED = form_data.enabled
  148. app.state.MODEL_FILTER_LIST = form_data.models
  149. ollama_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  150. ollama_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  151. openai_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  152. openai_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  153. return {
  154. "enabled": app.state.MODEL_FILTER_ENABLED,
  155. "models": app.state.MODEL_FILTER_LIST,
  156. }
  157. @app.get("/api/webhook")
  158. async def get_webhook_url(user=Depends(get_admin_user)):
  159. return {
  160. "url": app.state.WEBHOOK_URL,
  161. }
  162. class UrlForm(BaseModel):
  163. url: str
  164. @app.post("/api/webhook")
  165. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  166. app.state.WEBHOOK_URL = form_data.url
  167. webui_app.state.WEBHOOK_URL = app.state.WEBHOOK_URL
  168. return {
  169. "url": app.state.WEBHOOK_URL,
  170. }
  171. @app.get("/api/version")
  172. async def get_app_config():
  173. return {
  174. "version": VERSION,
  175. }
  176. @app.get("/api/changelog")
  177. async def get_app_changelog():
  178. return CHANGELOG
  179. @app.get("/api/version/updates")
  180. async def get_app_latest_release_version():
  181. try:
  182. response = requests.get(
  183. f"https://api.github.com/repos/open-webui/open-webui/releases/latest"
  184. )
  185. response.raise_for_status()
  186. latest_version = response.json()["tag_name"]
  187. return {"current": VERSION, "latest": latest_version[1:]}
  188. except Exception as e:
  189. raise HTTPException(
  190. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  191. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  192. )
  193. app.mount("/static", StaticFiles(directory="static"), name="static")
  194. app.mount("/cache", StaticFiles(directory="data/cache"), name="cache")
  195. app.mount(
  196. "/",
  197. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  198. name="spa-static-files",
  199. )