main.py 8.4 KB

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