main.py 12 KB

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