main.py 15 KB

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