main.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. from contextlib import asynccontextmanager
  2. from bs4 import BeautifulSoup
  3. import json
  4. import markdown
  5. import time
  6. import os
  7. import sys
  8. import logging
  9. import aiohttp
  10. import requests
  11. from fastapi import FastAPI, Request, Depends, status
  12. from fastapi.staticfiles import StaticFiles
  13. from fastapi import HTTPException
  14. from fastapi.middleware.wsgi import WSGIMiddleware
  15. from fastapi.middleware.cors import CORSMiddleware
  16. from starlette.exceptions import HTTPException as StarletteHTTPException
  17. from starlette.middleware.base import BaseHTTPMiddleware
  18. from starlette.responses import StreamingResponse, Response
  19. from apps.ollama.main import app as ollama_app
  20. from apps.openai.main import app as openai_app
  21. from apps.litellm.main import (
  22. app as litellm_app,
  23. start_litellm_background,
  24. shutdown_litellm_background,
  25. )
  26. from apps.audio.main import app as audio_app
  27. from apps.images.main import app as images_app
  28. from apps.rag.main import app as rag_app
  29. from apps.web.main import app as webui_app
  30. import asyncio
  31. from pydantic import BaseModel
  32. from typing import List
  33. from utils.utils import get_admin_user
  34. from apps.rag.utils import rag_messages
  35. from config import (
  36. CONFIG_DATA,
  37. WEBUI_NAME,
  38. WEBUI_URL,
  39. WEBUI_AUTH,
  40. ENV,
  41. VERSION,
  42. CHANGELOG,
  43. FRONTEND_BUILD_DIR,
  44. CACHE_DIR,
  45. STATIC_DIR,
  46. ENABLE_LITELLM,
  47. ENABLE_MODEL_FILTER,
  48. MODEL_FILTER_LIST,
  49. GLOBAL_LOG_LEVEL,
  50. SRC_LOG_LEVELS,
  51. WEBHOOK_URL,
  52. ENABLE_ADMIN_EXPORT,
  53. MODEL_CONFIG,
  54. AppConfig,
  55. )
  56. from constants import ERROR_MESSAGES
  57. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  58. log = logging.getLogger(__name__)
  59. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  60. class SPAStaticFiles(StaticFiles):
  61. async def get_response(self, path: str, scope):
  62. try:
  63. return await super().get_response(path, scope)
  64. except (HTTPException, StarletteHTTPException) as ex:
  65. if ex.status_code == 404:
  66. return await super().get_response("index.html", scope)
  67. else:
  68. raise ex
  69. print(
  70. rf"""
  71. ___ __ __ _ _ _ ___
  72. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  73. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  74. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  75. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  76. |_|
  77. v{VERSION} - building the best open-source AI user interface.
  78. https://github.com/open-webui/open-webui
  79. """
  80. )
  81. @asynccontextmanager
  82. async def lifespan(app: FastAPI):
  83. if ENABLE_LITELLM:
  84. asyncio.create_task(start_litellm_background())
  85. yield
  86. if ENABLE_LITELLM:
  87. await shutdown_litellm_background()
  88. app = FastAPI(
  89. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  90. )
  91. app.state.config = AppConfig()
  92. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  93. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  94. app.state.config.MODEL_CONFIG = MODEL_CONFIG
  95. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  96. origins = ["*"]
  97. class RAGMiddleware(BaseHTTPMiddleware):
  98. async def dispatch(self, request: Request, call_next):
  99. return_citations = False
  100. if request.method == "POST" and (
  101. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  102. ):
  103. log.debug(f"request.url.path: {request.url.path}")
  104. # Read the original request body
  105. body = await request.body()
  106. # Decode body to string
  107. body_str = body.decode("utf-8")
  108. # Parse string to JSON
  109. data = json.loads(body_str) if body_str else {}
  110. return_citations = data.get("citations", False)
  111. if "citations" in data:
  112. del data["citations"]
  113. # Example: Add a new key-value pair or modify existing ones
  114. # data["modified"] = True # Example modification
  115. if "docs" in data:
  116. data = {**data}
  117. data["messages"], citations = rag_messages(
  118. docs=data["docs"],
  119. messages=data["messages"],
  120. template=rag_app.state.config.RAG_TEMPLATE,
  121. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  122. k=rag_app.state.config.TOP_K,
  123. reranking_function=rag_app.state.sentence_transformer_rf,
  124. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  125. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  126. )
  127. del data["docs"]
  128. log.debug(
  129. f"data['messages']: {data['messages']}, citations: {citations}"
  130. )
  131. modified_body_bytes = json.dumps(data).encode("utf-8")
  132. # Replace the request body with the modified one
  133. request._body = modified_body_bytes
  134. # Set custom header to ensure content-length matches new body length
  135. request.headers.__dict__["_list"] = [
  136. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  137. *[
  138. (k, v)
  139. for k, v in request.headers.raw
  140. if k.lower() != b"content-length"
  141. ],
  142. ]
  143. response = await call_next(request)
  144. if return_citations:
  145. # Inject the citations into the response
  146. if isinstance(response, StreamingResponse):
  147. # If it's a streaming response, inject it as SSE event or NDJSON line
  148. content_type = response.headers.get("Content-Type")
  149. if "text/event-stream" in content_type:
  150. return StreamingResponse(
  151. self.openai_stream_wrapper(response.body_iterator, citations),
  152. )
  153. if "application/x-ndjson" in content_type:
  154. return StreamingResponse(
  155. self.ollama_stream_wrapper(response.body_iterator, citations),
  156. )
  157. return response
  158. async def _receive(self, body: bytes):
  159. return {"type": "http.request", "body": body, "more_body": False}
  160. async def openai_stream_wrapper(self, original_generator, citations):
  161. yield f"data: {json.dumps({'citations': citations})}\n\n"
  162. async for data in original_generator:
  163. yield data
  164. async def ollama_stream_wrapper(self, original_generator, citations):
  165. yield f"{json.dumps({'citations': citations})}\n"
  166. async for data in original_generator:
  167. yield data
  168. app.add_middleware(RAGMiddleware)
  169. app.add_middleware(
  170. CORSMiddleware,
  171. allow_origins=origins,
  172. allow_credentials=True,
  173. allow_methods=["*"],
  174. allow_headers=["*"],
  175. )
  176. @app.middleware("http")
  177. async def check_url(request: Request, call_next):
  178. start_time = int(time.time())
  179. response = await call_next(request)
  180. process_time = int(time.time()) - start_time
  181. response.headers["X-Process-Time"] = str(process_time)
  182. return response
  183. app.mount("/api/v1", webui_app)
  184. app.mount("/litellm/api", litellm_app)
  185. app.mount("/ollama", ollama_app)
  186. app.mount("/openai/api", openai_app)
  187. app.mount("/images/api/v1", images_app)
  188. app.mount("/audio/api/v1", audio_app)
  189. app.mount("/rag/api/v1", rag_app)
  190. @app.get("/api/config")
  191. async def get_app_config():
  192. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  193. default_locale = "en-US"
  194. if "ui" in CONFIG_DATA:
  195. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  196. # The Rest of the Function Now Uses the Variables Defined Above
  197. return {
  198. "status": True,
  199. "name": WEBUI_NAME,
  200. "version": VERSION,
  201. "auth": WEBUI_AUTH,
  202. "default_locale": default_locale,
  203. "images": images_app.state.config.ENABLED,
  204. "default_models": webui_app.state.config.DEFAULT_MODELS,
  205. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  206. "trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  207. "admin_export_enabled": ENABLE_ADMIN_EXPORT,
  208. }
  209. @app.get("/api/config/model/filter")
  210. async def get_model_filter_config(user=Depends(get_admin_user)):
  211. return {
  212. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  213. "models": app.state.config.MODEL_FILTER_LIST,
  214. }
  215. class ModelFilterConfigForm(BaseModel):
  216. enabled: bool
  217. models: List[str]
  218. @app.post("/api/config/model/filter")
  219. async def update_model_filter_config(
  220. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  221. ):
  222. app.state.config.ENABLE_MODEL_FILTER, form_data.enabled
  223. app.state.config.MODEL_FILTER_LIST, form_data.models
  224. ollama_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
  225. ollama_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
  226. openai_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
  227. openai_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
  228. litellm_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
  229. litellm_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
  230. return {
  231. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  232. "models": app.state.config.MODEL_FILTER_LIST,
  233. }
  234. class ModelConfig(BaseModel):
  235. id: str
  236. name: str
  237. description: str
  238. vision_capable: bool
  239. class SetModelConfigForm(BaseModel):
  240. ollama: List[ModelConfig]
  241. litellm: List[ModelConfig]
  242. openai: List[ModelConfig]
  243. @app.post("/api/config/models")
  244. async def update_model_config(
  245. form_data: SetModelConfigForm, user=Depends(get_admin_user)
  246. ):
  247. data = form_data.model_dump()
  248. ollama_app.state.MODEL_CONFIG = data.get("ollama", [])
  249. openai_app.state.MODEL_CONFIG = data.get("openai", [])
  250. litellm_app.state.MODEL_CONFIG = data.get("litellm", [])
  251. app.state.config.MODEL_CONFIG = {
  252. "ollama": ollama_app.state.MODEL_CONFIG,
  253. "openai": openai_app.state.MODEL_CONFIG,
  254. "litellm": litellm_app.state.MODEL_CONFIG,
  255. }
  256. return {"models": app.state.config.MODEL_CONFIG}
  257. @app.get("/api/config/models")
  258. async def get_model_config(user=Depends(get_admin_user)):
  259. return {"models": app.state.config.MODEL_CONFIG}
  260. @app.get("/api/webhook")
  261. async def get_webhook_url(user=Depends(get_admin_user)):
  262. return {
  263. "url": app.state.config.WEBHOOK_URL,
  264. }
  265. class UrlForm(BaseModel):
  266. url: str
  267. @app.post("/api/webhook")
  268. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  269. app.state.config.WEBHOOK_URL = form_data.url
  270. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  271. return {
  272. "url": app.state.config.WEBHOOK_URL,
  273. }
  274. @app.get("/api/version")
  275. async def get_app_config():
  276. return {
  277. "version": VERSION,
  278. }
  279. @app.get("/api/changelog")
  280. async def get_app_changelog():
  281. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  282. @app.get("/api/version/updates")
  283. async def get_app_latest_release_version():
  284. try:
  285. async with aiohttp.ClientSession() as session:
  286. async with session.get(
  287. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  288. ) as response:
  289. response.raise_for_status()
  290. data = await response.json()
  291. latest_version = data["tag_name"]
  292. return {"current": VERSION, "latest": latest_version[1:]}
  293. except aiohttp.ClientError as e:
  294. raise HTTPException(
  295. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  296. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  297. )
  298. @app.get("/manifest.json")
  299. async def get_manifest_json():
  300. return {
  301. "name": WEBUI_NAME,
  302. "short_name": WEBUI_NAME,
  303. "start_url": "/",
  304. "display": "standalone",
  305. "background_color": "#343541",
  306. "theme_color": "#343541",
  307. "orientation": "portrait-primary",
  308. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  309. }
  310. @app.get("/opensearch.xml")
  311. async def get_opensearch_xml():
  312. xml_content = rf"""
  313. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  314. <ShortName>{WEBUI_NAME}</ShortName>
  315. <Description>Search {WEBUI_NAME}</Description>
  316. <InputEncoding>UTF-8</InputEncoding>
  317. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  318. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  319. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  320. </OpenSearchDescription>
  321. """
  322. return Response(content=xml_content, media_type="application/xml")
  323. @app.get("/health")
  324. async def healthcheck():
  325. return {"status": True}
  326. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  327. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  328. if os.path.exists(FRONTEND_BUILD_DIR):
  329. app.mount(
  330. "/",
  331. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  332. name="spa-static-files",
  333. )
  334. else:
  335. log.warning(
  336. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  337. )