main.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. from bs4 import BeautifulSoup
  2. import json
  3. import markdown
  4. import time
  5. import os
  6. import sys
  7. import requests
  8. from fastapi import FastAPI, Request, Depends, status
  9. from fastapi.staticfiles import StaticFiles
  10. from fastapi import HTTPException
  11. from fastapi.middleware.wsgi import WSGIMiddleware
  12. from fastapi.middleware.cors import CORSMiddleware
  13. from starlette.exceptions import HTTPException as StarletteHTTPException
  14. from starlette.middleware.base import BaseHTTPMiddleware
  15. from apps.ollama.main import app as ollama_app
  16. from apps.openai.main import app as openai_app
  17. from apps.litellm.main import app as litellm_app, startup as litellm_app_startup
  18. from apps.audio.main import app as audio_app
  19. from apps.images.main import app as images_app
  20. from apps.rag.main import app as rag_app
  21. from apps.web.main import app as webui_app
  22. from pydantic import BaseModel
  23. from typing import List
  24. from utils.utils import get_admin_user
  25. from apps.rag.utils import rag_messages
  26. from config import (
  27. WEBUI_NAME,
  28. ENV,
  29. VERSION,
  30. CHANGELOG,
  31. FRONTEND_BUILD_DIR,
  32. MODEL_FILTER_ENABLED,
  33. MODEL_FILTER_LIST,
  34. WEBHOOK_URL,
  35. )
  36. from constants import ERROR_MESSAGES
  37. class SPAStaticFiles(StaticFiles):
  38. async def get_response(self, path: str, scope):
  39. try:
  40. return await super().get_response(path, scope)
  41. except (HTTPException, StarletteHTTPException) as ex:
  42. if ex.status_code == 404:
  43. return await super().get_response("index.html", scope)
  44. else:
  45. raise ex
  46. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  47. app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
  48. app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  49. app.state.WEBHOOK_URL = WEBHOOK_URL
  50. origins = ["*"]
  51. class RAGMiddleware(BaseHTTPMiddleware):
  52. async def dispatch(self, request: Request, call_next):
  53. if request.method == "POST" and (
  54. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  55. ):
  56. print(request.url.path)
  57. # Read the original request body
  58. body = await request.body()
  59. # Decode body to string
  60. body_str = body.decode("utf-8")
  61. # Parse string to JSON
  62. data = json.loads(body_str) if body_str else {}
  63. # Example: Add a new key-value pair or modify existing ones
  64. # data["modified"] = True # Example modification
  65. if "docs" in data:
  66. data = {**data}
  67. data["messages"] = rag_messages(
  68. data["docs"],
  69. data["messages"],
  70. rag_app.state.RAG_TEMPLATE,
  71. rag_app.state.TOP_K,
  72. rag_app.state.sentence_transformer_ef,
  73. )
  74. del data["docs"]
  75. print(data["messages"])
  76. modified_body_bytes = json.dumps(data).encode("utf-8")
  77. # Replace the request body with the modified one
  78. request._body = modified_body_bytes
  79. # Set custom header to ensure content-length matches new body length
  80. request.headers.__dict__["_list"] = [
  81. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  82. *[
  83. (k, v)
  84. for k, v in request.headers.raw
  85. if k.lower() != b"content-length"
  86. ],
  87. ]
  88. response = await call_next(request)
  89. return response
  90. async def _receive(self, body: bytes):
  91. return {"type": "http.request", "body": body, "more_body": False}
  92. app.add_middleware(RAGMiddleware)
  93. app.add_middleware(
  94. CORSMiddleware,
  95. allow_origins=origins,
  96. allow_credentials=True,
  97. allow_methods=["*"],
  98. allow_headers=["*"],
  99. )
  100. @app.middleware("http")
  101. async def check_url(request: Request, call_next):
  102. start_time = int(time.time())
  103. response = await call_next(request)
  104. process_time = int(time.time()) - start_time
  105. response.headers["X-Process-Time"] = str(process_time)
  106. return response
  107. @app.on_event("startup")
  108. async def on_startup():
  109. await litellm_app_startup()
  110. app.mount("/api/v1", webui_app)
  111. app.mount("/litellm/api", litellm_app)
  112. app.mount("/ollama", ollama_app)
  113. app.mount("/openai/api", openai_app)
  114. app.mount("/images/api/v1", images_app)
  115. app.mount("/audio/api/v1", audio_app)
  116. app.mount("/rag/api/v1", rag_app)
  117. @app.get("/api/config")
  118. async def get_app_config():
  119. return {
  120. "status": True,
  121. "name": WEBUI_NAME,
  122. "version": VERSION,
  123. "images": images_app.state.ENABLED,
  124. "default_models": webui_app.state.DEFAULT_MODELS,
  125. "default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
  126. }
  127. @app.get("/api/config/model/filter")
  128. async def get_model_filter_config(user=Depends(get_admin_user)):
  129. return {
  130. "enabled": app.state.MODEL_FILTER_ENABLED,
  131. "models": app.state.MODEL_FILTER_LIST,
  132. }
  133. class ModelFilterConfigForm(BaseModel):
  134. enabled: bool
  135. models: List[str]
  136. @app.post("/api/config/model/filter")
  137. async def update_model_filter_config(
  138. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  139. ):
  140. app.state.MODEL_FILTER_ENABLED = form_data.enabled
  141. app.state.MODEL_FILTER_LIST = form_data.models
  142. ollama_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  143. ollama_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  144. openai_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
  145. openai_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
  146. return {
  147. "enabled": app.state.MODEL_FILTER_ENABLED,
  148. "models": app.state.MODEL_FILTER_LIST,
  149. }
  150. @app.get("/api/webhook")
  151. async def get_webhook_url(user=Depends(get_admin_user)):
  152. return {
  153. "url": app.state.WEBHOOK_URL,
  154. }
  155. class UrlForm(BaseModel):
  156. url: str
  157. @app.post("/api/webhook")
  158. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  159. app.state.WEBHOOK_URL = form_data.url
  160. webui_app.state.WEBHOOK_URL = app.state.WEBHOOK_URL
  161. return {
  162. "url": app.state.WEBHOOK_URL,
  163. }
  164. @app.get("/api/version")
  165. async def get_app_config():
  166. return {
  167. "version": VERSION,
  168. }
  169. @app.get("/api/changelog")
  170. async def get_app_changelog():
  171. return CHANGELOG
  172. @app.get("/api/version/updates")
  173. async def get_app_latest_release_version():
  174. try:
  175. response = requests.get(
  176. f"https://api.github.com/repos/open-webui/open-webui/releases/latest"
  177. )
  178. response.raise_for_status()
  179. latest_version = response.json()["tag_name"]
  180. return {"current": VERSION, "latest": latest_version[1:]}
  181. except Exception as e:
  182. raise HTTPException(
  183. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  184. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  185. )
  186. app.mount("/static", StaticFiles(directory="static"), name="static")
  187. app.mount("/cache", StaticFiles(directory="data/cache"), name="cache")
  188. app.mount(
  189. "/",
  190. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  191. name="spa-static-files",
  192. )