main.py 8.3 KB

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