main.py 7.9 KB

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