main.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 aiohttp
  9. import requests
  10. from fastapi import FastAPI, Request, Depends, status
  11. from fastapi.staticfiles import StaticFiles
  12. from fastapi import HTTPException
  13. from fastapi.middleware.wsgi import WSGIMiddleware
  14. from fastapi.middleware.cors import CORSMiddleware
  15. from starlette.exceptions import HTTPException as StarletteHTTPException
  16. from starlette.middleware.base import BaseHTTPMiddleware
  17. from apps.ollama.main import app as ollama_app
  18. from apps.openai.main import app as openai_app
  19. from apps.litellm.main import app as litellm_app, startup as litellm_app_startup
  20. from apps.audio.main import app as audio_app
  21. from apps.images.main import app as images_app
  22. from apps.rag.main import app as rag_app
  23. from apps.web.main import app as webui_app
  24. from pydantic import BaseModel
  25. from typing import List
  26. from utils.utils import get_admin_user
  27. from apps.rag.utils import rag_messages
  28. from config import (
  29. CONFIG_DATA,
  30. WEBUI_NAME,
  31. ENV,
  32. VERSION,
  33. CHANGELOG,
  34. FRONTEND_BUILD_DIR,
  35. CACHE_DIR,
  36. STATIC_DIR,
  37. MODEL_FILTER_ENABLED,
  38. MODEL_FILTER_LIST,
  39. GLOBAL_LOG_LEVEL,
  40. SRC_LOG_LEVELS,
  41. WEBHOOK_URL,
  42. )
  43. from constants import ERROR_MESSAGES
  44. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  45. log = logging.getLogger(__name__)
  46. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  47. class SPAStaticFiles(StaticFiles):
  48. async def get_response(self, path: str, scope):
  49. try:
  50. return await super().get_response(path, scope)
  51. except (HTTPException, StarletteHTTPException) as ex:
  52. if ex.status_code == 404:
  53. return await super().get_response("index.html", scope)
  54. else:
  55. raise ex
  56. print(
  57. f"""
  58. ___ __ __ _ _ _ ___
  59. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  60. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  61. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  62. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  63. |_|
  64. v{VERSION} - building the best open-source AI user interface.
  65. https://github.com/open-webui/open-webui
  66. """
  67. )
  68. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  69. app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
  70. app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  71. app.state.WEBHOOK_URL = WEBHOOK_URL
  72. origins = ["*"]
  73. class RAGMiddleware(BaseHTTPMiddleware):
  74. async def dispatch(self, request: Request, call_next):
  75. if request.method == "POST" and (
  76. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  77. ):
  78. log.debug(f"request.url.path: {request.url.path}")
  79. # Read the original request body
  80. body = await request.body()
  81. # Decode body to string
  82. body_str = body.decode("utf-8")
  83. # Parse string to JSON
  84. data = json.loads(body_str) if body_str else {}
  85. # Example: Add a new key-value pair or modify existing ones
  86. # data["modified"] = True # Example modification
  87. if "docs" in data:
  88. data = {**data}
  89. data["messages"] = rag_messages(
  90. data["docs"],
  91. data["messages"],
  92. rag_app.state.RAG_TEMPLATE,
  93. rag_app.state.TOP_K,
  94. rag_app.state.RAG_EMBEDDING_ENGINE,
  95. rag_app.state.RAG_EMBEDDING_MODEL,
  96. rag_app.state.sentence_transformer_ef,
  97. rag_app.state.RAG_OPENAI_API_KEY,
  98. rag_app.state.RAG_OPENAI_API_BASE_URL,
  99. )
  100. del data["docs"]
  101. log.debug(f"data['messages']: {data['messages']}")
  102. modified_body_bytes = json.dumps(data).encode("utf-8")
  103. # Replace the request body with the modified one
  104. request._body = modified_body_bytes
  105. # Set custom header to ensure content-length matches new body length
  106. request.headers.__dict__["_list"] = [
  107. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  108. *[
  109. (k, v)
  110. for k, v in request.headers.raw
  111. if k.lower() != b"content-length"
  112. ],
  113. ]
  114. response = await call_next(request)
  115. return response
  116. async def _receive(self, body: bytes):
  117. return {"type": "http.request", "body": body, "more_body": False}
  118. app.add_middleware(RAGMiddleware)
  119. app.add_middleware(
  120. CORSMiddleware,
  121. allow_origins=origins,
  122. allow_credentials=True,
  123. allow_methods=["*"],
  124. allow_headers=["*"],
  125. )
  126. @app.middleware("http")
  127. async def check_url(request: Request, call_next):
  128. start_time = int(time.time())
  129. response = await call_next(request)
  130. process_time = int(time.time()) - start_time
  131. response.headers["X-Process-Time"] = str(process_time)
  132. return response
  133. @app.on_event("startup")
  134. async def on_startup():
  135. await litellm_app_startup()
  136. app.mount("/api/v1", webui_app)
  137. app.mount("/litellm/api", litellm_app)
  138. app.mount("/ollama", ollama_app)
  139. app.mount("/openai/api", openai_app)
  140. app.mount("/images/api/v1", images_app)
  141. app.mount("/audio/api/v1", audio_app)
  142. app.mount("/rag/api/v1", rag_app)
  143. @app.get("/api/config")
  144. async def get_app_config():
  145. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  146. default_locale = "en-US"
  147. if "ui" in CONFIG_DATA:
  148. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  149. # The Rest of the Function Now Uses the Variables Defined Above
  150. return {
  151. "status": True,
  152. "name": WEBUI_NAME,
  153. "version": VERSION,
  154. "default_locale": default_locale,
  155. "images": images_app.state.ENABLED,
  156. "default_models": webui_app.state.DEFAULT_MODELS,
  157. "default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
  158. "trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  159. }
  160. @app.get("/api/config/model/filter")
  161. async def get_model_filter_config(user=Depends(get_admin_user)):
  162. return {
  163. "enabled": app.state.MODEL_FILTER_ENABLED,
  164. "models": app.state.MODEL_FILTER_LIST,
  165. }
  166. class ModelFilterConfigForm(BaseModel):
  167. enabled: bool
  168. models: List[str]
  169. @app.post("/api/config/model/filter")
  170. async def update_model_filter_config(
  171. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  172. ):
  173. app.state.MODEL_FILTER_ENABLED = form_data.enabled
  174. app.state.MODEL_FILTER_LIST = form_data.models
  175. ollama_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  176. ollama_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  177. openai_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  178. openai_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  179. litellm_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  180. litellm_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  181. return {
  182. "enabled": app.state.MODEL_FILTER_ENABLED,
  183. "models": app.state.MODEL_FILTER_LIST,
  184. }
  185. @app.get("/api/webhook")
  186. async def get_webhook_url(user=Depends(get_admin_user)):
  187. return {
  188. "url": app.state.WEBHOOK_URL,
  189. }
  190. class UrlForm(BaseModel):
  191. url: str
  192. @app.post("/api/webhook")
  193. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  194. app.state.WEBHOOK_URL = form_data.url
  195. webui_app.state.WEBHOOK_URL = app.state.WEBHOOK_URL
  196. return {
  197. "url": app.state.WEBHOOK_URL,
  198. }
  199. @app.get("/api/version")
  200. async def get_app_config():
  201. return {
  202. "version": VERSION,
  203. }
  204. @app.get("/api/changelog")
  205. async def get_app_changelog():
  206. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  207. @app.get("/api/version/updates")
  208. async def get_app_latest_release_version():
  209. try:
  210. async with aiohttp.ClientSession() as session:
  211. async with session.get(
  212. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  213. ) as response:
  214. response.raise_for_status()
  215. data = await response.json()
  216. latest_version = data["tag_name"]
  217. return {"current": VERSION, "latest": latest_version[1:]}
  218. except aiohttp.ClientError as e:
  219. raise HTTPException(
  220. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  221. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  222. )
  223. @app.get("/manifest.json")
  224. async def get_manifest_json():
  225. return {
  226. "name": WEBUI_NAME,
  227. "short_name": WEBUI_NAME,
  228. "start_url": "/",
  229. "display": "standalone",
  230. "background_color": "#343541",
  231. "theme_color": "#343541",
  232. "orientation": "portrait-primary",
  233. "icons": [{"src": "/favicon.png", "type": "image/png", "sizes": "844x884"}],
  234. }
  235. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  236. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  237. app.mount(
  238. "/",
  239. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  240. name="spa-static-files",
  241. )