main.py 37 KB

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