main.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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. )
  29. from fastapi.middleware.cors import CORSMiddleware
  30. from fastapi.responses import JSONResponse, RedirectResponse
  31. from fastapi.staticfiles import StaticFiles
  32. from starlette.exceptions import HTTPException as StarletteHTTPException
  33. from starlette.middleware.base import BaseHTTPMiddleware
  34. from starlette.middleware.sessions import SessionMiddleware
  35. from starlette.responses import Response, StreamingResponse
  36. from open_webui.routers import (
  37. audio,
  38. chat,
  39. images,
  40. ollama,
  41. openai,
  42. retrieval,
  43. pipelines,
  44. tasks,
  45. auths,
  46. chats,
  47. folders,
  48. configs,
  49. groups,
  50. files,
  51. functions,
  52. memories,
  53. models,
  54. knowledge,
  55. prompts,
  56. evaluations,
  57. tools,
  58. users,
  59. utils,
  60. )
  61. from open_webui.retrieval.utils import get_sources_from_files
  62. from open_webui.socket.main import (
  63. app as socket_app,
  64. periodic_usage_pool_cleanup,
  65. get_event_call,
  66. get_event_emitter,
  67. )
  68. from open_webui.internal.db import Session
  69. from backend.open_webui.routers.webui import (
  70. app as webui_app,
  71. generate_function_chat_completion,
  72. get_all_models as get_open_webui_models,
  73. )
  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 backend.open_webui.utils.plugin import load_function_module_by_id
  78. from open_webui.constants import TASKS
  79. from open_webui.config import (
  80. # Ollama
  81. ENABLE_OLLAMA_API,
  82. OLLAMA_BASE_URLS,
  83. OLLAMA_API_CONFIGS,
  84. # OpenAI
  85. ENABLE_OPENAI_API,
  86. OPENAI_API_BASE_URLS,
  87. OPENAI_API_KEYS,
  88. OPENAI_API_CONFIGS,
  89. # Image
  90. AUTOMATIC1111_API_AUTH,
  91. AUTOMATIC1111_BASE_URL,
  92. AUTOMATIC1111_CFG_SCALE,
  93. AUTOMATIC1111_SAMPLER,
  94. AUTOMATIC1111_SCHEDULER,
  95. COMFYUI_BASE_URL,
  96. COMFYUI_WORKFLOW,
  97. COMFYUI_WORKFLOW_NODES,
  98. ENABLE_IMAGE_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. KAGI_SEARCH_API_KEY,
  168. MOJEEK_SEARCH_API_KEY,
  169. GOOGLE_PSE_API_KEY,
  170. GOOGLE_PSE_ENGINE_ID,
  171. ENABLE_RAG_HYBRID_SEARCH,
  172. ENABLE_RAG_LOCAL_WEB_FETCH,
  173. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  174. ENABLE_RAG_WEB_SEARCH,
  175. UPLOAD_DIR,
  176. # WebUI
  177. WEBUI_AUTH,
  178. WEBUI_NAME,
  179. WEBUI_BANNERS,
  180. WEBHOOK_URL,
  181. ADMIN_EMAIL,
  182. SHOW_ADMIN_DETAILS,
  183. JWT_EXPIRES_IN,
  184. ENABLE_SIGNUP,
  185. ENABLE_LOGIN_FORM,
  186. ENABLE_API_KEY,
  187. ENABLE_COMMUNITY_SHARING,
  188. ENABLE_MESSAGE_RATING,
  189. ENABLE_EVALUATION_ARENA_MODELS,
  190. USER_PERMISSIONS,
  191. DEFAULT_USER_ROLE,
  192. DEFAULT_PROMPT_SUGGESTIONS,
  193. DEFAULT_MODELS,
  194. DEFAULT_ARENA_MODEL,
  195. MODEL_ORDER_LIST,
  196. EVALUATION_ARENA_MODELS,
  197. # WebUI (OAuth)
  198. ENABLE_OAUTH_ROLE_MANAGEMENT,
  199. OAUTH_ROLES_CLAIM,
  200. OAUTH_EMAIL_CLAIM,
  201. OAUTH_PICTURE_CLAIM,
  202. OAUTH_USERNAME_CLAIM,
  203. OAUTH_ALLOWED_ROLES,
  204. OAUTH_ADMIN_ROLES,
  205. # WebUI (LDAP)
  206. ENABLE_LDAP,
  207. LDAP_SERVER_LABEL,
  208. LDAP_SERVER_HOST,
  209. LDAP_SERVER_PORT,
  210. LDAP_ATTRIBUTE_FOR_USERNAME,
  211. LDAP_SEARCH_FILTERS,
  212. LDAP_SEARCH_BASE,
  213. LDAP_APP_DN,
  214. LDAP_APP_PASSWORD,
  215. LDAP_USE_TLS,
  216. LDAP_CA_CERT_FILE,
  217. LDAP_CIPHERS,
  218. # Misc
  219. ENV,
  220. CACHE_DIR,
  221. STATIC_DIR,
  222. FRONTEND_BUILD_DIR,
  223. CORS_ALLOW_ORIGIN,
  224. DEFAULT_LOCALE,
  225. OAUTH_PROVIDERS,
  226. # Admin
  227. ENABLE_ADMIN_CHAT_ACCESS,
  228. ENABLE_ADMIN_EXPORT,
  229. # Tasks
  230. TASK_MODEL,
  231. TASK_MODEL_EXTERNAL,
  232. ENABLE_TAGS_GENERATION,
  233. ENABLE_SEARCH_QUERY_GENERATION,
  234. ENABLE_RETRIEVAL_QUERY_GENERATION,
  235. ENABLE_AUTOCOMPLETE_GENERATION,
  236. TITLE_GENERATION_PROMPT_TEMPLATE,
  237. TAGS_GENERATION_PROMPT_TEMPLATE,
  238. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  239. QUERY_GENERATION_PROMPT_TEMPLATE,
  240. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE,
  241. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH,
  242. AppConfig,
  243. reset_config,
  244. )
  245. from open_webui.env import (
  246. CHANGELOG,
  247. GLOBAL_LOG_LEVEL,
  248. SAFE_MODE,
  249. SRC_LOG_LEVELS,
  250. VERSION,
  251. WEBUI_URL,
  252. WEBUI_BUILD_HASH,
  253. WEBUI_SECRET_KEY,
  254. WEBUI_SESSION_COOKIE_SAME_SITE,
  255. WEBUI_SESSION_COOKIE_SECURE,
  256. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  257. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  258. BYPASS_MODEL_ACCESS_CONTROL,
  259. RESET_CONFIG_ON_START,
  260. OFFLINE_MODE,
  261. )
  262. from open_webui.utils.misc import (
  263. add_or_update_system_message,
  264. get_last_user_message,
  265. prepend_to_first_user_message_content,
  266. )
  267. from open_webui.utils.payload import convert_payload_openai_to_ollama
  268. from open_webui.utils.response import (
  269. convert_response_ollama_to_openai,
  270. convert_streaming_response_ollama_to_openai,
  271. )
  272. from open_webui.utils.task import (
  273. rag_template,
  274. tools_function_calling_generation_template,
  275. )
  276. from open_webui.utils.tools import get_tools
  277. from open_webui.utils.access_control import has_access
  278. from open_webui.utils.auth import (
  279. decode_token,
  280. get_admin_user,
  281. get_current_user,
  282. get_http_authorization_cred,
  283. get_verified_user,
  284. )
  285. from open_webui.utils.oauth import oauth_manager
  286. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  287. if SAFE_MODE:
  288. print("SAFE MODE ENABLED")
  289. Functions.deactivate_all_functions()
  290. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  291. log = logging.getLogger(__name__)
  292. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  293. class SPAStaticFiles(StaticFiles):
  294. async def get_response(self, path: str, scope):
  295. try:
  296. return await super().get_response(path, scope)
  297. except (HTTPException, StarletteHTTPException) as ex:
  298. if ex.status_code == 404:
  299. return await super().get_response("index.html", scope)
  300. else:
  301. raise ex
  302. print(
  303. rf"""
  304. ___ __ __ _ _ _ ___
  305. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  306. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  307. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  308. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  309. |_|
  310. v{VERSION} - building the best open-source AI user interface.
  311. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  312. https://github.com/open-webui/open-webui
  313. """
  314. )
  315. @asynccontextmanager
  316. async def lifespan(app: FastAPI):
  317. if RESET_CONFIG_ON_START:
  318. reset_config()
  319. asyncio.create_task(periodic_usage_pool_cleanup())
  320. yield
  321. app = FastAPI(
  322. docs_url="/docs" if ENV == "dev" else None,
  323. openapi_url="/openapi.json" if ENV == "dev" else None,
  324. redoc_url=None,
  325. lifespan=lifespan,
  326. )
  327. app.state.config = AppConfig()
  328. ########################################
  329. #
  330. # OLLAMA
  331. #
  332. ########################################
  333. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  334. app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
  335. app.state.config.OLLAMA_API_CONFIGS = OLLAMA_API_CONFIGS
  336. ########################################
  337. #
  338. # OPENAI
  339. #
  340. ########################################
  341. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  342. app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
  343. app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
  344. app.state.config.OPENAI_API_CONFIGS = OPENAI_API_CONFIGS
  345. ########################################
  346. #
  347. # WEBUI
  348. #
  349. ########################################
  350. app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP
  351. app.state.config.ENABLE_LOGIN_FORM = ENABLE_LOGIN_FORM
  352. app.state.config.ENABLE_API_KEY = ENABLE_API_KEY
  353. app.state.config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  354. app.state.config.SHOW_ADMIN_DETAILS = SHOW_ADMIN_DETAILS
  355. app.state.config.ADMIN_EMAIL = ADMIN_EMAIL
  356. app.state.config.DEFAULT_MODELS = DEFAULT_MODELS
  357. app.state.config.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
  358. app.state.config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  359. app.state.config.USER_PERMISSIONS = USER_PERMISSIONS
  360. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  361. app.state.config.BANNERS = WEBUI_BANNERS
  362. app.state.config.MODEL_ORDER_LIST = MODEL_ORDER_LIST
  363. app.state.config.ENABLE_COMMUNITY_SHARING = ENABLE_COMMUNITY_SHARING
  364. app.state.config.ENABLE_MESSAGE_RATING = ENABLE_MESSAGE_RATING
  365. app.state.config.ENABLE_EVALUATION_ARENA_MODELS = ENABLE_EVALUATION_ARENA_MODELS
  366. app.state.config.EVALUATION_ARENA_MODELS = EVALUATION_ARENA_MODELS
  367. app.state.config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  368. app.state.config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  369. app.state.config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  370. app.state.config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  371. app.state.config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  372. app.state.config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  373. app.state.config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  374. app.state.config.ENABLE_LDAP = ENABLE_LDAP
  375. app.state.config.LDAP_SERVER_LABEL = LDAP_SERVER_LABEL
  376. app.state.config.LDAP_SERVER_HOST = LDAP_SERVER_HOST
  377. app.state.config.LDAP_SERVER_PORT = LDAP_SERVER_PORT
  378. app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = LDAP_ATTRIBUTE_FOR_USERNAME
  379. app.state.config.LDAP_APP_DN = LDAP_APP_DN
  380. app.state.config.LDAP_APP_PASSWORD = LDAP_APP_PASSWORD
  381. app.state.config.LDAP_SEARCH_BASE = LDAP_SEARCH_BASE
  382. app.state.config.LDAP_SEARCH_FILTERS = LDAP_SEARCH_FILTERS
  383. app.state.config.LDAP_USE_TLS = LDAP_USE_TLS
  384. app.state.config.LDAP_CA_CERT_FILE = LDAP_CA_CERT_FILE
  385. app.state.config.LDAP_CIPHERS = LDAP_CIPHERS
  386. app.state.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
  387. app.state.AUTH_TRUSTED_NAME_HEADER = WEBUI_AUTH_TRUSTED_NAME_HEADER
  388. app.state.TOOLS = {}
  389. app.state.FUNCTIONS = {}
  390. ########################################
  391. #
  392. # RETRIEVAL
  393. #
  394. ########################################
  395. app.state.config.TOP_K = RAG_TOP_K
  396. app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
  397. app.state.config.FILE_MAX_SIZE = RAG_FILE_MAX_SIZE
  398. app.state.config.FILE_MAX_COUNT = RAG_FILE_MAX_COUNT
  399. app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
  400. app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
  401. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
  402. )
  403. app.state.config.CONTENT_EXTRACTION_ENGINE = CONTENT_EXTRACTION_ENGINE
  404. app.state.config.TIKA_SERVER_URL = TIKA_SERVER_URL
  405. app.state.config.TEXT_SPLITTER = RAG_TEXT_SPLITTER
  406. app.state.config.TIKTOKEN_ENCODING_NAME = TIKTOKEN_ENCODING_NAME
  407. app.state.config.CHUNK_SIZE = CHUNK_SIZE
  408. app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
  409. app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
  410. app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  411. app.state.config.RAG_EMBEDDING_BATCH_SIZE = RAG_EMBEDDING_BATCH_SIZE
  412. app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
  413. app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
  414. app.state.config.RAG_OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
  415. app.state.config.RAG_OPENAI_API_KEY = RAG_OPENAI_API_KEY
  416. app.state.config.RAG_OLLAMA_BASE_URL = RAG_OLLAMA_BASE_URL
  417. app.state.config.RAG_OLLAMA_API_KEY = RAG_OLLAMA_API_KEY
  418. app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
  419. app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
  420. app.state.config.YOUTUBE_LOADER_PROXY_URL = YOUTUBE_LOADER_PROXY_URL
  421. app.state.config.ENABLE_RAG_WEB_SEARCH = ENABLE_RAG_WEB_SEARCH
  422. app.state.config.RAG_WEB_SEARCH_ENGINE = RAG_WEB_SEARCH_ENGINE
  423. app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST = RAG_WEB_SEARCH_DOMAIN_FILTER_LIST
  424. app.state.config.SEARXNG_QUERY_URL = SEARXNG_QUERY_URL
  425. app.state.config.GOOGLE_PSE_API_KEY = GOOGLE_PSE_API_KEY
  426. app.state.config.GOOGLE_PSE_ENGINE_ID = GOOGLE_PSE_ENGINE_ID
  427. app.state.config.BRAVE_SEARCH_API_KEY = BRAVE_SEARCH_API_KEY
  428. app.state.config.KAGI_SEARCH_API_KEY = KAGI_SEARCH_API_KEY
  429. app.state.config.MOJEEK_SEARCH_API_KEY = MOJEEK_SEARCH_API_KEY
  430. app.state.config.SERPSTACK_API_KEY = SERPSTACK_API_KEY
  431. app.state.config.SERPSTACK_HTTPS = SERPSTACK_HTTPS
  432. app.state.config.SERPER_API_KEY = SERPER_API_KEY
  433. app.state.config.SERPLY_API_KEY = SERPLY_API_KEY
  434. app.state.config.TAVILY_API_KEY = TAVILY_API_KEY
  435. app.state.config.SEARCHAPI_API_KEY = SEARCHAPI_API_KEY
  436. app.state.config.SEARCHAPI_ENGINE = SEARCHAPI_ENGINE
  437. app.state.config.JINA_API_KEY = JINA_API_KEY
  438. app.state.config.BING_SEARCH_V7_ENDPOINT = BING_SEARCH_V7_ENDPOINT
  439. app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY = BING_SEARCH_V7_SUBSCRIPTION_KEY
  440. app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = RAG_WEB_SEARCH_RESULT_COUNT
  441. app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = RAG_WEB_SEARCH_CONCURRENT_REQUESTS
  442. app.state.YOUTUBE_LOADER_TRANSLATION = None
  443. app.state.EMBEDDING_FUNCTION = None
  444. ########################################
  445. #
  446. # IMAGES
  447. #
  448. ########################################
  449. app.state.config.IMAGE_GENERATION_ENGINE = IMAGE_GENERATION_ENGINE
  450. app.state.config.ENABLE_IMAGE_GENERATION = ENABLE_IMAGE_GENERATION
  451. app.state.config.IMAGES_OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
  452. app.state.config.IMAGES_OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
  453. app.state.config.IMAGE_GENERATION_MODEL = IMAGE_GENERATION_MODEL
  454. app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
  455. app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
  456. app.state.config.AUTOMATIC1111_CFG_SCALE = AUTOMATIC1111_CFG_SCALE
  457. app.state.config.AUTOMATIC1111_SAMPLER = AUTOMATIC1111_SAMPLER
  458. app.state.config.AUTOMATIC1111_SCHEDULER = AUTOMATIC1111_SCHEDULER
  459. app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
  460. app.state.config.COMFYUI_WORKFLOW = COMFYUI_WORKFLOW
  461. app.state.config.COMFYUI_WORKFLOW_NODES = COMFYUI_WORKFLOW_NODES
  462. app.state.config.IMAGE_SIZE = IMAGE_SIZE
  463. app.state.config.IMAGE_STEPS = IMAGE_STEPS
  464. ########################################
  465. #
  466. # AUDIO
  467. #
  468. ########################################
  469. app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
  470. app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
  471. app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
  472. app.state.config.STT_MODEL = AUDIO_STT_MODEL
  473. app.state.config.WHISPER_MODEL = WHISPER_MODEL
  474. app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
  475. app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
  476. app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
  477. app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
  478. app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
  479. app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
  480. app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
  481. app.state.config.TTS_AZURE_SPEECH_REGION = AUDIO_TTS_AZURE_SPEECH_REGION
  482. app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT
  483. app.state.faster_whisper_model = None
  484. app.state.speech_synthesiser = None
  485. app.state.speech_speaker_embeddings_dataset = None
  486. ########################################
  487. #
  488. # TASKS
  489. #
  490. ########################################
  491. app.state.config.TASK_MODEL = TASK_MODEL
  492. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  493. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  494. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  495. app.state.config.ENABLE_AUTOCOMPLETE_GENERATION = ENABLE_AUTOCOMPLETE_GENERATION
  496. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  497. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  498. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  499. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  500. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  501. )
  502. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  503. app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = (
  504. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  505. )
  506. app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = (
  507. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH
  508. )
  509. ##################################
  510. #
  511. # ChatCompletion Middleware
  512. #
  513. ##################################
  514. def get_filter_function_ids(model):
  515. def get_priority(function_id):
  516. function = Functions.get_function_by_id(function_id)
  517. if function is not None and hasattr(function, "valves"):
  518. # TODO: Fix FunctionModel
  519. return (function.valves if function.valves else {}).get("priority", 0)
  520. return 0
  521. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  522. if "info" in model and "meta" in model["info"]:
  523. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  524. filter_ids = list(set(filter_ids))
  525. enabled_filter_ids = [
  526. function.id
  527. for function in Functions.get_functions_by_type("filter", active_only=True)
  528. ]
  529. filter_ids = [
  530. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  531. ]
  532. filter_ids.sort(key=get_priority)
  533. return filter_ids
  534. async def chat_completion_filter_functions_handler(body, model, extra_params):
  535. skip_files = None
  536. filter_ids = get_filter_function_ids(model)
  537. for filter_id in filter_ids:
  538. filter = Functions.get_function_by_id(filter_id)
  539. if not filter:
  540. continue
  541. if filter_id in webui_app.state.FUNCTIONS:
  542. function_module = webui_app.state.FUNCTIONS[filter_id]
  543. else:
  544. function_module, _, _ = load_function_module_by_id(filter_id)
  545. webui_app.state.FUNCTIONS[filter_id] = function_module
  546. # Check if the function has a file_handler variable
  547. if hasattr(function_module, "file_handler"):
  548. skip_files = function_module.file_handler
  549. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  550. valves = Functions.get_function_valves_by_id(filter_id)
  551. function_module.valves = function_module.Valves(
  552. **(valves if valves else {})
  553. )
  554. if not hasattr(function_module, "inlet"):
  555. continue
  556. try:
  557. inlet = function_module.inlet
  558. # Get the signature of the function
  559. sig = inspect.signature(inlet)
  560. params = {"body": body} | {
  561. k: v
  562. for k, v in {
  563. **extra_params,
  564. "__model__": model,
  565. "__id__": filter_id,
  566. }.items()
  567. if k in sig.parameters
  568. }
  569. if "__user__" in params and hasattr(function_module, "UserValves"):
  570. try:
  571. params["__user__"]["valves"] = function_module.UserValves(
  572. **Functions.get_user_valves_by_id_and_user_id(
  573. filter_id, params["__user__"]["id"]
  574. )
  575. )
  576. except Exception as e:
  577. print(e)
  578. if inspect.iscoroutinefunction(inlet):
  579. body = await inlet(**params)
  580. else:
  581. body = inlet(**params)
  582. except Exception as e:
  583. print(f"Error: {e}")
  584. raise e
  585. if skip_files and "files" in body.get("metadata", {}):
  586. del body["metadata"]["files"]
  587. return body, {}
  588. def get_tools_function_calling_payload(messages, task_model_id, content):
  589. user_message = get_last_user_message(messages)
  590. history = "\n".join(
  591. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  592. for message in messages[::-1][:4]
  593. )
  594. prompt = f"History:\n{history}\nQuery: {user_message}"
  595. return {
  596. "model": task_model_id,
  597. "messages": [
  598. {"role": "system", "content": content},
  599. {"role": "user", "content": f"Query: {prompt}"},
  600. ],
  601. "stream": False,
  602. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  603. }
  604. async def get_content_from_response(response) -> Optional[str]:
  605. content = None
  606. if hasattr(response, "body_iterator"):
  607. async for chunk in response.body_iterator:
  608. data = json.loads(chunk.decode("utf-8"))
  609. content = data["choices"][0]["message"]["content"]
  610. # Cleanup any remaining background tasks if necessary
  611. if response.background is not None:
  612. await response.background()
  613. else:
  614. content = response["choices"][0]["message"]["content"]
  615. return content
  616. def get_task_model_id(
  617. default_model_id: str, task_model: str, task_model_external: str, models
  618. ) -> str:
  619. # Set the task model
  620. task_model_id = default_model_id
  621. # Check if the user has a custom task model and use that model
  622. if models[task_model_id]["owned_by"] == "ollama":
  623. if task_model and task_model in models:
  624. task_model_id = task_model
  625. else:
  626. if task_model_external and task_model_external in models:
  627. task_model_id = task_model_external
  628. return task_model_id
  629. async def chat_completion_tools_handler(
  630. body: dict, user: UserModel, models, extra_params: dict
  631. ) -> tuple[dict, dict]:
  632. # If tool_ids field is present, call the functions
  633. metadata = body.get("metadata", {})
  634. tool_ids = metadata.get("tool_ids", None)
  635. log.debug(f"{tool_ids=}")
  636. if not tool_ids:
  637. return body, {}
  638. skip_files = False
  639. sources = []
  640. task_model_id = get_task_model_id(
  641. body["model"],
  642. app.state.config.TASK_MODEL,
  643. app.state.config.TASK_MODEL_EXTERNAL,
  644. models,
  645. )
  646. tools = get_tools(
  647. webui_app,
  648. tool_ids,
  649. user,
  650. {
  651. **extra_params,
  652. "__model__": models[task_model_id],
  653. "__messages__": body["messages"],
  654. "__files__": metadata.get("files", []),
  655. },
  656. )
  657. log.info(f"{tools=}")
  658. specs = [tool["spec"] for tool in tools.values()]
  659. tools_specs = json.dumps(specs)
  660. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  661. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  662. else:
  663. template = """Available Tools: {{TOOLS}}\nReturn an empty string if no tools match the query. If a function tool matches, construct and return a JSON object in the format {\"name\": \"functionName\", \"parameters\": {\"requiredFunctionParamKey\": \"requiredFunctionParamValue\"}} using the appropriate tool and its parameters. Only return the object and limit the response to the JSON object without additional text."""
  664. tools_function_calling_prompt = tools_function_calling_generation_template(
  665. template, tools_specs
  666. )
  667. log.info(f"{tools_function_calling_prompt=}")
  668. payload = get_tools_function_calling_payload(
  669. body["messages"], task_model_id, tools_function_calling_prompt
  670. )
  671. try:
  672. payload = filter_pipeline(payload, user, models)
  673. except Exception as e:
  674. raise e
  675. try:
  676. response = await generate_chat_completions(form_data=payload, user=user)
  677. log.debug(f"{response=}")
  678. content = await get_content_from_response(response)
  679. log.debug(f"{content=}")
  680. if not content:
  681. return body, {}
  682. try:
  683. content = content[content.find("{") : content.rfind("}") + 1]
  684. if not content:
  685. raise Exception("No JSON object found in the response")
  686. result = json.loads(content)
  687. tool_function_name = result.get("name", None)
  688. if tool_function_name not in tools:
  689. return body, {}
  690. tool_function_params = result.get("parameters", {})
  691. try:
  692. required_params = (
  693. tools[tool_function_name]
  694. .get("spec", {})
  695. .get("parameters", {})
  696. .get("required", [])
  697. )
  698. tool_function = tools[tool_function_name]["callable"]
  699. tool_function_params = {
  700. k: v
  701. for k, v in tool_function_params.items()
  702. if k in required_params
  703. }
  704. tool_output = await tool_function(**tool_function_params)
  705. except Exception as e:
  706. tool_output = str(e)
  707. if isinstance(tool_output, str):
  708. if tools[tool_function_name]["citation"]:
  709. sources.append(
  710. {
  711. "source": {
  712. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  713. },
  714. "document": [tool_output],
  715. "metadata": [
  716. {
  717. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  718. }
  719. ],
  720. }
  721. )
  722. else:
  723. sources.append(
  724. {
  725. "source": {},
  726. "document": [tool_output],
  727. "metadata": [
  728. {
  729. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  730. }
  731. ],
  732. }
  733. )
  734. if tools[tool_function_name]["file_handler"]:
  735. skip_files = True
  736. except Exception as e:
  737. log.exception(f"Error: {e}")
  738. content = None
  739. except Exception as e:
  740. log.exception(f"Error: {e}")
  741. content = None
  742. log.debug(f"tool_contexts: {sources}")
  743. if skip_files and "files" in body.get("metadata", {}):
  744. del body["metadata"]["files"]
  745. return body, {"sources": sources}
  746. async def chat_completion_files_handler(
  747. body: dict, user: UserModel
  748. ) -> tuple[dict, dict[str, list]]:
  749. sources = []
  750. if files := body.get("metadata", {}).get("files", None):
  751. try:
  752. queries_response = await generate_queries(
  753. {
  754. "model": body["model"],
  755. "messages": body["messages"],
  756. "type": "retrieval",
  757. },
  758. user,
  759. )
  760. queries_response = queries_response["choices"][0]["message"]["content"]
  761. try:
  762. bracket_start = queries_response.find("{")
  763. bracket_end = queries_response.rfind("}") + 1
  764. if bracket_start == -1 or bracket_end == -1:
  765. raise Exception("No JSON object found in the response")
  766. queries_response = queries_response[bracket_start:bracket_end]
  767. queries_response = json.loads(queries_response)
  768. except Exception as e:
  769. queries_response = {"queries": [queries_response]}
  770. queries = queries_response.get("queries", [])
  771. except Exception as e:
  772. queries = []
  773. if len(queries) == 0:
  774. queries = [get_last_user_message(body["messages"])]
  775. sources = get_sources_from_files(
  776. files=files,
  777. queries=queries,
  778. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  779. k=retrieval_app.state.config.TOP_K,
  780. reranking_function=retrieval_app.state.sentence_transformer_rf,
  781. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  782. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  783. )
  784. log.debug(f"rag_contexts:sources: {sources}")
  785. return body, {"sources": sources}
  786. async def get_body_and_model_and_user(request, models):
  787. # Read the original request body
  788. body = await request.body()
  789. body_str = body.decode("utf-8")
  790. body = json.loads(body_str) if body_str else {}
  791. model_id = body["model"]
  792. if model_id not in models:
  793. raise Exception("Model not found")
  794. model = models[model_id]
  795. user = get_current_user(
  796. request,
  797. get_http_authorization_cred(request.headers.get("Authorization")),
  798. )
  799. return body, model, user
  800. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  801. async def dispatch(self, request: Request, call_next):
  802. if not request.method == "POST" and any(
  803. endpoint in request.url.path
  804. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  805. ):
  806. return await call_next(request)
  807. log.debug(f"request.url.path: {request.url.path}")
  808. model_list = await get_all_models()
  809. models = {model["id"]: model for model in model_list}
  810. try:
  811. body, model, user = await get_body_and_model_and_user(request, models)
  812. except Exception as e:
  813. return JSONResponse(
  814. status_code=status.HTTP_400_BAD_REQUEST,
  815. content={"detail": str(e)},
  816. )
  817. model_info = Models.get_model_by_id(model["id"])
  818. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  819. if model.get("arena"):
  820. if not has_access(
  821. user.id,
  822. type="read",
  823. access_control=model.get("info", {})
  824. .get("meta", {})
  825. .get("access_control", {}),
  826. ):
  827. raise HTTPException(
  828. status_code=403,
  829. detail="Model not found",
  830. )
  831. else:
  832. if not model_info:
  833. return JSONResponse(
  834. status_code=status.HTTP_404_NOT_FOUND,
  835. content={"detail": "Model not found"},
  836. )
  837. elif not (
  838. user.id == model_info.user_id
  839. or has_access(
  840. user.id, type="read", access_control=model_info.access_control
  841. )
  842. ):
  843. return JSONResponse(
  844. status_code=status.HTTP_403_FORBIDDEN,
  845. content={"detail": "User does not have access to the model"},
  846. )
  847. metadata = {
  848. "chat_id": body.pop("chat_id", None),
  849. "message_id": body.pop("id", None),
  850. "session_id": body.pop("session_id", None),
  851. "tool_ids": body.get("tool_ids", None),
  852. "files": body.get("files", None),
  853. }
  854. body["metadata"] = metadata
  855. extra_params = {
  856. "__event_emitter__": get_event_emitter(metadata),
  857. "__event_call__": get_event_call(metadata),
  858. "__user__": {
  859. "id": user.id,
  860. "email": user.email,
  861. "name": user.name,
  862. "role": user.role,
  863. },
  864. "__metadata__": metadata,
  865. }
  866. # Initialize data_items to store additional data to be sent to the client
  867. # Initialize contexts and citation
  868. data_items = []
  869. sources = []
  870. try:
  871. body, flags = await chat_completion_filter_functions_handler(
  872. body, model, extra_params
  873. )
  874. except Exception as e:
  875. return JSONResponse(
  876. status_code=status.HTTP_400_BAD_REQUEST,
  877. content={"detail": str(e)},
  878. )
  879. tool_ids = body.pop("tool_ids", None)
  880. files = body.pop("files", None)
  881. metadata = {
  882. **metadata,
  883. "tool_ids": tool_ids,
  884. "files": files,
  885. }
  886. body["metadata"] = metadata
  887. try:
  888. body, flags = await chat_completion_tools_handler(
  889. body, user, models, extra_params
  890. )
  891. sources.extend(flags.get("sources", []))
  892. except Exception as e:
  893. log.exception(e)
  894. try:
  895. body, flags = await chat_completion_files_handler(body, user)
  896. sources.extend(flags.get("sources", []))
  897. except Exception as e:
  898. log.exception(e)
  899. # If context is not empty, insert it into the messages
  900. if len(sources) > 0:
  901. context_string = ""
  902. for source_idx, source in enumerate(sources):
  903. source_id = source.get("source", {}).get("name", "")
  904. if "document" in source:
  905. for doc_idx, doc_context in enumerate(source["document"]):
  906. metadata = source.get("metadata")
  907. doc_source_id = None
  908. if metadata:
  909. doc_source_id = metadata[doc_idx].get("source", source_id)
  910. if source_id:
  911. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  912. else:
  913. # If there is no source_id, then do not include the source_id tag
  914. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  915. context_string = context_string.strip()
  916. prompt = get_last_user_message(body["messages"])
  917. if prompt is None:
  918. raise Exception("No user message found")
  919. if (
  920. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  921. and context_string.strip() == ""
  922. ):
  923. log.debug(
  924. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  925. )
  926. # Workaround for Ollama 2.0+ system prompt issue
  927. # TODO: replace with add_or_update_system_message
  928. if model["owned_by"] == "ollama":
  929. body["messages"] = prepend_to_first_user_message_content(
  930. rag_template(
  931. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  932. ),
  933. body["messages"],
  934. )
  935. else:
  936. body["messages"] = add_or_update_system_message(
  937. rag_template(
  938. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  939. ),
  940. body["messages"],
  941. )
  942. # If there are citations, add them to the data_items
  943. sources = [
  944. source for source in sources if source.get("source", {}).get("name", "")
  945. ]
  946. if len(sources) > 0:
  947. data_items.append({"sources": sources})
  948. modified_body_bytes = json.dumps(body).encode("utf-8")
  949. # Replace the request body with the modified one
  950. request._body = modified_body_bytes
  951. # Set custom header to ensure content-length matches new body length
  952. request.headers.__dict__["_list"] = [
  953. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  954. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  955. ]
  956. response = await call_next(request)
  957. if not isinstance(response, StreamingResponse):
  958. return response
  959. content_type = response.headers["Content-Type"]
  960. is_openai = "text/event-stream" in content_type
  961. is_ollama = "application/x-ndjson" in content_type
  962. if not is_openai and not is_ollama:
  963. return response
  964. def wrap_item(item):
  965. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  966. async def stream_wrapper(original_generator, data_items):
  967. for item in data_items:
  968. yield wrap_item(json.dumps(item))
  969. async for data in original_generator:
  970. yield data
  971. return StreamingResponse(
  972. stream_wrapper(response.body_iterator, data_items),
  973. headers=dict(response.headers),
  974. )
  975. async def _receive(self, body: bytes):
  976. return {"type": "http.request", "body": body, "more_body": False}
  977. app.add_middleware(ChatCompletionMiddleware)
  978. ##################################
  979. #
  980. # Pipeline Middleware
  981. #
  982. ##################################
  983. def get_sorted_filters(model_id, models):
  984. filters = [
  985. model
  986. for model in models.values()
  987. if "pipeline" in model
  988. and "type" in model["pipeline"]
  989. and model["pipeline"]["type"] == "filter"
  990. and (
  991. model["pipeline"]["pipelines"] == ["*"]
  992. or any(
  993. model_id == target_model_id
  994. for target_model_id in model["pipeline"]["pipelines"]
  995. )
  996. )
  997. ]
  998. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  999. return sorted_filters
  1000. def filter_pipeline(payload, user, models):
  1001. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  1002. model_id = payload["model"]
  1003. sorted_filters = get_sorted_filters(model_id, models)
  1004. model = models[model_id]
  1005. if "pipeline" in model:
  1006. sorted_filters.append(model)
  1007. for filter in sorted_filters:
  1008. r = None
  1009. try:
  1010. urlIdx = filter["urlIdx"]
  1011. url = app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1012. key = app.state.config.OPENAI_API_KEYS[urlIdx]
  1013. if key == "":
  1014. continue
  1015. headers = {"Authorization": f"Bearer {key}"}
  1016. r = requests.post(
  1017. f"{url}/{filter['id']}/filter/inlet",
  1018. headers=headers,
  1019. json={
  1020. "user": user,
  1021. "body": payload,
  1022. },
  1023. )
  1024. r.raise_for_status()
  1025. payload = r.json()
  1026. except Exception as e:
  1027. # Handle connection error here
  1028. print(f"Connection error: {e}")
  1029. if r is not None:
  1030. res = r.json()
  1031. if "detail" in res:
  1032. raise Exception(r.status_code, res["detail"])
  1033. return payload
  1034. class PipelineMiddleware(BaseHTTPMiddleware):
  1035. async def dispatch(self, request: Request, call_next):
  1036. if not request.method == "POST" and any(
  1037. endpoint in request.url.path
  1038. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  1039. ):
  1040. return await call_next(request)
  1041. log.debug(f"request.url.path: {request.url.path}")
  1042. # Read the original request body
  1043. body = await request.body()
  1044. # Decode body to string
  1045. body_str = body.decode("utf-8")
  1046. # Parse string to JSON
  1047. data = json.loads(body_str) if body_str else {}
  1048. try:
  1049. user = get_current_user(
  1050. request,
  1051. get_http_authorization_cred(request.headers["Authorization"]),
  1052. )
  1053. except KeyError as e:
  1054. if len(e.args) > 1:
  1055. return JSONResponse(
  1056. status_code=e.args[0],
  1057. content={"detail": e.args[1]},
  1058. )
  1059. else:
  1060. return JSONResponse(
  1061. status_code=status.HTTP_401_UNAUTHORIZED,
  1062. content={"detail": "Not authenticated"},
  1063. )
  1064. except HTTPException as e:
  1065. return JSONResponse(
  1066. status_code=e.status_code,
  1067. content={"detail": e.detail},
  1068. )
  1069. model_list = await get_all_models()
  1070. models = {model["id"]: model for model in model_list}
  1071. try:
  1072. data = filter_pipeline(data, user, models)
  1073. except Exception as e:
  1074. if len(e.args) > 1:
  1075. return JSONResponse(
  1076. status_code=e.args[0],
  1077. content={"detail": e.args[1]},
  1078. )
  1079. else:
  1080. return JSONResponse(
  1081. status_code=status.HTTP_400_BAD_REQUEST,
  1082. content={"detail": str(e)},
  1083. )
  1084. modified_body_bytes = json.dumps(data).encode("utf-8")
  1085. # Replace the request body with the modified one
  1086. request._body = modified_body_bytes
  1087. # Set custom header to ensure content-length matches new body length
  1088. request.headers.__dict__["_list"] = [
  1089. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  1090. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  1091. ]
  1092. response = await call_next(request)
  1093. return response
  1094. async def _receive(self, body: bytes):
  1095. return {"type": "http.request", "body": body, "more_body": False}
  1096. app.add_middleware(PipelineMiddleware)
  1097. class RedirectMiddleware(BaseHTTPMiddleware):
  1098. async def dispatch(self, request: Request, call_next):
  1099. # Check if the request is a GET request
  1100. if request.method == "GET":
  1101. path = request.url.path
  1102. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  1103. # Check for the specific watch path and the presence of 'v' parameter
  1104. if path.endswith("/watch") and "v" in query_params:
  1105. video_id = query_params["v"][0] # Extract the first 'v' parameter
  1106. encoded_video_id = urlencode({"youtube": video_id})
  1107. redirect_url = f"/?{encoded_video_id}"
  1108. return RedirectResponse(url=redirect_url)
  1109. # Proceed with the normal flow of other requests
  1110. response = await call_next(request)
  1111. return response
  1112. # Add the middleware to the app
  1113. app.add_middleware(RedirectMiddleware)
  1114. app.add_middleware(SecurityHeadersMiddleware)
  1115. @app.middleware("http")
  1116. async def commit_session_after_request(request: Request, call_next):
  1117. response = await call_next(request)
  1118. # log.debug("Commit session after request")
  1119. Session.commit()
  1120. return response
  1121. @app.middleware("http")
  1122. async def check_url(request: Request, call_next):
  1123. start_time = int(time.time())
  1124. request.state.enable_api_key = webui_app.state.config.ENABLE_API_KEY
  1125. response = await call_next(request)
  1126. process_time = int(time.time()) - start_time
  1127. response.headers["X-Process-Time"] = str(process_time)
  1128. return response
  1129. @app.middleware("http")
  1130. async def inspect_websocket(request: Request, call_next):
  1131. if (
  1132. "/ws/socket.io" in request.url.path
  1133. and request.query_params.get("transport") == "websocket"
  1134. ):
  1135. upgrade = (request.headers.get("Upgrade") or "").lower()
  1136. connection = (request.headers.get("Connection") or "").lower().split(",")
  1137. # Check that there's the correct headers for an upgrade, else reject the connection
  1138. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  1139. if upgrade != "websocket" or "upgrade" not in connection:
  1140. return JSONResponse(
  1141. status_code=status.HTTP_400_BAD_REQUEST,
  1142. content={"detail": "Invalid WebSocket upgrade request"},
  1143. )
  1144. return await call_next(request)
  1145. app.add_middleware(
  1146. CORSMiddleware,
  1147. allow_origins=CORS_ALLOW_ORIGIN,
  1148. allow_credentials=True,
  1149. allow_methods=["*"],
  1150. allow_headers=["*"],
  1151. )
  1152. app.mount("/ws", socket_app)
  1153. app.include_router(ollama.router, prefix="/ollama")
  1154. app.include_router(openai.router, prefix="/openai")
  1155. app.include_router(images.router, prefix="/api/v1/images")
  1156. app.include_router(audio.router, prefix="/api/v1/audio")
  1157. app.include_router(retrieval.router, prefix="/api/v1/retrieval")
  1158. app.include_router(configs.router, prefix="/api/v1/configs", tags=["configs"])
  1159. app.include_router(auths.router, prefix="/api/v1/auths", tags=["auths"])
  1160. app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
  1161. app.include_router(chats.router, prefix="/api/v1/chats", tags=["chats"])
  1162. app.include_router(models.router, prefix="/api/v1/models", tags=["models"])
  1163. app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])
  1164. app.include_router(prompts.router, prefix="/api/v1/prompts", tags=["prompts"])
  1165. app.include_router(tools.router, prefix="/api/v1/tools", tags=["tools"])
  1166. app.include_router(memories.router, prefix="/api/v1/memories", tags=["memories"])
  1167. app.include_router(folders.router, prefix="/api/v1/folders", tags=["folders"])
  1168. app.include_router(groups.router, prefix="/api/v1/groups", tags=["groups"])
  1169. app.include_router(files.router, prefix="/api/v1/files", tags=["files"])
  1170. app.include_router(functions.router, prefix="/api/v1/functions", tags=["functions"])
  1171. app.include_router(
  1172. evaluations.router, prefix="/api/v1/evaluations", tags=["evaluations"]
  1173. )
  1174. app.include_router(utils.router, prefix="/api/v1/utils", tags=["utils"])
  1175. async def get_all_base_models():
  1176. open_webui_models = []
  1177. openai_models = []
  1178. ollama_models = []
  1179. if app.state.config.ENABLE_OPENAI_API:
  1180. openai_models = await openai.get_all_models()
  1181. openai_models = openai_models["data"]
  1182. if app.state.config.ENABLE_OLLAMA_API:
  1183. ollama_models = await get_ollama_models()
  1184. ollama_models = [
  1185. {
  1186. "id": model["model"],
  1187. "name": model["name"],
  1188. "object": "model",
  1189. "created": int(time.time()),
  1190. "owned_by": "ollama",
  1191. "ollama": model,
  1192. }
  1193. for model in ollama_models["models"]
  1194. ]
  1195. open_webui_models = await get_open_webui_models()
  1196. models = open_webui_models + openai_models + ollama_models
  1197. return models
  1198. @cached(ttl=3)
  1199. async def get_all_models():
  1200. models = await get_all_base_models()
  1201. # If there are no models, return an empty list
  1202. if len([model for model in models if not model.get("arena", False)]) == 0:
  1203. return []
  1204. global_action_ids = [
  1205. function.id for function in Functions.get_global_action_functions()
  1206. ]
  1207. enabled_action_ids = [
  1208. function.id
  1209. for function in Functions.get_functions_by_type("action", active_only=True)
  1210. ]
  1211. custom_models = Models.get_all_models()
  1212. for custom_model in custom_models:
  1213. if custom_model.base_model_id is None:
  1214. for model in models:
  1215. if (
  1216. custom_model.id == model["id"]
  1217. or custom_model.id == model["id"].split(":")[0]
  1218. ):
  1219. if custom_model.is_active:
  1220. model["name"] = custom_model.name
  1221. model["info"] = custom_model.model_dump()
  1222. action_ids = []
  1223. if "info" in model and "meta" in model["info"]:
  1224. action_ids.extend(
  1225. model["info"]["meta"].get("actionIds", [])
  1226. )
  1227. model["action_ids"] = action_ids
  1228. else:
  1229. models.remove(model)
  1230. elif custom_model.is_active and (
  1231. custom_model.id not in [model["id"] for model in models]
  1232. ):
  1233. owned_by = "openai"
  1234. pipe = None
  1235. action_ids = []
  1236. for model in models:
  1237. if (
  1238. custom_model.base_model_id == model["id"]
  1239. or custom_model.base_model_id == model["id"].split(":")[0]
  1240. ):
  1241. owned_by = model["owned_by"]
  1242. if "pipe" in model:
  1243. pipe = model["pipe"]
  1244. break
  1245. if custom_model.meta:
  1246. meta = custom_model.meta.model_dump()
  1247. if "actionIds" in meta:
  1248. action_ids.extend(meta["actionIds"])
  1249. models.append(
  1250. {
  1251. "id": f"{custom_model.id}",
  1252. "name": custom_model.name,
  1253. "object": "model",
  1254. "created": custom_model.created_at,
  1255. "owned_by": owned_by,
  1256. "info": custom_model.model_dump(),
  1257. "preset": True,
  1258. **({"pipe": pipe} if pipe is not None else {}),
  1259. "action_ids": action_ids,
  1260. }
  1261. )
  1262. # Process action_ids to get the actions
  1263. def get_action_items_from_module(function, module):
  1264. actions = []
  1265. if hasattr(module, "actions"):
  1266. actions = module.actions
  1267. return [
  1268. {
  1269. "id": f"{function.id}.{action['id']}",
  1270. "name": action.get("name", f"{function.name} ({action['id']})"),
  1271. "description": function.meta.description,
  1272. "icon_url": action.get(
  1273. "icon_url", function.meta.manifest.get("icon_url", None)
  1274. ),
  1275. }
  1276. for action in actions
  1277. ]
  1278. else:
  1279. return [
  1280. {
  1281. "id": function.id,
  1282. "name": function.name,
  1283. "description": function.meta.description,
  1284. "icon_url": function.meta.manifest.get("icon_url", None),
  1285. }
  1286. ]
  1287. def get_function_module_by_id(function_id):
  1288. if function_id in webui_app.state.FUNCTIONS:
  1289. function_module = webui_app.state.FUNCTIONS[function_id]
  1290. else:
  1291. function_module, _, _ = load_function_module_by_id(function_id)
  1292. webui_app.state.FUNCTIONS[function_id] = function_module
  1293. for model in models:
  1294. action_ids = [
  1295. action_id
  1296. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  1297. if action_id in enabled_action_ids
  1298. ]
  1299. model["actions"] = []
  1300. for action_id in action_ids:
  1301. action_function = Functions.get_function_by_id(action_id)
  1302. if action_function is None:
  1303. raise Exception(f"Action not found: {action_id}")
  1304. function_module = get_function_module_by_id(action_id)
  1305. model["actions"].extend(
  1306. get_action_items_from_module(action_function, function_module)
  1307. )
  1308. log.debug(f"get_all_models() returned {len(models)} models")
  1309. return models
  1310. @app.get("/api/models")
  1311. async def get_models(user=Depends(get_verified_user)):
  1312. models = await get_all_models()
  1313. # Filter out filter pipelines
  1314. models = [
  1315. model
  1316. for model in models
  1317. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  1318. ]
  1319. model_order_list = webui_app.state.config.MODEL_ORDER_LIST
  1320. if model_order_list:
  1321. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  1322. # Sort models by order list priority, with fallback for those not in the list
  1323. models.sort(
  1324. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  1325. )
  1326. # Filter out models that the user does not have access to
  1327. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  1328. filtered_models = []
  1329. for model in models:
  1330. if model.get("arena"):
  1331. if has_access(
  1332. user.id,
  1333. type="read",
  1334. access_control=model.get("info", {})
  1335. .get("meta", {})
  1336. .get("access_control", {}),
  1337. ):
  1338. filtered_models.append(model)
  1339. continue
  1340. model_info = Models.get_model_by_id(model["id"])
  1341. if model_info:
  1342. if user.id == model_info.user_id or has_access(
  1343. user.id, type="read", access_control=model_info.access_control
  1344. ):
  1345. filtered_models.append(model)
  1346. models = filtered_models
  1347. log.debug(
  1348. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  1349. )
  1350. return {"data": models}
  1351. @app.get("/api/models/base")
  1352. async def get_base_models(user=Depends(get_admin_user)):
  1353. models = await get_all_base_models()
  1354. # Filter out arena models
  1355. models = [model for model in models if not model.get("arena", False)]
  1356. return {"data": models}
  1357. ##################################
  1358. #
  1359. # Config Endpoints
  1360. #
  1361. ##################################
  1362. @app.get("/api/config")
  1363. async def get_app_config(request: Request):
  1364. user = None
  1365. if "token" in request.cookies:
  1366. token = request.cookies.get("token")
  1367. try:
  1368. data = decode_token(token)
  1369. except Exception as e:
  1370. log.debug(e)
  1371. raise HTTPException(
  1372. status_code=status.HTTP_401_UNAUTHORIZED,
  1373. detail="Invalid token",
  1374. )
  1375. if data is not None and "id" in data:
  1376. user = Users.get_user_by_id(data["id"])
  1377. onboarding = False
  1378. if user is None:
  1379. user_count = Users.get_num_users()
  1380. onboarding = user_count == 0
  1381. return {
  1382. **({"onboarding": True} if onboarding else {}),
  1383. "status": True,
  1384. "name": WEBUI_NAME,
  1385. "version": VERSION,
  1386. "default_locale": str(DEFAULT_LOCALE),
  1387. "oauth": {
  1388. "providers": {
  1389. name: config.get("name", name)
  1390. for name, config in OAUTH_PROVIDERS.items()
  1391. }
  1392. },
  1393. "features": {
  1394. "auth": WEBUI_AUTH,
  1395. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1396. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  1397. "enable_api_key": webui_app.state.config.ENABLE_API_KEY,
  1398. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1399. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1400. **(
  1401. {
  1402. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1403. "enable_image_generation": images_app.state.config.ENABLED,
  1404. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1405. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1406. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1407. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1408. }
  1409. if user is not None
  1410. else {}
  1411. ),
  1412. },
  1413. **(
  1414. {
  1415. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1416. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1417. "audio": {
  1418. "tts": {
  1419. "engine": audio_app.state.config.TTS_ENGINE,
  1420. "voice": audio_app.state.config.TTS_VOICE,
  1421. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  1422. },
  1423. "stt": {
  1424. "engine": audio_app.state.config.STT_ENGINE,
  1425. },
  1426. },
  1427. "file": {
  1428. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  1429. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  1430. },
  1431. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  1432. }
  1433. if user is not None
  1434. else {}
  1435. ),
  1436. }
  1437. class UrlForm(BaseModel):
  1438. url: str
  1439. @app.get("/api/webhook")
  1440. async def get_webhook_url(user=Depends(get_admin_user)):
  1441. return {
  1442. "url": app.state.config.WEBHOOK_URL,
  1443. }
  1444. @app.post("/api/webhook")
  1445. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1446. app.state.config.WEBHOOK_URL = form_data.url
  1447. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1448. return {"url": app.state.config.WEBHOOK_URL}
  1449. @app.get("/api/version")
  1450. async def get_app_version():
  1451. return {
  1452. "version": VERSION,
  1453. }
  1454. @app.get("/api/version/updates")
  1455. async def get_app_latest_release_version():
  1456. if OFFLINE_MODE:
  1457. log.debug(
  1458. f"Offline mode is enabled, returning current version as latest version"
  1459. )
  1460. return {"current": VERSION, "latest": VERSION}
  1461. try:
  1462. timeout = aiohttp.ClientTimeout(total=1)
  1463. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  1464. async with session.get(
  1465. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1466. ) as response:
  1467. response.raise_for_status()
  1468. data = await response.json()
  1469. latest_version = data["tag_name"]
  1470. return {"current": VERSION, "latest": latest_version[1:]}
  1471. except Exception as e:
  1472. log.debug(e)
  1473. return {"current": VERSION, "latest": VERSION}
  1474. @app.get("/api/changelog")
  1475. async def get_app_changelog():
  1476. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1477. ############################
  1478. # OAuth Login & Callback
  1479. ############################
  1480. # SessionMiddleware is used by authlib for oauth
  1481. if len(OAUTH_PROVIDERS) > 0:
  1482. app.add_middleware(
  1483. SessionMiddleware,
  1484. secret_key=WEBUI_SECRET_KEY,
  1485. session_cookie="oui-session",
  1486. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1487. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1488. )
  1489. @app.get("/oauth/{provider}/login")
  1490. async def oauth_login(provider: str, request: Request):
  1491. return await oauth_manager.handle_login(provider, request)
  1492. # OAuth login logic is as follows:
  1493. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1494. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1495. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1496. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1497. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  1498. @app.get("/oauth/{provider}/callback")
  1499. async def oauth_callback(provider: str, request: Request, response: Response):
  1500. return await oauth_manager.handle_callback(provider, request, response)
  1501. @app.get("/manifest.json")
  1502. async def get_manifest_json():
  1503. return {
  1504. "name": WEBUI_NAME,
  1505. "short_name": WEBUI_NAME,
  1506. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  1507. "start_url": "/",
  1508. "display": "standalone",
  1509. "background_color": "#343541",
  1510. "orientation": "natural",
  1511. "icons": [
  1512. {
  1513. "src": "/static/logo.png",
  1514. "type": "image/png",
  1515. "sizes": "500x500",
  1516. "purpose": "any",
  1517. },
  1518. {
  1519. "src": "/static/logo.png",
  1520. "type": "image/png",
  1521. "sizes": "500x500",
  1522. "purpose": "maskable",
  1523. },
  1524. ],
  1525. }
  1526. @app.get("/opensearch.xml")
  1527. async def get_opensearch_xml():
  1528. xml_content = rf"""
  1529. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1530. <ShortName>{WEBUI_NAME}</ShortName>
  1531. <Description>Search {WEBUI_NAME}</Description>
  1532. <InputEncoding>UTF-8</InputEncoding>
  1533. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1534. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1535. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1536. </OpenSearchDescription>
  1537. """
  1538. return Response(content=xml_content, media_type="application/xml")
  1539. @app.get("/health")
  1540. async def healthcheck():
  1541. return {"status": True}
  1542. @app.get("/health/db")
  1543. async def healthcheck_with_db():
  1544. Session.execute(text("SELECT 1;")).all()
  1545. return {"status": True}
  1546. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1547. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1548. if os.path.exists(FRONTEND_BUILD_DIR):
  1549. mimetypes.add_type("text/javascript", ".js")
  1550. app.mount(
  1551. "/",
  1552. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1553. name="spa-static-files",
  1554. )
  1555. else:
  1556. log.warning(
  1557. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1558. )