main.py 9.1 KB

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