main.py 16 KB

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