main.py 16 KB

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