main.py 16 KB

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