main.py 15 KB

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