main.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. import asyncio
  2. import inspect
  3. import json
  4. import logging
  5. import mimetypes
  6. import os
  7. import shutil
  8. import sys
  9. import time
  10. import random
  11. from contextlib import asynccontextmanager
  12. from urllib.parse import urlencode, parse_qs, urlparse
  13. from pydantic import BaseModel
  14. from sqlalchemy import text
  15. from typing import Optional
  16. from aiocache import cached
  17. import aiohttp
  18. import requests
  19. from fastapi import (
  20. Depends,
  21. FastAPI,
  22. File,
  23. Form,
  24. HTTPException,
  25. Request,
  26. UploadFile,
  27. status,
  28. applications,
  29. BackgroundTasks,
  30. )
  31. from fastapi.openapi.docs import get_swagger_ui_html
  32. from fastapi.middleware.cors import CORSMiddleware
  33. from fastapi.responses import JSONResponse, RedirectResponse
  34. from fastapi.staticfiles import StaticFiles
  35. from starlette.exceptions import HTTPException as StarletteHTTPException
  36. from starlette.middleware.base import BaseHTTPMiddleware
  37. from starlette.middleware.sessions import SessionMiddleware
  38. from starlette.responses import Response, StreamingResponse
  39. from open_webui.socket.main import (
  40. app as socket_app,
  41. periodic_usage_pool_cleanup,
  42. )
  43. from open_webui.routers import (
  44. audio,
  45. images,
  46. ollama,
  47. openai,
  48. retrieval,
  49. pipelines,
  50. tasks,
  51. auths,
  52. channels,
  53. chats,
  54. folders,
  55. configs,
  56. groups,
  57. files,
  58. functions,
  59. memories,
  60. models,
  61. knowledge,
  62. prompts,
  63. evaluations,
  64. tools,
  65. users,
  66. utils,
  67. )
  68. from open_webui.routers.retrieval import (
  69. get_embedding_function,
  70. get_ef,
  71. get_rf,
  72. )
  73. from open_webui.internal.db import Session
  74. from open_webui.models.functions import Functions
  75. from open_webui.models.models import Models
  76. from open_webui.models.users import UserModel, Users
  77. from open_webui.config import (
  78. # Ollama
  79. ENABLE_OLLAMA_API,
  80. OLLAMA_BASE_URLS,
  81. OLLAMA_API_CONFIGS,
  82. # OpenAI
  83. ENABLE_OPENAI_API,
  84. OPENAI_API_BASE_URLS,
  85. OPENAI_API_KEYS,
  86. OPENAI_API_CONFIGS,
  87. # Image
  88. AUTOMATIC1111_API_AUTH,
  89. AUTOMATIC1111_BASE_URL,
  90. AUTOMATIC1111_CFG_SCALE,
  91. AUTOMATIC1111_SAMPLER,
  92. AUTOMATIC1111_SCHEDULER,
  93. COMFYUI_BASE_URL,
  94. COMFYUI_API_KEY,
  95. COMFYUI_WORKFLOW,
  96. COMFYUI_WORKFLOW_NODES,
  97. ENABLE_IMAGE_GENERATION,
  98. ENABLE_IMAGE_PROMPT_GENERATION,
  99. IMAGE_GENERATION_ENGINE,
  100. IMAGE_GENERATION_MODEL,
  101. IMAGE_SIZE,
  102. IMAGE_STEPS,
  103. IMAGES_OPENAI_API_BASE_URL,
  104. IMAGES_OPENAI_API_KEY,
  105. # Audio
  106. AUDIO_STT_ENGINE,
  107. AUDIO_STT_MODEL,
  108. AUDIO_STT_OPENAI_API_BASE_URL,
  109. AUDIO_STT_OPENAI_API_KEY,
  110. AUDIO_TTS_API_KEY,
  111. AUDIO_TTS_ENGINE,
  112. AUDIO_TTS_MODEL,
  113. AUDIO_TTS_OPENAI_API_BASE_URL,
  114. AUDIO_TTS_OPENAI_API_KEY,
  115. AUDIO_TTS_SPLIT_ON,
  116. AUDIO_TTS_VOICE,
  117. AUDIO_TTS_AZURE_SPEECH_REGION,
  118. AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  119. WHISPER_MODEL,
  120. WHISPER_MODEL_AUTO_UPDATE,
  121. WHISPER_MODEL_DIR,
  122. # Retrieval
  123. RAG_TEMPLATE,
  124. DEFAULT_RAG_TEMPLATE,
  125. RAG_EMBEDDING_MODEL,
  126. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  127. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  128. RAG_RERANKING_MODEL,
  129. RAG_RERANKING_MODEL_AUTO_UPDATE,
  130. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  131. RAG_EMBEDDING_ENGINE,
  132. RAG_EMBEDDING_BATCH_SIZE,
  133. RAG_RELEVANCE_THRESHOLD,
  134. RAG_FILE_MAX_COUNT,
  135. RAG_FILE_MAX_SIZE,
  136. RAG_OPENAI_API_BASE_URL,
  137. RAG_OPENAI_API_KEY,
  138. RAG_OLLAMA_BASE_URL,
  139. RAG_OLLAMA_API_KEY,
  140. CHUNK_OVERLAP,
  141. CHUNK_SIZE,
  142. CONTENT_EXTRACTION_ENGINE,
  143. TIKA_SERVER_URL,
  144. RAG_TOP_K,
  145. RAG_TEXT_SPLITTER,
  146. TIKTOKEN_ENCODING_NAME,
  147. PDF_EXTRACT_IMAGES,
  148. YOUTUBE_LOADER_LANGUAGE,
  149. YOUTUBE_LOADER_PROXY_URL,
  150. # Retrieval (Web Search)
  151. RAG_WEB_SEARCH_ENGINE,
  152. RAG_WEB_SEARCH_RESULT_COUNT,
  153. RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  154. RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  155. JINA_API_KEY,
  156. SEARCHAPI_API_KEY,
  157. SEARCHAPI_ENGINE,
  158. SEARXNG_QUERY_URL,
  159. SERPER_API_KEY,
  160. SERPLY_API_KEY,
  161. SERPSTACK_API_KEY,
  162. SERPSTACK_HTTPS,
  163. TAVILY_API_KEY,
  164. BING_SEARCH_V7_ENDPOINT,
  165. BING_SEARCH_V7_SUBSCRIPTION_KEY,
  166. BRAVE_SEARCH_API_KEY,
  167. EXA_API_KEY,
  168. KAGI_SEARCH_API_KEY,
  169. MOJEEK_SEARCH_API_KEY,
  170. GOOGLE_PSE_API_KEY,
  171. GOOGLE_PSE_ENGINE_ID,
  172. GOOGLE_DRIVE_CLIENT_ID,
  173. GOOGLE_DRIVE_API_KEY,
  174. ENABLE_RAG_HYBRID_SEARCH,
  175. ENABLE_RAG_LOCAL_WEB_FETCH,
  176. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  177. ENABLE_RAG_WEB_SEARCH,
  178. ENABLE_GOOGLE_DRIVE_INTEGRATION,
  179. UPLOAD_DIR,
  180. # WebUI
  181. WEBUI_AUTH,
  182. WEBUI_NAME,
  183. WEBUI_BANNERS,
  184. WEBHOOK_URL,
  185. ADMIN_EMAIL,
  186. SHOW_ADMIN_DETAILS,
  187. JWT_EXPIRES_IN,
  188. ENABLE_SIGNUP,
  189. ENABLE_LOGIN_FORM,
  190. ENABLE_API_KEY,
  191. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  192. API_KEY_ALLOWED_ENDPOINTS,
  193. ENABLE_CHANNELS,
  194. ENABLE_COMMUNITY_SHARING,
  195. ENABLE_MESSAGE_RATING,
  196. ENABLE_EVALUATION_ARENA_MODELS,
  197. USER_PERMISSIONS,
  198. DEFAULT_USER_ROLE,
  199. DEFAULT_PROMPT_SUGGESTIONS,
  200. DEFAULT_MODELS,
  201. DEFAULT_ARENA_MODEL,
  202. MODEL_ORDER_LIST,
  203. EVALUATION_ARENA_MODELS,
  204. # WebUI (OAuth)
  205. ENABLE_OAUTH_ROLE_MANAGEMENT,
  206. OAUTH_ROLES_CLAIM,
  207. OAUTH_EMAIL_CLAIM,
  208. OAUTH_PICTURE_CLAIM,
  209. OAUTH_USERNAME_CLAIM,
  210. OAUTH_ALLOWED_ROLES,
  211. OAUTH_ADMIN_ROLES,
  212. # WebUI (LDAP)
  213. ENABLE_LDAP,
  214. LDAP_SERVER_LABEL,
  215. LDAP_SERVER_HOST,
  216. LDAP_SERVER_PORT,
  217. LDAP_ATTRIBUTE_FOR_MAIL,
  218. LDAP_ATTRIBUTE_FOR_USERNAME,
  219. LDAP_SEARCH_FILTERS,
  220. LDAP_SEARCH_BASE,
  221. LDAP_APP_DN,
  222. LDAP_APP_PASSWORD,
  223. LDAP_USE_TLS,
  224. LDAP_CA_CERT_FILE,
  225. LDAP_CIPHERS,
  226. # Misc
  227. ENV,
  228. CACHE_DIR,
  229. STATIC_DIR,
  230. FRONTEND_BUILD_DIR,
  231. CORS_ALLOW_ORIGIN,
  232. DEFAULT_LOCALE,
  233. OAUTH_PROVIDERS,
  234. WEBUI_URL,
  235. # Admin
  236. ENABLE_ADMIN_CHAT_ACCESS,
  237. ENABLE_ADMIN_EXPORT,
  238. # Tasks
  239. TASK_MODEL,
  240. TASK_MODEL_EXTERNAL,
  241. ENABLE_TAGS_GENERATION,
  242. ENABLE_SEARCH_QUERY_GENERATION,
  243. ENABLE_RETRIEVAL_QUERY_GENERATION,
  244. ENABLE_AUTOCOMPLETE_GENERATION,
  245. TITLE_GENERATION_PROMPT_TEMPLATE,
  246. TAGS_GENERATION_PROMPT_TEMPLATE,
  247. IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE,
  248. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  249. QUERY_GENERATION_PROMPT_TEMPLATE,
  250. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE,
  251. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH,
  252. AppConfig,
  253. reset_config,
  254. )
  255. from open_webui.env import (
  256. CHANGELOG,
  257. GLOBAL_LOG_LEVEL,
  258. SAFE_MODE,
  259. SRC_LOG_LEVELS,
  260. VERSION,
  261. WEBUI_BUILD_HASH,
  262. WEBUI_SECRET_KEY,
  263. WEBUI_SESSION_COOKIE_SAME_SITE,
  264. WEBUI_SESSION_COOKIE_SECURE,
  265. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  266. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  267. ENABLE_WEBSOCKET_SUPPORT,
  268. BYPASS_MODEL_ACCESS_CONTROL,
  269. RESET_CONFIG_ON_START,
  270. OFFLINE_MODE,
  271. )
  272. from open_webui.utils.models import (
  273. get_all_models,
  274. get_all_base_models,
  275. check_model_access,
  276. )
  277. from open_webui.utils.chat import (
  278. generate_chat_completion as chat_completion_handler,
  279. chat_completed as chat_completed_handler,
  280. chat_action as chat_action_handler,
  281. )
  282. from open_webui.utils.middleware import process_chat_payload, process_chat_response
  283. from open_webui.utils.access_control import has_access
  284. from open_webui.utils.auth import (
  285. decode_token,
  286. get_admin_user,
  287. get_verified_user,
  288. )
  289. from open_webui.utils.oauth import oauth_manager
  290. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  291. from open_webui.tasks import stop_task, list_tasks # Import from tasks.py
  292. if SAFE_MODE:
  293. print("SAFE MODE ENABLED")
  294. Functions.deactivate_all_functions()
  295. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  296. log = logging.getLogger(__name__)
  297. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  298. class SPAStaticFiles(StaticFiles):
  299. async def get_response(self, path: str, scope):
  300. try:
  301. return await super().get_response(path, scope)
  302. except (HTTPException, StarletteHTTPException) as ex:
  303. if ex.status_code == 404:
  304. return await super().get_response("index.html", scope)
  305. else:
  306. raise ex
  307. print(
  308. rf"""
  309. ___ __ __ _ _ _ ___
  310. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  311. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  312. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  313. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  314. |_|
  315. v{VERSION} - building the best open-source AI user interface.
  316. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  317. https://github.com/open-webui/open-webui
  318. """
  319. )
  320. @asynccontextmanager
  321. async def lifespan(app: FastAPI):
  322. if RESET_CONFIG_ON_START:
  323. reset_config()
  324. asyncio.create_task(periodic_usage_pool_cleanup())
  325. yield
  326. app = FastAPI(
  327. docs_url="/docs" if ENV == "dev" else None,
  328. openapi_url="/openapi.json" if ENV == "dev" else None,
  329. redoc_url=None,
  330. lifespan=lifespan,
  331. )
  332. app.state.config = AppConfig()
  333. ########################################
  334. #
  335. # OLLAMA
  336. #
  337. ########################################
  338. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  339. app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
  340. app.state.config.OLLAMA_API_CONFIGS = OLLAMA_API_CONFIGS
  341. app.state.OLLAMA_MODELS = {}
  342. ########################################
  343. #
  344. # OPENAI
  345. #
  346. ########################################
  347. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  348. app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
  349. app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
  350. app.state.config.OPENAI_API_CONFIGS = OPENAI_API_CONFIGS
  351. app.state.OPENAI_MODELS = {}
  352. ########################################
  353. #
  354. # WEBUI
  355. #
  356. ########################################
  357. app.state.config.WEBUI_URL = WEBUI_URL
  358. app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP
  359. app.state.config.ENABLE_LOGIN_FORM = ENABLE_LOGIN_FORM
  360. app.state.config.ENABLE_API_KEY = ENABLE_API_KEY
  361. app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  362. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  363. )
  364. app.state.config.API_KEY_ALLOWED_ENDPOINTS = API_KEY_ALLOWED_ENDPOINTS
  365. app.state.config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  366. app.state.config.SHOW_ADMIN_DETAILS = SHOW_ADMIN_DETAILS
  367. app.state.config.ADMIN_EMAIL = ADMIN_EMAIL
  368. app.state.config.DEFAULT_MODELS = DEFAULT_MODELS
  369. app.state.config.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
  370. app.state.config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  371. app.state.config.USER_PERMISSIONS = USER_PERMISSIONS
  372. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  373. app.state.config.BANNERS = WEBUI_BANNERS
  374. app.state.config.MODEL_ORDER_LIST = MODEL_ORDER_LIST
  375. app.state.config.ENABLE_CHANNELS = ENABLE_CHANNELS
  376. app.state.config.ENABLE_COMMUNITY_SHARING = ENABLE_COMMUNITY_SHARING
  377. app.state.config.ENABLE_MESSAGE_RATING = ENABLE_MESSAGE_RATING
  378. app.state.config.ENABLE_EVALUATION_ARENA_MODELS = ENABLE_EVALUATION_ARENA_MODELS
  379. app.state.config.EVALUATION_ARENA_MODELS = EVALUATION_ARENA_MODELS
  380. app.state.config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  381. app.state.config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  382. app.state.config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  383. app.state.config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  384. app.state.config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  385. app.state.config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  386. app.state.config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  387. app.state.config.ENABLE_LDAP = ENABLE_LDAP
  388. app.state.config.LDAP_SERVER_LABEL = LDAP_SERVER_LABEL
  389. app.state.config.LDAP_SERVER_HOST = LDAP_SERVER_HOST
  390. app.state.config.LDAP_SERVER_PORT = LDAP_SERVER_PORT
  391. app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = LDAP_ATTRIBUTE_FOR_MAIL
  392. app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = LDAP_ATTRIBUTE_FOR_USERNAME
  393. app.state.config.LDAP_APP_DN = LDAP_APP_DN
  394. app.state.config.LDAP_APP_PASSWORD = LDAP_APP_PASSWORD
  395. app.state.config.LDAP_SEARCH_BASE = LDAP_SEARCH_BASE
  396. app.state.config.LDAP_SEARCH_FILTERS = LDAP_SEARCH_FILTERS
  397. app.state.config.LDAP_USE_TLS = LDAP_USE_TLS
  398. app.state.config.LDAP_CA_CERT_FILE = LDAP_CA_CERT_FILE
  399. app.state.config.LDAP_CIPHERS = LDAP_CIPHERS
  400. app.state.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
  401. app.state.AUTH_TRUSTED_NAME_HEADER = WEBUI_AUTH_TRUSTED_NAME_HEADER
  402. app.state.TOOLS = {}
  403. app.state.FUNCTIONS = {}
  404. ########################################
  405. #
  406. # RETRIEVAL
  407. #
  408. ########################################
  409. app.state.config.TOP_K = RAG_TOP_K
  410. app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
  411. app.state.config.FILE_MAX_SIZE = RAG_FILE_MAX_SIZE
  412. app.state.config.FILE_MAX_COUNT = RAG_FILE_MAX_COUNT
  413. app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
  414. app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
  415. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
  416. )
  417. app.state.config.CONTENT_EXTRACTION_ENGINE = CONTENT_EXTRACTION_ENGINE
  418. app.state.config.TIKA_SERVER_URL = TIKA_SERVER_URL
  419. app.state.config.TEXT_SPLITTER = RAG_TEXT_SPLITTER
  420. app.state.config.TIKTOKEN_ENCODING_NAME = TIKTOKEN_ENCODING_NAME
  421. app.state.config.CHUNK_SIZE = CHUNK_SIZE
  422. app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
  423. app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
  424. app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  425. app.state.config.RAG_EMBEDDING_BATCH_SIZE = RAG_EMBEDDING_BATCH_SIZE
  426. app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
  427. app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
  428. app.state.config.RAG_OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
  429. app.state.config.RAG_OPENAI_API_KEY = RAG_OPENAI_API_KEY
  430. app.state.config.RAG_OLLAMA_BASE_URL = RAG_OLLAMA_BASE_URL
  431. app.state.config.RAG_OLLAMA_API_KEY = RAG_OLLAMA_API_KEY
  432. app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
  433. app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
  434. app.state.config.YOUTUBE_LOADER_PROXY_URL = YOUTUBE_LOADER_PROXY_URL
  435. app.state.config.ENABLE_RAG_WEB_SEARCH = ENABLE_RAG_WEB_SEARCH
  436. app.state.config.RAG_WEB_SEARCH_ENGINE = RAG_WEB_SEARCH_ENGINE
  437. app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST = RAG_WEB_SEARCH_DOMAIN_FILTER_LIST
  438. app.state.config.ENABLE_GOOGLE_DRIVE_INTEGRATION = ENABLE_GOOGLE_DRIVE_INTEGRATION
  439. app.state.config.SEARXNG_QUERY_URL = SEARXNG_QUERY_URL
  440. app.state.config.GOOGLE_PSE_API_KEY = GOOGLE_PSE_API_KEY
  441. app.state.config.GOOGLE_PSE_ENGINE_ID = GOOGLE_PSE_ENGINE_ID
  442. app.state.config.BRAVE_SEARCH_API_KEY = BRAVE_SEARCH_API_KEY
  443. app.state.config.KAGI_SEARCH_API_KEY = KAGI_SEARCH_API_KEY
  444. app.state.config.MOJEEK_SEARCH_API_KEY = MOJEEK_SEARCH_API_KEY
  445. app.state.config.SERPSTACK_API_KEY = SERPSTACK_API_KEY
  446. app.state.config.SERPSTACK_HTTPS = SERPSTACK_HTTPS
  447. app.state.config.SERPER_API_KEY = SERPER_API_KEY
  448. app.state.config.SERPLY_API_KEY = SERPLY_API_KEY
  449. app.state.config.TAVILY_API_KEY = TAVILY_API_KEY
  450. app.state.config.SEARCHAPI_API_KEY = SEARCHAPI_API_KEY
  451. app.state.config.SEARCHAPI_ENGINE = SEARCHAPI_ENGINE
  452. app.state.config.JINA_API_KEY = JINA_API_KEY
  453. app.state.config.BING_SEARCH_V7_ENDPOINT = BING_SEARCH_V7_ENDPOINT
  454. app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY = BING_SEARCH_V7_SUBSCRIPTION_KEY
  455. app.state.config.EXA_API_KEY = EXA_API_KEY
  456. app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = RAG_WEB_SEARCH_RESULT_COUNT
  457. app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = RAG_WEB_SEARCH_CONCURRENT_REQUESTS
  458. app.state.EMBEDDING_FUNCTION = None
  459. app.state.ef = None
  460. app.state.rf = None
  461. app.state.YOUTUBE_LOADER_TRANSLATION = None
  462. try:
  463. app.state.ef = get_ef(
  464. app.state.config.RAG_EMBEDDING_ENGINE,
  465. app.state.config.RAG_EMBEDDING_MODEL,
  466. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  467. )
  468. app.state.rf = get_rf(
  469. app.state.config.RAG_RERANKING_MODEL,
  470. RAG_RERANKING_MODEL_AUTO_UPDATE,
  471. )
  472. except Exception as e:
  473. log.error(f"Error updating models: {e}")
  474. pass
  475. app.state.EMBEDDING_FUNCTION = get_embedding_function(
  476. app.state.config.RAG_EMBEDDING_ENGINE,
  477. app.state.config.RAG_EMBEDDING_MODEL,
  478. app.state.ef,
  479. (
  480. app.state.config.RAG_OPENAI_API_BASE_URL
  481. if app.state.config.RAG_EMBEDDING_ENGINE == "openai"
  482. else app.state.config.RAG_OLLAMA_BASE_URL
  483. ),
  484. (
  485. app.state.config.RAG_OPENAI_API_KEY
  486. if app.state.config.RAG_EMBEDDING_ENGINE == "openai"
  487. else app.state.config.RAG_OLLAMA_API_KEY
  488. ),
  489. app.state.config.RAG_EMBEDDING_BATCH_SIZE,
  490. )
  491. ########################################
  492. #
  493. # IMAGES
  494. #
  495. ########################################
  496. app.state.config.IMAGE_GENERATION_ENGINE = IMAGE_GENERATION_ENGINE
  497. app.state.config.ENABLE_IMAGE_GENERATION = ENABLE_IMAGE_GENERATION
  498. app.state.config.ENABLE_IMAGE_PROMPT_GENERATION = ENABLE_IMAGE_PROMPT_GENERATION
  499. app.state.config.IMAGES_OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
  500. app.state.config.IMAGES_OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
  501. app.state.config.IMAGE_GENERATION_MODEL = IMAGE_GENERATION_MODEL
  502. app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
  503. app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
  504. app.state.config.AUTOMATIC1111_CFG_SCALE = AUTOMATIC1111_CFG_SCALE
  505. app.state.config.AUTOMATIC1111_SAMPLER = AUTOMATIC1111_SAMPLER
  506. app.state.config.AUTOMATIC1111_SCHEDULER = AUTOMATIC1111_SCHEDULER
  507. app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
  508. app.state.config.COMFYUI_API_KEY = COMFYUI_API_KEY
  509. app.state.config.COMFYUI_WORKFLOW = COMFYUI_WORKFLOW
  510. app.state.config.COMFYUI_WORKFLOW_NODES = COMFYUI_WORKFLOW_NODES
  511. app.state.config.IMAGE_SIZE = IMAGE_SIZE
  512. app.state.config.IMAGE_STEPS = IMAGE_STEPS
  513. ########################################
  514. #
  515. # AUDIO
  516. #
  517. ########################################
  518. app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
  519. app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
  520. app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
  521. app.state.config.STT_MODEL = AUDIO_STT_MODEL
  522. app.state.config.WHISPER_MODEL = WHISPER_MODEL
  523. app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
  524. app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
  525. app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
  526. app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
  527. app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
  528. app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
  529. app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
  530. app.state.config.TTS_AZURE_SPEECH_REGION = AUDIO_TTS_AZURE_SPEECH_REGION
  531. app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT
  532. app.state.faster_whisper_model = None
  533. app.state.speech_synthesiser = None
  534. app.state.speech_speaker_embeddings_dataset = None
  535. ########################################
  536. #
  537. # TASKS
  538. #
  539. ########################################
  540. app.state.config.TASK_MODEL = TASK_MODEL
  541. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  542. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  543. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  544. app.state.config.ENABLE_AUTOCOMPLETE_GENERATION = ENABLE_AUTOCOMPLETE_GENERATION
  545. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  546. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  547. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  548. app.state.config.IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE = (
  549. IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE
  550. )
  551. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  552. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  553. )
  554. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  555. app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = (
  556. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  557. )
  558. app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = (
  559. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH
  560. )
  561. ########################################
  562. #
  563. # WEBUI
  564. #
  565. ########################################
  566. app.state.MODELS = {}
  567. class RedirectMiddleware(BaseHTTPMiddleware):
  568. async def dispatch(self, request: Request, call_next):
  569. # Check if the request is a GET request
  570. if request.method == "GET":
  571. path = request.url.path
  572. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  573. # Check for the specific watch path and the presence of 'v' parameter
  574. if path.endswith("/watch") and "v" in query_params:
  575. video_id = query_params["v"][0] # Extract the first 'v' parameter
  576. encoded_video_id = urlencode({"youtube": video_id})
  577. redirect_url = f"/?{encoded_video_id}"
  578. return RedirectResponse(url=redirect_url)
  579. # Proceed with the normal flow of other requests
  580. response = await call_next(request)
  581. return response
  582. # Add the middleware to the app
  583. app.add_middleware(RedirectMiddleware)
  584. app.add_middleware(SecurityHeadersMiddleware)
  585. @app.middleware("http")
  586. async def commit_session_after_request(request: Request, call_next):
  587. response = await call_next(request)
  588. # log.debug("Commit session after request")
  589. Session.commit()
  590. return response
  591. @app.middleware("http")
  592. async def check_url(request: Request, call_next):
  593. start_time = int(time.time())
  594. request.state.enable_api_key = app.state.config.ENABLE_API_KEY
  595. response = await call_next(request)
  596. process_time = int(time.time()) - start_time
  597. response.headers["X-Process-Time"] = str(process_time)
  598. return response
  599. @app.middleware("http")
  600. async def inspect_websocket(request: Request, call_next):
  601. if (
  602. "/ws/socket.io" in request.url.path
  603. and request.query_params.get("transport") == "websocket"
  604. ):
  605. upgrade = (request.headers.get("Upgrade") or "").lower()
  606. connection = (request.headers.get("Connection") or "").lower().split(",")
  607. # Check that there's the correct headers for an upgrade, else reject the connection
  608. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  609. if upgrade != "websocket" or "upgrade" not in connection:
  610. return JSONResponse(
  611. status_code=status.HTTP_400_BAD_REQUEST,
  612. content={"detail": "Invalid WebSocket upgrade request"},
  613. )
  614. return await call_next(request)
  615. app.add_middleware(
  616. CORSMiddleware,
  617. allow_origins=CORS_ALLOW_ORIGIN,
  618. allow_credentials=True,
  619. allow_methods=["*"],
  620. allow_headers=["*"],
  621. )
  622. app.mount("/ws", socket_app)
  623. app.include_router(ollama.router, prefix="/ollama", tags=["ollama"])
  624. app.include_router(openai.router, prefix="/openai", tags=["openai"])
  625. app.include_router(pipelines.router, prefix="/api/v1/pipelines", tags=["pipelines"])
  626. app.include_router(tasks.router, prefix="/api/v1/tasks", tags=["tasks"])
  627. app.include_router(images.router, prefix="/api/v1/images", tags=["images"])
  628. app.include_router(audio.router, prefix="/api/v1/audio", tags=["audio"])
  629. app.include_router(retrieval.router, prefix="/api/v1/retrieval", tags=["retrieval"])
  630. app.include_router(configs.router, prefix="/api/v1/configs", tags=["configs"])
  631. app.include_router(auths.router, prefix="/api/v1/auths", tags=["auths"])
  632. app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
  633. app.include_router(channels.router, prefix="/api/v1/channels", tags=["channels"])
  634. app.include_router(chats.router, prefix="/api/v1/chats", tags=["chats"])
  635. app.include_router(models.router, prefix="/api/v1/models", tags=["models"])
  636. app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])
  637. app.include_router(prompts.router, prefix="/api/v1/prompts", tags=["prompts"])
  638. app.include_router(tools.router, prefix="/api/v1/tools", tags=["tools"])
  639. app.include_router(memories.router, prefix="/api/v1/memories", tags=["memories"])
  640. app.include_router(folders.router, prefix="/api/v1/folders", tags=["folders"])
  641. app.include_router(groups.router, prefix="/api/v1/groups", tags=["groups"])
  642. app.include_router(files.router, prefix="/api/v1/files", tags=["files"])
  643. app.include_router(functions.router, prefix="/api/v1/functions", tags=["functions"])
  644. app.include_router(
  645. evaluations.router, prefix="/api/v1/evaluations", tags=["evaluations"]
  646. )
  647. app.include_router(utils.router, prefix="/api/v1/utils", tags=["utils"])
  648. ##################################
  649. #
  650. # Chat Endpoints
  651. #
  652. ##################################
  653. @app.get("/api/models")
  654. async def get_models(request: Request, user=Depends(get_verified_user)):
  655. def get_filtered_models(models, user):
  656. filtered_models = []
  657. for model in models:
  658. if model.get("arena"):
  659. if has_access(
  660. user.id,
  661. type="read",
  662. access_control=model.get("info", {})
  663. .get("meta", {})
  664. .get("access_control", {}),
  665. ):
  666. filtered_models.append(model)
  667. continue
  668. model_info = Models.get_model_by_id(model["id"])
  669. if model_info:
  670. if user.id == model_info.user_id or has_access(
  671. user.id, type="read", access_control=model_info.access_control
  672. ):
  673. filtered_models.append(model)
  674. return filtered_models
  675. models = await get_all_models(request)
  676. # Filter out filter pipelines
  677. models = [
  678. model
  679. for model in models
  680. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  681. ]
  682. model_order_list = request.app.state.config.MODEL_ORDER_LIST
  683. if model_order_list:
  684. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  685. # Sort models by order list priority, with fallback for those not in the list
  686. models.sort(
  687. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  688. )
  689. # Filter out models that the user does not have access to
  690. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  691. models = get_filtered_models(models, user)
  692. log.debug(
  693. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  694. )
  695. return {"data": models}
  696. @app.get("/api/models/base")
  697. async def get_base_models(request: Request, user=Depends(get_admin_user)):
  698. models = await get_all_base_models(request)
  699. return {"data": models}
  700. @app.post("/api/chat/completions")
  701. async def chat_completion(
  702. request: Request,
  703. form_data: dict,
  704. user=Depends(get_verified_user),
  705. ):
  706. if not request.app.state.MODELS:
  707. await get_all_models(request)
  708. tasks = form_data.pop("background_tasks", None)
  709. try:
  710. model_id = form_data.get("model", None)
  711. if model_id not in request.app.state.MODELS:
  712. raise Exception("Model not found")
  713. model = request.app.state.MODELS[model_id]
  714. model_info = Models.get_model_by_id(model_id)
  715. # Check if user has access to the model
  716. if not BYPASS_MODEL_ACCESS_CONTROL and user.role == "user":
  717. try:
  718. check_model_access(user, model)
  719. except Exception as e:
  720. raise e
  721. metadata = {
  722. "user_id": user.id,
  723. "chat_id": form_data.pop("chat_id", None),
  724. "message_id": form_data.pop("id", None),
  725. "session_id": form_data.pop("session_id", None),
  726. "tool_ids": form_data.get("tool_ids", None),
  727. "files": form_data.get("files", None),
  728. "features": form_data.get("features", None),
  729. "variables": form_data.get("variables", None),
  730. "model": model_info,
  731. **(
  732. {"function_calling": "native"}
  733. if form_data.get("params", {}).get("function_calling") == "native"
  734. or (
  735. model_info
  736. and model_info.params.model_dump().get("function_calling")
  737. == "native"
  738. )
  739. else {}
  740. ),
  741. }
  742. form_data["metadata"] = metadata
  743. form_data, metadata, events = await process_chat_payload(
  744. request, form_data, metadata, user, model
  745. )
  746. except Exception as e:
  747. raise HTTPException(
  748. status_code=status.HTTP_400_BAD_REQUEST,
  749. detail=str(e),
  750. )
  751. try:
  752. response = await chat_completion_handler(request, form_data, user)
  753. return await process_chat_response(
  754. request, response, form_data, user, events, metadata, tasks
  755. )
  756. except Exception as e:
  757. raise HTTPException(
  758. status_code=status.HTTP_400_BAD_REQUEST,
  759. detail=str(e),
  760. )
  761. # Alias for chat_completion (Legacy)
  762. generate_chat_completions = chat_completion
  763. generate_chat_completion = chat_completion
  764. @app.post("/api/chat/completed")
  765. async def chat_completed(
  766. request: Request, form_data: dict, user=Depends(get_verified_user)
  767. ):
  768. try:
  769. return await chat_completed_handler(request, form_data, user)
  770. except Exception as e:
  771. raise HTTPException(
  772. status_code=status.HTTP_400_BAD_REQUEST,
  773. detail=str(e),
  774. )
  775. @app.post("/api/chat/actions/{action_id}")
  776. async def chat_action(
  777. request: Request, action_id: str, form_data: dict, user=Depends(get_verified_user)
  778. ):
  779. try:
  780. return await chat_action_handler(request, action_id, form_data, user)
  781. except Exception as e:
  782. raise HTTPException(
  783. status_code=status.HTTP_400_BAD_REQUEST,
  784. detail=str(e),
  785. )
  786. @app.post("/api/tasks/stop/{task_id}")
  787. async def stop_task_endpoint(task_id: str, user=Depends(get_verified_user)):
  788. try:
  789. result = await stop_task(task_id) # Use the function from tasks.py
  790. return result
  791. except ValueError as e:
  792. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
  793. @app.get("/api/tasks")
  794. async def list_tasks_endpoint(user=Depends(get_verified_user)):
  795. return {"tasks": list_tasks()} # Use the function from tasks.py
  796. ##################################
  797. #
  798. # Config Endpoints
  799. #
  800. ##################################
  801. @app.get("/api/config")
  802. async def get_app_config(request: Request):
  803. user = None
  804. if "token" in request.cookies:
  805. token = request.cookies.get("token")
  806. try:
  807. data = decode_token(token)
  808. except Exception as e:
  809. log.debug(e)
  810. raise HTTPException(
  811. status_code=status.HTTP_401_UNAUTHORIZED,
  812. detail="Invalid token",
  813. )
  814. if data is not None and "id" in data:
  815. user = Users.get_user_by_id(data["id"])
  816. onboarding = False
  817. if user is None:
  818. user_count = Users.get_num_users()
  819. onboarding = user_count == 0
  820. return {
  821. **({"onboarding": True} if onboarding else {}),
  822. "status": True,
  823. "name": WEBUI_NAME,
  824. "version": VERSION,
  825. "default_locale": str(DEFAULT_LOCALE),
  826. "oauth": {
  827. "providers": {
  828. name: config.get("name", name)
  829. for name, config in OAUTH_PROVIDERS.items()
  830. }
  831. },
  832. "features": {
  833. "auth": WEBUI_AUTH,
  834. "auth_trusted_header": bool(app.state.AUTH_TRUSTED_EMAIL_HEADER),
  835. "enable_ldap": app.state.config.ENABLE_LDAP,
  836. "enable_api_key": app.state.config.ENABLE_API_KEY,
  837. "enable_signup": app.state.config.ENABLE_SIGNUP,
  838. "enable_login_form": app.state.config.ENABLE_LOGIN_FORM,
  839. "enable_websocket": ENABLE_WEBSOCKET_SUPPORT,
  840. **(
  841. {
  842. "enable_channels": app.state.config.ENABLE_CHANNELS,
  843. "enable_web_search": app.state.config.ENABLE_RAG_WEB_SEARCH,
  844. "enable_google_drive_integration": app.state.config.ENABLE_GOOGLE_DRIVE_INTEGRATION,
  845. "enable_image_generation": app.state.config.ENABLE_IMAGE_GENERATION,
  846. "enable_community_sharing": app.state.config.ENABLE_COMMUNITY_SHARING,
  847. "enable_message_rating": app.state.config.ENABLE_MESSAGE_RATING,
  848. "enable_autocomplete_generation": app.state.config.ENABLE_AUTOCOMPLETE_GENERATION,
  849. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  850. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  851. }
  852. if user is not None
  853. else {}
  854. ),
  855. },
  856. **(
  857. {
  858. "default_models": app.state.config.DEFAULT_MODELS,
  859. "default_prompt_suggestions": app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  860. "audio": {
  861. "tts": {
  862. "engine": app.state.config.TTS_ENGINE,
  863. "voice": app.state.config.TTS_VOICE,
  864. "split_on": app.state.config.TTS_SPLIT_ON,
  865. },
  866. "stt": {
  867. "engine": app.state.config.STT_ENGINE,
  868. },
  869. },
  870. "file": {
  871. "max_size": app.state.config.FILE_MAX_SIZE,
  872. "max_count": app.state.config.FILE_MAX_COUNT,
  873. },
  874. "permissions": {**app.state.config.USER_PERMISSIONS},
  875. "google_drive": {
  876. "client_id": GOOGLE_DRIVE_CLIENT_ID.value,
  877. "api_key": GOOGLE_DRIVE_API_KEY.value,
  878. },
  879. }
  880. if user is not None
  881. else {}
  882. ),
  883. }
  884. class UrlForm(BaseModel):
  885. url: str
  886. @app.get("/api/webhook")
  887. async def get_webhook_url(user=Depends(get_admin_user)):
  888. return {
  889. "url": app.state.config.WEBHOOK_URL,
  890. }
  891. @app.post("/api/webhook")
  892. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  893. app.state.config.WEBHOOK_URL = form_data.url
  894. app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  895. return {"url": app.state.config.WEBHOOK_URL}
  896. @app.get("/api/version")
  897. async def get_app_version():
  898. return {
  899. "version": VERSION,
  900. }
  901. @app.get("/api/version/updates")
  902. async def get_app_latest_release_version(user=Depends(get_verified_user)):
  903. if OFFLINE_MODE:
  904. log.debug(
  905. f"Offline mode is enabled, returning current version as latest version"
  906. )
  907. return {"current": VERSION, "latest": VERSION}
  908. try:
  909. timeout = aiohttp.ClientTimeout(total=1)
  910. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  911. async with session.get(
  912. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  913. ) as response:
  914. response.raise_for_status()
  915. data = await response.json()
  916. latest_version = data["tag_name"]
  917. return {"current": VERSION, "latest": latest_version[1:]}
  918. except Exception as e:
  919. log.debug(e)
  920. return {"current": VERSION, "latest": VERSION}
  921. @app.get("/api/changelog")
  922. async def get_app_changelog():
  923. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  924. ############################
  925. # OAuth Login & Callback
  926. ############################
  927. # SessionMiddleware is used by authlib for oauth
  928. if len(OAUTH_PROVIDERS) > 0:
  929. app.add_middleware(
  930. SessionMiddleware,
  931. secret_key=WEBUI_SECRET_KEY,
  932. session_cookie="oui-session",
  933. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  934. https_only=WEBUI_SESSION_COOKIE_SECURE,
  935. )
  936. @app.get("/oauth/{provider}/login")
  937. async def oauth_login(provider: str, request: Request):
  938. return await oauth_manager.handle_login(provider, request)
  939. # OAuth login logic is as follows:
  940. # 1. Attempt to find a user with matching subject ID, tied to the provider
  941. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  942. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  943. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  944. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  945. @app.get("/oauth/{provider}/callback")
  946. async def oauth_callback(provider: str, request: Request, response: Response):
  947. return await oauth_manager.handle_callback(provider, request, response)
  948. @app.get("/manifest.json")
  949. async def get_manifest_json():
  950. return {
  951. "name": WEBUI_NAME,
  952. "short_name": WEBUI_NAME,
  953. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  954. "start_url": "/",
  955. "display": "standalone",
  956. "background_color": "#343541",
  957. "orientation": "natural",
  958. "icons": [
  959. {
  960. "src": "/static/logo.png",
  961. "type": "image/png",
  962. "sizes": "500x500",
  963. "purpose": "any",
  964. },
  965. {
  966. "src": "/static/logo.png",
  967. "type": "image/png",
  968. "sizes": "500x500",
  969. "purpose": "maskable",
  970. },
  971. ],
  972. }
  973. @app.get("/opensearch.xml")
  974. async def get_opensearch_xml():
  975. xml_content = rf"""
  976. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  977. <ShortName>{WEBUI_NAME}</ShortName>
  978. <Description>Search {WEBUI_NAME}</Description>
  979. <InputEncoding>UTF-8</InputEncoding>
  980. <Image width="16" height="16" type="image/x-icon">{app.state.config.WEBUI_URL}/static/favicon.png</Image>
  981. <Url type="text/html" method="get" template="{app.state.config.WEBUI_URL}/?q={"{searchTerms}"}"/>
  982. <moz:SearchForm>{app.state.config.WEBUI_URL}</moz:SearchForm>
  983. </OpenSearchDescription>
  984. """
  985. return Response(content=xml_content, media_type="application/xml")
  986. @app.get("/health")
  987. async def healthcheck():
  988. return {"status": True}
  989. @app.get("/health/db")
  990. async def healthcheck_with_db():
  991. Session.execute(text("SELECT 1;")).all()
  992. return {"status": True}
  993. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  994. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  995. def swagger_ui_html(*args, **kwargs):
  996. return get_swagger_ui_html(
  997. *args,
  998. **kwargs,
  999. swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
  1000. swagger_css_url="/static/swagger-ui/swagger-ui.css",
  1001. swagger_favicon_url="/static/swagger-ui/favicon.png",
  1002. )
  1003. applications.get_swagger_ui_html = swagger_ui_html
  1004. if os.path.exists(FRONTEND_BUILD_DIR):
  1005. mimetypes.add_type("text/javascript", ".js")
  1006. app.mount(
  1007. "/",
  1008. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1009. name="spa-static-files",
  1010. )
  1011. else:
  1012. log.warning(
  1013. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1014. )