main.py 38 KB

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