main.py 12 KB

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