main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. from bs4 import BeautifulSoup
  2. import json
  3. import markdown
  4. import time
  5. import os
  6. import sys
  7. import logging
  8. import aiohttp
  9. import requests
  10. from fastapi import FastAPI, Request, Depends, status
  11. from fastapi.staticfiles import StaticFiles
  12. from fastapi import HTTPException
  13. from fastapi.middleware.wsgi import WSGIMiddleware
  14. from fastapi.middleware.cors import CORSMiddleware
  15. from starlette.exceptions import HTTPException as StarletteHTTPException
  16. from starlette.middleware.base import BaseHTTPMiddleware
  17. from starlette.responses import StreamingResponse, Response
  18. from apps.ollama.main import app as ollama_app
  19. from apps.openai.main import app as openai_app
  20. from apps.litellm.main import (
  21. app as litellm_app,
  22. start_litellm_background,
  23. shutdown_litellm_background,
  24. )
  25. from apps.audio.main import app as audio_app
  26. from apps.images.main import app as images_app
  27. from apps.rag.main import app as rag_app
  28. from apps.web.main import app as webui_app
  29. import asyncio
  30. from pydantic import BaseModel
  31. from typing import List
  32. from utils.utils import get_admin_user
  33. from apps.rag.utils import rag_messages
  34. from config import (
  35. CONFIG_DATA,
  36. WEBUI_NAME,
  37. WEBUI_URL,
  38. WEBUI_AUTH,
  39. ENV,
  40. VERSION,
  41. CHANGELOG,
  42. FRONTEND_BUILD_DIR,
  43. CACHE_DIR,
  44. STATIC_DIR,
  45. ENABLE_LITELLM,
  46. ENABLE_MODEL_FILTER,
  47. MODEL_FILTER_LIST,
  48. GLOBAL_LOG_LEVEL,
  49. SRC_LOG_LEVELS,
  50. WEBHOOK_URL,
  51. ENABLE_ADMIN_EXPORT,
  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. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  80. app.state.config = AppConfig()
  81. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  82. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  83. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  84. origins = ["*"]
  85. class RAGMiddleware(BaseHTTPMiddleware):
  86. async def dispatch(self, request: Request, call_next):
  87. return_citations = False
  88. if request.method == "POST" and (
  89. "/api/chat" in request.url.path or "/chat/completions" in request.url.path
  90. ):
  91. log.debug(f"request.url.path: {request.url.path}")
  92. # Read the original request body
  93. body = await request.body()
  94. # Decode body to string
  95. body_str = body.decode("utf-8")
  96. # Parse string to JSON
  97. data = json.loads(body_str) if body_str else {}
  98. return_citations = data.get("citations", False)
  99. if "citations" in data:
  100. del data["citations"]
  101. # Example: Add a new key-value pair or modify existing ones
  102. # data["modified"] = True # Example modification
  103. if "docs" in data:
  104. data = {**data}
  105. data["messages"], citations = rag_messages(
  106. docs=data["docs"],
  107. messages=data["messages"],
  108. template=rag_app.state.RAG_TEMPLATE,
  109. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  110. k=rag_app.state.TOP_K,
  111. reranking_function=rag_app.state.sentence_transformer_rf,
  112. r=rag_app.state.RELEVANCE_THRESHOLD,
  113. hybrid_search=rag_app.state.ENABLE_RAG_HYBRID_SEARCH,
  114. )
  115. del data["docs"]
  116. log.debug(
  117. f"data['messages']: {data['messages']}, citations: {citations}"
  118. )
  119. modified_body_bytes = json.dumps(data).encode("utf-8")
  120. # Replace the request body with the modified one
  121. request._body = modified_body_bytes
  122. # Set custom header to ensure content-length matches new body length
  123. request.headers.__dict__["_list"] = [
  124. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  125. *[
  126. (k, v)
  127. for k, v in request.headers.raw
  128. if k.lower() != b"content-length"
  129. ],
  130. ]
  131. response = await call_next(request)
  132. if return_citations:
  133. # Inject the citations into the response
  134. if isinstance(response, StreamingResponse):
  135. # If it's a streaming response, inject it as SSE event or NDJSON line
  136. content_type = response.headers.get("Content-Type")
  137. if "text/event-stream" in content_type:
  138. return StreamingResponse(
  139. self.openai_stream_wrapper(response.body_iterator, citations),
  140. )
  141. if "application/x-ndjson" in content_type:
  142. return StreamingResponse(
  143. self.ollama_stream_wrapper(response.body_iterator, citations),
  144. )
  145. return response
  146. async def _receive(self, body: bytes):
  147. return {"type": "http.request", "body": body, "more_body": False}
  148. async def openai_stream_wrapper(self, original_generator, citations):
  149. yield f"data: {json.dumps({'citations': citations})}\n\n"
  150. async for data in original_generator:
  151. yield data
  152. async def ollama_stream_wrapper(self, original_generator, citations):
  153. yield f"{json.dumps({'citations': citations})}\n"
  154. async for data in original_generator:
  155. yield data
  156. app.add_middleware(RAGMiddleware)
  157. app.add_middleware(
  158. CORSMiddleware,
  159. allow_origins=origins,
  160. allow_credentials=True,
  161. allow_methods=["*"],
  162. allow_headers=["*"],
  163. )
  164. @app.middleware("http")
  165. async def check_url(request: Request, call_next):
  166. start_time = int(time.time())
  167. response = await call_next(request)
  168. process_time = int(time.time()) - start_time
  169. response.headers["X-Process-Time"] = str(process_time)
  170. return response
  171. @app.on_event("startup")
  172. async def on_startup():
  173. if ENABLE_LITELLM:
  174. asyncio.create_task(start_litellm_background())
  175. app.mount("/api/v1", webui_app)
  176. app.mount("/litellm/api", litellm_app)
  177. app.mount("/ollama", ollama_app)
  178. app.mount("/openai/api", openai_app)
  179. app.mount("/images/api/v1", images_app)
  180. app.mount("/audio/api/v1", audio_app)
  181. app.mount("/rag/api/v1", rag_app)
  182. @app.get("/api/config")
  183. async def get_app_config():
  184. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  185. default_locale = "en-US"
  186. if "ui" in CONFIG_DATA:
  187. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  188. # The Rest of the Function Now Uses the Variables Defined Above
  189. return {
  190. "status": True,
  191. "name": WEBUI_NAME,
  192. "version": VERSION,
  193. "auth": WEBUI_AUTH,
  194. "default_locale": default_locale,
  195. "images": images_app.state.config.ENABLED,
  196. "default_models": webui_app.state.config.DEFAULT_MODELS,
  197. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  198. "trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  199. "admin_export_enabled": ENABLE_ADMIN_EXPORT,
  200. }
  201. @app.get("/api/config/model/filter")
  202. async def get_model_filter_config(user=Depends(get_admin_user)):
  203. return {
  204. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  205. "models": app.state.config.MODEL_FILTER_LIST,
  206. }
  207. class ModelFilterConfigForm(BaseModel):
  208. enabled: bool
  209. models: List[str]
  210. @app.post("/api/config/model/filter")
  211. async def update_model_filter_config(
  212. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  213. ):
  214. app.state.config.ENABLE_MODEL_FILTER, form_data.enabled
  215. app.state.config.MODEL_FILTER_LIST, form_data.models
  216. ollama_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
  217. ollama_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
  218. openai_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
  219. openai_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
  220. litellm_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
  221. litellm_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
  222. return {
  223. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  224. "models": app.state.config.MODEL_FILTER_LIST,
  225. }
  226. @app.get("/api/webhook")
  227. async def get_webhook_url(user=Depends(get_admin_user)):
  228. return {
  229. "url": app.state.config.WEBHOOK_URL,
  230. }
  231. class UrlForm(BaseModel):
  232. url: str
  233. @app.post("/api/webhook")
  234. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  235. app.state.config.WEBHOOK_URL = form_data.url
  236. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  237. return {
  238. "url": app.state.config.WEBHOOK_URL,
  239. }
  240. @app.get("/api/version")
  241. async def get_app_config():
  242. return {
  243. "version": VERSION,
  244. }
  245. @app.get("/api/changelog")
  246. async def get_app_changelog():
  247. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  248. @app.get("/api/version/updates")
  249. async def get_app_latest_release_version():
  250. try:
  251. async with aiohttp.ClientSession() as session:
  252. async with session.get(
  253. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  254. ) as response:
  255. response.raise_for_status()
  256. data = await response.json()
  257. latest_version = data["tag_name"]
  258. return {"current": VERSION, "latest": latest_version[1:]}
  259. except aiohttp.ClientError as e:
  260. raise HTTPException(
  261. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  262. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  263. )
  264. @app.get("/manifest.json")
  265. async def get_manifest_json():
  266. return {
  267. "name": WEBUI_NAME,
  268. "short_name": WEBUI_NAME,
  269. "start_url": "/",
  270. "display": "standalone",
  271. "background_color": "#343541",
  272. "theme_color": "#343541",
  273. "orientation": "portrait-primary",
  274. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  275. }
  276. @app.get("/opensearch.xml")
  277. async def get_opensearch_xml():
  278. xml_content = rf"""
  279. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  280. <ShortName>{WEBUI_NAME}</ShortName>
  281. <Description>Search {WEBUI_NAME}</Description>
  282. <InputEncoding>UTF-8</InputEncoding>
  283. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  284. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  285. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  286. </OpenSearchDescription>
  287. """
  288. return Response(content=xml_content, media_type="application/xml")
  289. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  290. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  291. if os.path.exists(FRONTEND_BUILD_DIR):
  292. app.mount(
  293. "/",
  294. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  295. name="spa-static-files",
  296. )
  297. else:
  298. log.warning(
  299. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  300. )
  301. @app.on_event("shutdown")
  302. async def shutdown_event():
  303. if ENABLE_LITELLM:
  304. await shutdown_litellm_background()