main.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  1. import base64
  2. import uuid
  3. from contextlib import asynccontextmanager
  4. from authlib.integrations.starlette_client import OAuth
  5. from authlib.oidc.core import UserInfo
  6. import json
  7. import time
  8. import os
  9. import sys
  10. import logging
  11. import aiohttp
  12. import requests
  13. import mimetypes
  14. import shutil
  15. import inspect
  16. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  17. from fastapi.staticfiles import StaticFiles
  18. from fastapi.responses import JSONResponse
  19. from fastapi import HTTPException
  20. from fastapi.middleware.cors import CORSMiddleware
  21. from sqlalchemy import text
  22. from starlette.exceptions import HTTPException as StarletteHTTPException
  23. from starlette.middleware.base import BaseHTTPMiddleware
  24. from starlette.middleware.sessions import SessionMiddleware
  25. from starlette.responses import StreamingResponse, Response, RedirectResponse
  26. from apps.socket.main import app as socket_app, get_event_emitter, get_event_call
  27. from apps.ollama.main import (
  28. app as ollama_app,
  29. get_all_models as get_ollama_models,
  30. generate_openai_chat_completion as generate_ollama_chat_completion,
  31. )
  32. from apps.openai.main import (
  33. app as openai_app,
  34. get_all_models as get_openai_models,
  35. generate_chat_completion as generate_openai_chat_completion,
  36. )
  37. from apps.audio.main import app as audio_app
  38. from apps.images.main import app as images_app
  39. from apps.rag.main import app as rag_app
  40. from apps.webui.main import (
  41. app as webui_app,
  42. get_pipe_models,
  43. generate_function_chat_completion,
  44. )
  45. from apps.webui.internal.db import Session
  46. from pydantic import BaseModel
  47. from typing import Optional
  48. from apps.webui.models.auths import Auths
  49. from apps.webui.models.models import Models
  50. from apps.webui.models.tools import Tools
  51. from apps.webui.models.functions import Functions
  52. from apps.webui.models.users import Users
  53. from apps.webui.utils import load_toolkit_module_by_id, load_function_module_by_id
  54. from utils.utils import (
  55. get_admin_user,
  56. get_verified_user,
  57. get_current_user,
  58. get_http_authorization_cred,
  59. get_password_hash,
  60. create_token,
  61. )
  62. from utils.task import (
  63. title_generation_template,
  64. search_query_generation_template,
  65. tools_function_calling_generation_template,
  66. )
  67. from utils.misc import (
  68. get_last_user_message,
  69. add_or_update_system_message,
  70. prepend_to_first_user_message_content,
  71. parse_duration,
  72. )
  73. from apps.rag.utils import get_rag_context, rag_template
  74. from config import (
  75. WEBUI_NAME,
  76. WEBUI_URL,
  77. WEBUI_AUTH,
  78. ENV,
  79. VERSION,
  80. CHANGELOG,
  81. FRONTEND_BUILD_DIR,
  82. CACHE_DIR,
  83. STATIC_DIR,
  84. DEFAULT_LOCALE,
  85. ENABLE_OPENAI_API,
  86. ENABLE_OLLAMA_API,
  87. ENABLE_MODEL_FILTER,
  88. MODEL_FILTER_LIST,
  89. GLOBAL_LOG_LEVEL,
  90. SRC_LOG_LEVELS,
  91. WEBHOOK_URL,
  92. ENABLE_ADMIN_EXPORT,
  93. WEBUI_BUILD_HASH,
  94. TASK_MODEL,
  95. TASK_MODEL_EXTERNAL,
  96. TITLE_GENERATION_PROMPT_TEMPLATE,
  97. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  98. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  99. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  100. SAFE_MODE,
  101. OAUTH_PROVIDERS,
  102. ENABLE_OAUTH_SIGNUP,
  103. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  104. WEBUI_SECRET_KEY,
  105. WEBUI_SESSION_COOKIE_SAME_SITE,
  106. WEBUI_SESSION_COOKIE_SECURE,
  107. ENABLE_ADMIN_CHAT_ACCESS,
  108. AppConfig,
  109. )
  110. from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES, TASKS
  111. from utils.webhook import post_webhook
  112. if SAFE_MODE:
  113. print("SAFE MODE ENABLED")
  114. Functions.deactivate_all_functions()
  115. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  116. log = logging.getLogger(__name__)
  117. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  118. class SPAStaticFiles(StaticFiles):
  119. async def get_response(self, path: str, scope):
  120. try:
  121. return await super().get_response(path, scope)
  122. except (HTTPException, StarletteHTTPException) as ex:
  123. if ex.status_code == 404:
  124. return await super().get_response("index.html", scope)
  125. else:
  126. raise ex
  127. print(
  128. rf"""
  129. ___ __ __ _ _ _ ___
  130. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  131. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  132. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  133. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  134. |_|
  135. v{VERSION} - building the best open-source AI user interface.
  136. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  137. https://github.com/open-webui/open-webui
  138. """
  139. )
  140. def run_migrations():
  141. try:
  142. from alembic.config import Config
  143. from alembic import command
  144. alembic_cfg = Config("alembic.ini")
  145. command.upgrade(alembic_cfg, "head")
  146. except Exception as e:
  147. print(f"Error: {e}")
  148. @asynccontextmanager
  149. async def lifespan(app: FastAPI):
  150. run_migrations()
  151. yield
  152. app = FastAPI(
  153. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  154. )
  155. app.state.config = AppConfig()
  156. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  157. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  158. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  159. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  160. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  161. app.state.config.TASK_MODEL = TASK_MODEL
  162. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  163. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  164. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  165. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  166. )
  167. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  168. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  169. )
  170. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  171. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  172. )
  173. app.state.MODELS = {}
  174. origins = ["*"]
  175. ##################################
  176. #
  177. # ChatCompletion Middleware
  178. #
  179. ##################################
  180. async def get_body_and_model_and_user(request):
  181. # Read the original request body
  182. body = await request.body()
  183. body_str = body.decode("utf-8")
  184. body = json.loads(body_str) if body_str else {}
  185. model_id = body["model"]
  186. if model_id not in app.state.MODELS:
  187. raise Exception("Model not found")
  188. model = app.state.MODELS[model_id]
  189. user = get_current_user(
  190. request,
  191. get_http_authorization_cred(request.headers.get("Authorization")),
  192. )
  193. return body, model, user
  194. def get_task_model_id(default_model_id):
  195. # Set the task model
  196. task_model_id = default_model_id
  197. # Check if the user has a custom task model and use that model
  198. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  199. if (
  200. app.state.config.TASK_MODEL
  201. and app.state.config.TASK_MODEL in app.state.MODELS
  202. ):
  203. task_model_id = app.state.config.TASK_MODEL
  204. else:
  205. if (
  206. app.state.config.TASK_MODEL_EXTERNAL
  207. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  208. ):
  209. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  210. return task_model_id
  211. def get_filter_function_ids(model):
  212. def get_priority(function_id):
  213. function = Functions.get_function_by_id(function_id)
  214. if function is not None and hasattr(function, "valves"):
  215. return (function.valves if function.valves else {}).get("priority", 0)
  216. return 0
  217. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  218. if "info" in model and "meta" in model["info"]:
  219. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  220. filter_ids = list(set(filter_ids))
  221. enabled_filter_ids = [
  222. function.id
  223. for function in Functions.get_functions_by_type("filter", active_only=True)
  224. ]
  225. filter_ids = [
  226. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  227. ]
  228. filter_ids.sort(key=get_priority)
  229. return filter_ids
  230. async def get_function_call_response(
  231. messages,
  232. files,
  233. tool_id,
  234. template,
  235. task_model_id,
  236. user,
  237. __event_emitter__=None,
  238. __event_call__=None,
  239. ):
  240. tool = Tools.get_tool_by_id(tool_id)
  241. tools_specs = json.dumps(tool.specs, indent=2)
  242. content = tools_function_calling_generation_template(template, tools_specs)
  243. user_message = get_last_user_message(messages)
  244. prompt = (
  245. "History:\n"
  246. + "\n".join(
  247. [
  248. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  249. for message in messages[::-1][:4]
  250. ]
  251. )
  252. + f"\nQuery: {user_message}"
  253. )
  254. print(prompt)
  255. payload = {
  256. "model": task_model_id,
  257. "messages": [
  258. {"role": "system", "content": content},
  259. {"role": "user", "content": f"Query: {prompt}"},
  260. ],
  261. "stream": False,
  262. "task": str(TASKS.FUNCTION_CALLING),
  263. }
  264. try:
  265. payload = filter_pipeline(payload, user)
  266. except Exception as e:
  267. raise e
  268. model = app.state.MODELS[task_model_id]
  269. response = None
  270. try:
  271. response = await generate_chat_completions(form_data=payload, user=user)
  272. content = None
  273. if hasattr(response, "body_iterator"):
  274. async for chunk in response.body_iterator:
  275. data = json.loads(chunk.decode("utf-8"))
  276. content = data["choices"][0]["message"]["content"]
  277. # Cleanup any remaining background tasks if necessary
  278. if response.background is not None:
  279. await response.background()
  280. else:
  281. content = response["choices"][0]["message"]["content"]
  282. if content is None:
  283. return None, None, False
  284. # Parse the function response
  285. print(f"content: {content}")
  286. result = json.loads(content)
  287. print(result)
  288. citation = None
  289. if "name" not in result:
  290. return None, None, False
  291. # Call the function
  292. if tool_id in webui_app.state.TOOLS:
  293. toolkit_module = webui_app.state.TOOLS[tool_id]
  294. else:
  295. toolkit_module, _ = load_toolkit_module_by_id(tool_id)
  296. webui_app.state.TOOLS[tool_id] = toolkit_module
  297. file_handler = False
  298. # check if toolkit_module has file_handler self variable
  299. if hasattr(toolkit_module, "file_handler"):
  300. file_handler = True
  301. print("file_handler: ", file_handler)
  302. if hasattr(toolkit_module, "valves") and hasattr(toolkit_module, "Valves"):
  303. valves = Tools.get_tool_valves_by_id(tool_id)
  304. toolkit_module.valves = toolkit_module.Valves(**(valves if valves else {}))
  305. function = getattr(toolkit_module, result["name"])
  306. function_result = None
  307. try:
  308. # Get the signature of the function
  309. sig = inspect.signature(function)
  310. params = result["parameters"]
  311. # Extra parameters to be passed to the function
  312. extra_params = {
  313. "__model__": model,
  314. "__id__": tool_id,
  315. "__messages__": messages,
  316. "__files__": files,
  317. "__event_emitter__": __event_emitter__,
  318. "__event_call__": __event_call__,
  319. }
  320. # Add extra params in contained in function signature
  321. for key, value in extra_params.items():
  322. if key in sig.parameters:
  323. params[key] = value
  324. if "__user__" in sig.parameters:
  325. # Call the function with the '__user__' parameter included
  326. __user__ = {
  327. "id": user.id,
  328. "email": user.email,
  329. "name": user.name,
  330. "role": user.role,
  331. }
  332. try:
  333. if hasattr(toolkit_module, "UserValves"):
  334. __user__["valves"] = toolkit_module.UserValves(
  335. **Tools.get_user_valves_by_id_and_user_id(tool_id, user.id)
  336. )
  337. except Exception as e:
  338. print(e)
  339. params = {**params, "__user__": __user__}
  340. if inspect.iscoroutinefunction(function):
  341. function_result = await function(**params)
  342. else:
  343. function_result = function(**params)
  344. if hasattr(toolkit_module, "citation") and toolkit_module.citation:
  345. citation = {
  346. "source": {"name": f"TOOL:{tool.name}/{result['name']}"},
  347. "document": [function_result],
  348. "metadata": [{"source": result["name"]}],
  349. }
  350. except Exception as e:
  351. print(e)
  352. # Add the function result to the system prompt
  353. if function_result is not None:
  354. return function_result, citation, file_handler
  355. except Exception as e:
  356. print(f"Error: {e}")
  357. return None, None, False
  358. async def chat_completion_functions_handler(
  359. body, model, user, __event_emitter__, __event_call__
  360. ):
  361. skip_files = None
  362. filter_ids = get_filter_function_ids(model)
  363. for filter_id in filter_ids:
  364. filter = Functions.get_function_by_id(filter_id)
  365. if not filter:
  366. continue
  367. if filter_id in webui_app.state.FUNCTIONS:
  368. function_module = webui_app.state.FUNCTIONS[filter_id]
  369. else:
  370. function_module, _, _ = load_function_module_by_id(filter_id)
  371. webui_app.state.FUNCTIONS[filter_id] = function_module
  372. # Check if the function has a file_handler variable
  373. if hasattr(function_module, "file_handler"):
  374. skip_files = function_module.file_handler
  375. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  376. valves = Functions.get_function_valves_by_id(filter_id)
  377. function_module.valves = function_module.Valves(
  378. **(valves if valves else {})
  379. )
  380. if not hasattr(function_module, "inlet"):
  381. continue
  382. try:
  383. inlet = function_module.inlet
  384. # Get the signature of the function
  385. sig = inspect.signature(inlet)
  386. params = {"body": body}
  387. # Extra parameters to be passed to the function
  388. extra_params = {
  389. "__model__": model,
  390. "__id__": filter_id,
  391. "__event_emitter__": __event_emitter__,
  392. "__event_call__": __event_call__,
  393. }
  394. # Add extra params in contained in function signature
  395. for key, value in extra_params.items():
  396. if key in sig.parameters:
  397. params[key] = value
  398. if "__user__" in sig.parameters:
  399. __user__ = {
  400. "id": user.id,
  401. "email": user.email,
  402. "name": user.name,
  403. "role": user.role,
  404. }
  405. try:
  406. if hasattr(function_module, "UserValves"):
  407. __user__["valves"] = function_module.UserValves(
  408. **Functions.get_user_valves_by_id_and_user_id(
  409. filter_id, user.id
  410. )
  411. )
  412. except Exception as e:
  413. print(e)
  414. params = {**params, "__user__": __user__}
  415. if inspect.iscoroutinefunction(inlet):
  416. body = await inlet(**params)
  417. else:
  418. body = inlet(**params)
  419. except Exception as e:
  420. print(f"Error: {e}")
  421. raise e
  422. if skip_files:
  423. if "files" in body:
  424. del body["files"]
  425. return body, {}
  426. async def chat_completion_tools_handler(body, user, __event_emitter__, __event_call__):
  427. skip_files = None
  428. contexts = []
  429. citations = None
  430. task_model_id = get_task_model_id(body["model"])
  431. # If tool_ids field is present, call the functions
  432. if "tool_ids" not in body:
  433. return body, {}
  434. print(body["tool_ids"])
  435. for tool_id in body["tool_ids"]:
  436. print(tool_id)
  437. try:
  438. response, citation, file_handler = await get_function_call_response(
  439. messages=body["messages"],
  440. files=body.get("files", []),
  441. tool_id=tool_id,
  442. template=app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  443. task_model_id=task_model_id,
  444. user=user,
  445. __event_emitter__=__event_emitter__,
  446. __event_call__=__event_call__,
  447. )
  448. print(file_handler)
  449. if isinstance(response, str):
  450. contexts.append(response)
  451. if citation:
  452. if citations is None:
  453. citations = [citation]
  454. else:
  455. citations.append(citation)
  456. if file_handler:
  457. skip_files = True
  458. except Exception as e:
  459. print(f"Error: {e}")
  460. del body["tool_ids"]
  461. print(f"tool_contexts: {contexts}")
  462. if skip_files:
  463. if "files" in body:
  464. del body["files"]
  465. return body, {
  466. **({"contexts": contexts} if contexts is not None else {}),
  467. **({"citations": citations} if citations is not None else {}),
  468. }
  469. async def chat_completion_files_handler(body):
  470. contexts = []
  471. citations = None
  472. if "files" in body:
  473. files = body["files"]
  474. del body["files"]
  475. contexts, citations = get_rag_context(
  476. files=files,
  477. messages=body["messages"],
  478. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  479. k=rag_app.state.config.TOP_K,
  480. reranking_function=rag_app.state.sentence_transformer_rf,
  481. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  482. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  483. )
  484. log.debug(f"rag_contexts: {contexts}, citations: {citations}")
  485. return body, {
  486. **({"contexts": contexts} if contexts is not None else {}),
  487. **({"citations": citations} if citations is not None else {}),
  488. }
  489. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  490. async def dispatch(self, request: Request, call_next):
  491. if request.method == "POST" and any(
  492. endpoint in request.url.path
  493. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  494. ):
  495. log.debug(f"request.url.path: {request.url.path}")
  496. try:
  497. body, model, user = await get_body_and_model_and_user(request)
  498. except Exception as e:
  499. return JSONResponse(
  500. status_code=status.HTTP_400_BAD_REQUEST,
  501. content={"detail": str(e)},
  502. )
  503. metadata = {
  504. "chat_id": body.pop("chat_id", None),
  505. "message_id": body.pop("id", None),
  506. "session_id": body.pop("session_id", None),
  507. "valves": body.pop("valves", None),
  508. }
  509. __event_emitter__ = get_event_emitter(metadata)
  510. __event_call__ = get_event_call(metadata)
  511. # Initialize data_items to store additional data to be sent to the client
  512. data_items = []
  513. # Initialize context, and citations
  514. contexts = []
  515. citations = []
  516. try:
  517. body, flags = await chat_completion_functions_handler(
  518. body, model, user, __event_emitter__, __event_call__
  519. )
  520. except Exception as e:
  521. return JSONResponse(
  522. status_code=status.HTTP_400_BAD_REQUEST,
  523. content={"detail": str(e)},
  524. )
  525. try:
  526. body, flags = await chat_completion_tools_handler(
  527. body, user, __event_emitter__, __event_call__
  528. )
  529. contexts.extend(flags.get("contexts", []))
  530. citations.extend(flags.get("citations", []))
  531. except Exception as e:
  532. print(e)
  533. pass
  534. try:
  535. body, flags = await chat_completion_files_handler(body)
  536. contexts.extend(flags.get("contexts", []))
  537. citations.extend(flags.get("citations", []))
  538. except Exception as e:
  539. print(e)
  540. pass
  541. # If context is not empty, insert it into the messages
  542. if len(contexts) > 0:
  543. context_string = "/n".join(contexts).strip()
  544. prompt = get_last_user_message(body["messages"])
  545. # Workaround for Ollama 2.0+ system prompt issue
  546. # TODO: replace with add_or_update_system_message
  547. if model["owned_by"] == "ollama":
  548. body["messages"] = prepend_to_first_user_message_content(
  549. rag_template(
  550. rag_app.state.config.RAG_TEMPLATE, context_string, prompt
  551. ),
  552. body["messages"],
  553. )
  554. else:
  555. body["messages"] = add_or_update_system_message(
  556. rag_template(
  557. rag_app.state.config.RAG_TEMPLATE, context_string, prompt
  558. ),
  559. body["messages"],
  560. )
  561. # If there are citations, add them to the data_items
  562. if len(citations) > 0:
  563. data_items.append({"citations": citations})
  564. body["metadata"] = metadata
  565. modified_body_bytes = json.dumps(body).encode("utf-8")
  566. # Replace the request body with the modified one
  567. request._body = modified_body_bytes
  568. # Set custom header to ensure content-length matches new body length
  569. request.headers.__dict__["_list"] = [
  570. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  571. *[
  572. (k, v)
  573. for k, v in request.headers.raw
  574. if k.lower() != b"content-length"
  575. ],
  576. ]
  577. response = await call_next(request)
  578. if isinstance(response, StreamingResponse):
  579. # If it's a streaming response, inject it as SSE event or NDJSON line
  580. content_type = response.headers.get("Content-Type")
  581. if "text/event-stream" in content_type:
  582. return StreamingResponse(
  583. self.openai_stream_wrapper(response.body_iterator, data_items),
  584. )
  585. if "application/x-ndjson" in content_type:
  586. return StreamingResponse(
  587. self.ollama_stream_wrapper(response.body_iterator, data_items),
  588. )
  589. return response
  590. else:
  591. return response
  592. # If it's not a chat completion request, just pass it through
  593. response = await call_next(request)
  594. return response
  595. async def _receive(self, body: bytes):
  596. return {"type": "http.request", "body": body, "more_body": False}
  597. async def openai_stream_wrapper(self, original_generator, data_items):
  598. for item in data_items:
  599. yield f"data: {json.dumps(item)}\n\n"
  600. async for data in original_generator:
  601. yield data
  602. async def ollama_stream_wrapper(self, original_generator, data_items):
  603. for item in data_items:
  604. yield f"{json.dumps(item)}\n"
  605. async for data in original_generator:
  606. yield data
  607. app.add_middleware(ChatCompletionMiddleware)
  608. ##################################
  609. #
  610. # Pipeline Middleware
  611. #
  612. ##################################
  613. def get_sorted_filters(model_id):
  614. filters = [
  615. model
  616. for model in app.state.MODELS.values()
  617. if "pipeline" in model
  618. and "type" in model["pipeline"]
  619. and model["pipeline"]["type"] == "filter"
  620. and (
  621. model["pipeline"]["pipelines"] == ["*"]
  622. or any(
  623. model_id == target_model_id
  624. for target_model_id in model["pipeline"]["pipelines"]
  625. )
  626. )
  627. ]
  628. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  629. return sorted_filters
  630. def filter_pipeline(payload, user):
  631. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  632. model_id = payload["model"]
  633. sorted_filters = get_sorted_filters(model_id)
  634. model = app.state.MODELS[model_id]
  635. if "pipeline" in model:
  636. sorted_filters.append(model)
  637. for filter in sorted_filters:
  638. r = None
  639. try:
  640. urlIdx = filter["urlIdx"]
  641. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  642. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  643. if key != "":
  644. headers = {"Authorization": f"Bearer {key}"}
  645. r = requests.post(
  646. f"{url}/{filter['id']}/filter/inlet",
  647. headers=headers,
  648. json={
  649. "user": user,
  650. "body": payload,
  651. },
  652. )
  653. r.raise_for_status()
  654. payload = r.json()
  655. except Exception as e:
  656. # Handle connection error here
  657. print(f"Connection error: {e}")
  658. if r is not None:
  659. res = r.json()
  660. if "detail" in res:
  661. raise Exception(r.status_code, res["detail"])
  662. return payload
  663. class PipelineMiddleware(BaseHTTPMiddleware):
  664. async def dispatch(self, request: Request, call_next):
  665. if request.method == "POST" and (
  666. "/ollama/api/chat" in request.url.path
  667. or "/chat/completions" in request.url.path
  668. ):
  669. log.debug(f"request.url.path: {request.url.path}")
  670. # Read the original request body
  671. body = await request.body()
  672. # Decode body to string
  673. body_str = body.decode("utf-8")
  674. # Parse string to JSON
  675. data = json.loads(body_str) if body_str else {}
  676. user = get_current_user(
  677. request,
  678. get_http_authorization_cred(request.headers.get("Authorization")),
  679. )
  680. try:
  681. data = filter_pipeline(data, user)
  682. except Exception as e:
  683. return JSONResponse(
  684. status_code=e.args[0],
  685. content={"detail": e.args[1]},
  686. )
  687. modified_body_bytes = json.dumps(data).encode("utf-8")
  688. # Replace the request body with the modified one
  689. request._body = modified_body_bytes
  690. # Set custom header to ensure content-length matches new body length
  691. request.headers.__dict__["_list"] = [
  692. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  693. *[
  694. (k, v)
  695. for k, v in request.headers.raw
  696. if k.lower() != b"content-length"
  697. ],
  698. ]
  699. response = await call_next(request)
  700. return response
  701. async def _receive(self, body: bytes):
  702. return {"type": "http.request", "body": body, "more_body": False}
  703. app.add_middleware(PipelineMiddleware)
  704. app.add_middleware(
  705. CORSMiddleware,
  706. allow_origins=origins,
  707. allow_credentials=True,
  708. allow_methods=["*"],
  709. allow_headers=["*"],
  710. )
  711. @app.middleware("http")
  712. async def commit_session_after_request(request: Request, call_next):
  713. response = await call_next(request)
  714. log.debug("Commit session after request")
  715. Session.commit()
  716. return response
  717. @app.middleware("http")
  718. async def check_url(request: Request, call_next):
  719. if len(app.state.MODELS) == 0:
  720. await get_all_models()
  721. else:
  722. pass
  723. start_time = int(time.time())
  724. response = await call_next(request)
  725. process_time = int(time.time()) - start_time
  726. response.headers["X-Process-Time"] = str(process_time)
  727. return response
  728. @app.middleware("http")
  729. async def update_embedding_function(request: Request, call_next):
  730. response = await call_next(request)
  731. if "/embedding/update" in request.url.path:
  732. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  733. return response
  734. app.mount("/ws", socket_app)
  735. app.mount("/ollama", ollama_app)
  736. app.mount("/openai", openai_app)
  737. app.mount("/images/api/v1", images_app)
  738. app.mount("/audio/api/v1", audio_app)
  739. app.mount("/rag/api/v1", rag_app)
  740. app.mount("/api/v1", webui_app)
  741. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  742. async def get_all_models():
  743. # TODO: Optimize this function
  744. pipe_models = []
  745. openai_models = []
  746. ollama_models = []
  747. pipe_models = await get_pipe_models()
  748. if app.state.config.ENABLE_OPENAI_API:
  749. openai_models = await get_openai_models()
  750. openai_models = openai_models["data"]
  751. if app.state.config.ENABLE_OLLAMA_API:
  752. ollama_models = await get_ollama_models()
  753. ollama_models = [
  754. {
  755. "id": model["model"],
  756. "name": model["name"],
  757. "object": "model",
  758. "created": int(time.time()),
  759. "owned_by": "ollama",
  760. "ollama": model,
  761. }
  762. for model in ollama_models["models"]
  763. ]
  764. models = pipe_models + openai_models + ollama_models
  765. global_action_ids = [
  766. function.id for function in Functions.get_global_action_functions()
  767. ]
  768. enabled_action_ids = [
  769. function.id
  770. for function in Functions.get_functions_by_type("action", active_only=True)
  771. ]
  772. custom_models = Models.get_all_models()
  773. for custom_model in custom_models:
  774. if custom_model.base_model_id is None:
  775. for model in models:
  776. if (
  777. custom_model.id == model["id"]
  778. or custom_model.id == model["id"].split(":")[0]
  779. ):
  780. model["name"] = custom_model.name
  781. model["info"] = custom_model.model_dump()
  782. action_ids = []
  783. if "info" in model and "meta" in model["info"]:
  784. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  785. model["action_ids"] = action_ids
  786. else:
  787. owned_by = "openai"
  788. pipe = None
  789. action_ids = []
  790. for model in models:
  791. if (
  792. custom_model.base_model_id == model["id"]
  793. or custom_model.base_model_id == model["id"].split(":")[0]
  794. ):
  795. owned_by = model["owned_by"]
  796. if "pipe" in model:
  797. pipe = model["pipe"]
  798. if "info" in model and "meta" in model["info"]:
  799. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  800. break
  801. models.append(
  802. {
  803. "id": custom_model.id,
  804. "name": custom_model.name,
  805. "object": "model",
  806. "created": custom_model.created_at,
  807. "owned_by": owned_by,
  808. "info": custom_model.model_dump(),
  809. "preset": True,
  810. **({"pipe": pipe} if pipe is not None else {}),
  811. "action_ids": action_ids,
  812. }
  813. )
  814. for model in models:
  815. action_ids = []
  816. if "action_ids" in model:
  817. action_ids = model["action_ids"]
  818. del model["action_ids"]
  819. action_ids = action_ids + global_action_ids
  820. action_ids = list(set(action_ids))
  821. action_ids = [
  822. action_id for action_id in action_ids if action_id in enabled_action_ids
  823. ]
  824. model["actions"] = []
  825. for action_id in action_ids:
  826. action = Functions.get_function_by_id(action_id)
  827. if action_id in webui_app.state.FUNCTIONS:
  828. function_module = webui_app.state.FUNCTIONS[action_id]
  829. else:
  830. function_module, _, _ = load_function_module_by_id(action_id)
  831. webui_app.state.FUNCTIONS[action_id] = function_module
  832. if hasattr(function_module, "actions"):
  833. actions = function_module.actions
  834. model["actions"].extend(
  835. [
  836. {
  837. "id": f"{action_id}.{_action['id']}",
  838. "name": _action.get(
  839. "name", f"{action.name} ({_action['id']})"
  840. ),
  841. "description": action.meta.description,
  842. "icon_url": _action.get(
  843. "icon_url", action.meta.manifest.get("icon_url", None)
  844. ),
  845. }
  846. for _action in actions
  847. ]
  848. )
  849. else:
  850. model["actions"].append(
  851. {
  852. "id": action_id,
  853. "name": action.name,
  854. "description": action.meta.description,
  855. "icon_url": action.meta.manifest.get("icon_url", None),
  856. }
  857. )
  858. app.state.MODELS = {model["id"]: model for model in models}
  859. webui_app.state.MODELS = app.state.MODELS
  860. return models
  861. @app.get("/api/models")
  862. async def get_models(user=Depends(get_verified_user)):
  863. models = await get_all_models()
  864. # Filter out filter pipelines
  865. models = [
  866. model
  867. for model in models
  868. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  869. ]
  870. if app.state.config.ENABLE_MODEL_FILTER:
  871. if user.role == "user":
  872. models = list(
  873. filter(
  874. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  875. models,
  876. )
  877. )
  878. return {"data": models}
  879. return {"data": models}
  880. @app.post("/api/chat/completions")
  881. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  882. model_id = form_data["model"]
  883. if model_id not in app.state.MODELS:
  884. raise HTTPException(
  885. status_code=status.HTTP_404_NOT_FOUND,
  886. detail="Model not found",
  887. )
  888. model = app.state.MODELS[model_id]
  889. # `task` field is used to determine the type of the request, e.g. `title_generation`, `query_generation`, etc.
  890. task = None
  891. if "task" in form_data:
  892. task = form_data["task"]
  893. del form_data["task"]
  894. if task:
  895. if "metadata" in form_data:
  896. form_data["metadata"]["task"] = task
  897. else:
  898. form_data["metadata"] = {"task": task}
  899. if model.get("pipe"):
  900. return await generate_function_chat_completion(form_data, user=user)
  901. if model["owned_by"] == "ollama":
  902. print("generate_ollama_chat_completion")
  903. return await generate_ollama_chat_completion(form_data, user=user)
  904. else:
  905. return await generate_openai_chat_completion(form_data, user=user)
  906. @app.post("/api/chat/completed")
  907. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  908. data = form_data
  909. model_id = data["model"]
  910. if model_id not in app.state.MODELS:
  911. raise HTTPException(
  912. status_code=status.HTTP_404_NOT_FOUND,
  913. detail="Model not found",
  914. )
  915. model = app.state.MODELS[model_id]
  916. sorted_filters = get_sorted_filters(model_id)
  917. if "pipeline" in model:
  918. sorted_filters = [model] + sorted_filters
  919. for filter in sorted_filters:
  920. r = None
  921. try:
  922. urlIdx = filter["urlIdx"]
  923. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  924. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  925. if key != "":
  926. headers = {"Authorization": f"Bearer {key}"}
  927. r = requests.post(
  928. f"{url}/{filter['id']}/filter/outlet",
  929. headers=headers,
  930. json={
  931. "user": {
  932. "id": user.id,
  933. "name": user.name,
  934. "email": user.email,
  935. "role": user.role,
  936. },
  937. "body": data,
  938. },
  939. )
  940. r.raise_for_status()
  941. data = r.json()
  942. except Exception as e:
  943. # Handle connection error here
  944. print(f"Connection error: {e}")
  945. if r is not None:
  946. try:
  947. res = r.json()
  948. if "detail" in res:
  949. return JSONResponse(
  950. status_code=r.status_code,
  951. content=res,
  952. )
  953. except Exception:
  954. pass
  955. else:
  956. pass
  957. __event_emitter__ = get_event_emitter(
  958. {
  959. "chat_id": data["chat_id"],
  960. "message_id": data["id"],
  961. "session_id": data["session_id"],
  962. }
  963. )
  964. __event_call__ = get_event_call(
  965. {
  966. "chat_id": data["chat_id"],
  967. "message_id": data["id"],
  968. "session_id": data["session_id"],
  969. }
  970. )
  971. def get_priority(function_id):
  972. function = Functions.get_function_by_id(function_id)
  973. if function is not None and hasattr(function, "valves"):
  974. return (function.valves if function.valves else {}).get("priority", 0)
  975. return 0
  976. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  977. if "info" in model and "meta" in model["info"]:
  978. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  979. filter_ids = list(set(filter_ids))
  980. enabled_filter_ids = [
  981. function.id
  982. for function in Functions.get_functions_by_type("filter", active_only=True)
  983. ]
  984. filter_ids = [
  985. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  986. ]
  987. # Sort filter_ids by priority, using the get_priority function
  988. filter_ids.sort(key=get_priority)
  989. for filter_id in filter_ids:
  990. filter = Functions.get_function_by_id(filter_id)
  991. if not filter:
  992. continue
  993. if filter_id in webui_app.state.FUNCTIONS:
  994. function_module = webui_app.state.FUNCTIONS[filter_id]
  995. else:
  996. function_module, _, _ = load_function_module_by_id(filter_id)
  997. webui_app.state.FUNCTIONS[filter_id] = function_module
  998. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  999. valves = Functions.get_function_valves_by_id(filter_id)
  1000. function_module.valves = function_module.Valves(
  1001. **(valves if valves else {})
  1002. )
  1003. if not hasattr(function_module, "outlet"):
  1004. continue
  1005. try:
  1006. outlet = function_module.outlet
  1007. # Get the signature of the function
  1008. sig = inspect.signature(outlet)
  1009. params = {"body": data}
  1010. # Extra parameters to be passed to the function
  1011. extra_params = {
  1012. "__model__": model,
  1013. "__id__": filter_id,
  1014. "__event_emitter__": __event_emitter__,
  1015. "__event_call__": __event_call__,
  1016. }
  1017. # Add extra params in contained in function signature
  1018. for key, value in extra_params.items():
  1019. if key in sig.parameters:
  1020. params[key] = value
  1021. if "__user__" in sig.parameters:
  1022. __user__ = {
  1023. "id": user.id,
  1024. "email": user.email,
  1025. "name": user.name,
  1026. "role": user.role,
  1027. }
  1028. try:
  1029. if hasattr(function_module, "UserValves"):
  1030. __user__["valves"] = function_module.UserValves(
  1031. **Functions.get_user_valves_by_id_and_user_id(
  1032. filter_id, user.id
  1033. )
  1034. )
  1035. except Exception as e:
  1036. print(e)
  1037. params = {**params, "__user__": __user__}
  1038. if inspect.iscoroutinefunction(outlet):
  1039. data = await outlet(**params)
  1040. else:
  1041. data = outlet(**params)
  1042. except Exception as e:
  1043. print(f"Error: {e}")
  1044. return JSONResponse(
  1045. status_code=status.HTTP_400_BAD_REQUEST,
  1046. content={"detail": str(e)},
  1047. )
  1048. return data
  1049. @app.post("/api/chat/actions/{action_id}")
  1050. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1051. if "." in action_id:
  1052. action_id, sub_action_id = action_id.split(".")
  1053. else:
  1054. sub_action_id = None
  1055. action = Functions.get_function_by_id(action_id)
  1056. if not action:
  1057. raise HTTPException(
  1058. status_code=status.HTTP_404_NOT_FOUND,
  1059. detail="Action not found",
  1060. )
  1061. data = form_data
  1062. model_id = data["model"]
  1063. if model_id not in app.state.MODELS:
  1064. raise HTTPException(
  1065. status_code=status.HTTP_404_NOT_FOUND,
  1066. detail="Model not found",
  1067. )
  1068. model = app.state.MODELS[model_id]
  1069. __event_emitter__ = get_event_emitter(
  1070. {
  1071. "chat_id": data["chat_id"],
  1072. "message_id": data["id"],
  1073. "session_id": data["session_id"],
  1074. }
  1075. )
  1076. __event_call__ = get_event_call(
  1077. {
  1078. "chat_id": data["chat_id"],
  1079. "message_id": data["id"],
  1080. "session_id": data["session_id"],
  1081. }
  1082. )
  1083. if action_id in webui_app.state.FUNCTIONS:
  1084. function_module = webui_app.state.FUNCTIONS[action_id]
  1085. else:
  1086. function_module, _, _ = load_function_module_by_id(action_id)
  1087. webui_app.state.FUNCTIONS[action_id] = function_module
  1088. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1089. valves = Functions.get_function_valves_by_id(action_id)
  1090. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1091. if hasattr(function_module, "action"):
  1092. try:
  1093. action = function_module.action
  1094. # Get the signature of the function
  1095. sig = inspect.signature(action)
  1096. params = {"body": data}
  1097. # Extra parameters to be passed to the function
  1098. extra_params = {
  1099. "__model__": model,
  1100. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1101. "__event_emitter__": __event_emitter__,
  1102. "__event_call__": __event_call__,
  1103. }
  1104. # Add extra params in contained in function signature
  1105. for key, value in extra_params.items():
  1106. if key in sig.parameters:
  1107. params[key] = value
  1108. if "__user__" in sig.parameters:
  1109. __user__ = {
  1110. "id": user.id,
  1111. "email": user.email,
  1112. "name": user.name,
  1113. "role": user.role,
  1114. }
  1115. try:
  1116. if hasattr(function_module, "UserValves"):
  1117. __user__["valves"] = function_module.UserValves(
  1118. **Functions.get_user_valves_by_id_and_user_id(
  1119. action_id, user.id
  1120. )
  1121. )
  1122. except Exception as e:
  1123. print(e)
  1124. params = {**params, "__user__": __user__}
  1125. if inspect.iscoroutinefunction(action):
  1126. data = await action(**params)
  1127. else:
  1128. data = action(**params)
  1129. except Exception as e:
  1130. print(f"Error: {e}")
  1131. return JSONResponse(
  1132. status_code=status.HTTP_400_BAD_REQUEST,
  1133. content={"detail": str(e)},
  1134. )
  1135. return data
  1136. ##################################
  1137. #
  1138. # Task Endpoints
  1139. #
  1140. ##################################
  1141. # TODO: Refactor task API endpoints below into a separate file
  1142. @app.get("/api/task/config")
  1143. async def get_task_config(user=Depends(get_verified_user)):
  1144. return {
  1145. "TASK_MODEL": app.state.config.TASK_MODEL,
  1146. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1147. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1148. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1149. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1150. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1151. }
  1152. class TaskConfigForm(BaseModel):
  1153. TASK_MODEL: Optional[str]
  1154. TASK_MODEL_EXTERNAL: Optional[str]
  1155. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1156. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1157. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  1158. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1159. @app.post("/api/task/config/update")
  1160. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1161. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1162. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1163. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1164. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1165. )
  1166. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1167. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1168. )
  1169. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  1170. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  1171. )
  1172. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1173. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1174. )
  1175. return {
  1176. "TASK_MODEL": app.state.config.TASK_MODEL,
  1177. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1178. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1179. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1180. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1181. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1182. }
  1183. @app.post("/api/task/title/completions")
  1184. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1185. print("generate_title")
  1186. model_id = form_data["model"]
  1187. if model_id not in app.state.MODELS:
  1188. raise HTTPException(
  1189. status_code=status.HTTP_404_NOT_FOUND,
  1190. detail="Model not found",
  1191. )
  1192. # Check if the user has a custom task model
  1193. # If the user has a custom task model, use that model
  1194. model_id = get_task_model_id(model_id)
  1195. print(model_id)
  1196. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1197. content = title_generation_template(
  1198. template,
  1199. form_data["prompt"],
  1200. {
  1201. "name": user.name,
  1202. "location": user.info.get("location") if user.info else None,
  1203. },
  1204. )
  1205. payload = {
  1206. "model": model_id,
  1207. "messages": [{"role": "user", "content": content}],
  1208. "stream": False,
  1209. "max_tokens": 50,
  1210. "chat_id": form_data.get("chat_id", None),
  1211. "task": str(TASKS.TITLE_GENERATION),
  1212. }
  1213. log.debug(payload)
  1214. try:
  1215. payload = filter_pipeline(payload, user)
  1216. except Exception as e:
  1217. return JSONResponse(
  1218. status_code=e.args[0],
  1219. content={"detail": e.args[1]},
  1220. )
  1221. if "chat_id" in payload:
  1222. del payload["chat_id"]
  1223. return await generate_chat_completions(form_data=payload, user=user)
  1224. @app.post("/api/task/query/completions")
  1225. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1226. print("generate_search_query")
  1227. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1228. raise HTTPException(
  1229. status_code=status.HTTP_400_BAD_REQUEST,
  1230. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1231. )
  1232. model_id = form_data["model"]
  1233. if model_id not in app.state.MODELS:
  1234. raise HTTPException(
  1235. status_code=status.HTTP_404_NOT_FOUND,
  1236. detail="Model not found",
  1237. )
  1238. # Check if the user has a custom task model
  1239. # If the user has a custom task model, use that model
  1240. model_id = get_task_model_id(model_id)
  1241. print(model_id)
  1242. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1243. content = search_query_generation_template(
  1244. template, form_data["prompt"], {"name": user.name}
  1245. )
  1246. payload = {
  1247. "model": model_id,
  1248. "messages": [{"role": "user", "content": content}],
  1249. "stream": False,
  1250. "max_tokens": 30,
  1251. "task": str(TASKS.QUERY_GENERATION),
  1252. }
  1253. print(payload)
  1254. try:
  1255. payload = filter_pipeline(payload, user)
  1256. except Exception as e:
  1257. return JSONResponse(
  1258. status_code=e.args[0],
  1259. content={"detail": e.args[1]},
  1260. )
  1261. if "chat_id" in payload:
  1262. del payload["chat_id"]
  1263. return await generate_chat_completions(form_data=payload, user=user)
  1264. @app.post("/api/task/emoji/completions")
  1265. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1266. print("generate_emoji")
  1267. model_id = form_data["model"]
  1268. if model_id not in app.state.MODELS:
  1269. raise HTTPException(
  1270. status_code=status.HTTP_404_NOT_FOUND,
  1271. detail="Model not found",
  1272. )
  1273. # Check if the user has a custom task model
  1274. # If the user has a custom task model, use that model
  1275. model_id = get_task_model_id(model_id)
  1276. print(model_id)
  1277. template = '''
  1278. Your task is to reflect the speaker's likely facial expression through a fitting emoji. Interpret emotions from the message and reflect their facial expression using fitting, diverse emojis (e.g., 😊, 😢, 😡, 😱).
  1279. Message: """{{prompt}}"""
  1280. '''
  1281. content = title_generation_template(
  1282. template,
  1283. form_data["prompt"],
  1284. {
  1285. "name": user.name,
  1286. "location": user.info.get("location") if user.info else None,
  1287. },
  1288. )
  1289. payload = {
  1290. "model": model_id,
  1291. "messages": [{"role": "user", "content": content}],
  1292. "stream": False,
  1293. "max_tokens": 4,
  1294. "chat_id": form_data.get("chat_id", None),
  1295. "task": str(TASKS.EMOJI_GENERATION),
  1296. }
  1297. log.debug(payload)
  1298. try:
  1299. payload = filter_pipeline(payload, user)
  1300. except Exception as e:
  1301. return JSONResponse(
  1302. status_code=e.args[0],
  1303. content={"detail": e.args[1]},
  1304. )
  1305. if "chat_id" in payload:
  1306. del payload["chat_id"]
  1307. return await generate_chat_completions(form_data=payload, user=user)
  1308. ##################################
  1309. #
  1310. # Pipelines Endpoints
  1311. #
  1312. ##################################
  1313. # TODO: Refactor pipelines API endpoints below into a separate file
  1314. @app.get("/api/pipelines/list")
  1315. async def get_pipelines_list(user=Depends(get_admin_user)):
  1316. responses = await get_openai_models(raw=True)
  1317. print(responses)
  1318. urlIdxs = [
  1319. idx
  1320. for idx, response in enumerate(responses)
  1321. if response is not None and "pipelines" in response
  1322. ]
  1323. return {
  1324. "data": [
  1325. {
  1326. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1327. "idx": urlIdx,
  1328. }
  1329. for urlIdx in urlIdxs
  1330. ]
  1331. }
  1332. @app.post("/api/pipelines/upload")
  1333. async def upload_pipeline(
  1334. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1335. ):
  1336. print("upload_pipeline", urlIdx, file.filename)
  1337. # Check if the uploaded file is a python file
  1338. if not file.filename.endswith(".py"):
  1339. raise HTTPException(
  1340. status_code=status.HTTP_400_BAD_REQUEST,
  1341. detail="Only Python (.py) files are allowed.",
  1342. )
  1343. upload_folder = f"{CACHE_DIR}/pipelines"
  1344. os.makedirs(upload_folder, exist_ok=True)
  1345. file_path = os.path.join(upload_folder, file.filename)
  1346. r = None
  1347. try:
  1348. # Save the uploaded file
  1349. with open(file_path, "wb") as buffer:
  1350. shutil.copyfileobj(file.file, buffer)
  1351. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1352. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1353. headers = {"Authorization": f"Bearer {key}"}
  1354. with open(file_path, "rb") as f:
  1355. files = {"file": f}
  1356. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1357. r.raise_for_status()
  1358. data = r.json()
  1359. return {**data}
  1360. except Exception as e:
  1361. # Handle connection error here
  1362. print(f"Connection error: {e}")
  1363. detail = "Pipeline not found"
  1364. status_code = status.HTTP_404_NOT_FOUND
  1365. if r is not None:
  1366. status_code = r.status_code
  1367. try:
  1368. res = r.json()
  1369. if "detail" in res:
  1370. detail = res["detail"]
  1371. except Exception:
  1372. pass
  1373. raise HTTPException(
  1374. status_code=status_code,
  1375. detail=detail,
  1376. )
  1377. finally:
  1378. # Ensure the file is deleted after the upload is completed or on failure
  1379. if os.path.exists(file_path):
  1380. os.remove(file_path)
  1381. class AddPipelineForm(BaseModel):
  1382. url: str
  1383. urlIdx: int
  1384. @app.post("/api/pipelines/add")
  1385. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1386. r = None
  1387. try:
  1388. urlIdx = form_data.urlIdx
  1389. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1390. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1391. headers = {"Authorization": f"Bearer {key}"}
  1392. r = requests.post(
  1393. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1394. )
  1395. r.raise_for_status()
  1396. data = r.json()
  1397. return {**data}
  1398. except Exception as e:
  1399. # Handle connection error here
  1400. print(f"Connection error: {e}")
  1401. detail = "Pipeline not found"
  1402. if r is not None:
  1403. try:
  1404. res = r.json()
  1405. if "detail" in res:
  1406. detail = res["detail"]
  1407. except Exception:
  1408. pass
  1409. raise HTTPException(
  1410. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1411. detail=detail,
  1412. )
  1413. class DeletePipelineForm(BaseModel):
  1414. id: str
  1415. urlIdx: int
  1416. @app.delete("/api/pipelines/delete")
  1417. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1418. r = None
  1419. try:
  1420. urlIdx = form_data.urlIdx
  1421. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1422. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1423. headers = {"Authorization": f"Bearer {key}"}
  1424. r = requests.delete(
  1425. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1426. )
  1427. r.raise_for_status()
  1428. data = r.json()
  1429. return {**data}
  1430. except Exception as e:
  1431. # Handle connection error here
  1432. print(f"Connection error: {e}")
  1433. detail = "Pipeline not found"
  1434. if r is not None:
  1435. try:
  1436. res = r.json()
  1437. if "detail" in res:
  1438. detail = res["detail"]
  1439. except Exception:
  1440. pass
  1441. raise HTTPException(
  1442. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1443. detail=detail,
  1444. )
  1445. @app.get("/api/pipelines")
  1446. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1447. r = None
  1448. try:
  1449. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1450. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1451. headers = {"Authorization": f"Bearer {key}"}
  1452. r = requests.get(f"{url}/pipelines", headers=headers)
  1453. r.raise_for_status()
  1454. data = r.json()
  1455. return {**data}
  1456. except Exception as e:
  1457. # Handle connection error here
  1458. print(f"Connection error: {e}")
  1459. detail = "Pipeline not found"
  1460. if r is not None:
  1461. try:
  1462. res = r.json()
  1463. if "detail" in res:
  1464. detail = res["detail"]
  1465. except Exception:
  1466. pass
  1467. raise HTTPException(
  1468. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1469. detail=detail,
  1470. )
  1471. @app.get("/api/pipelines/{pipeline_id}/valves")
  1472. async def get_pipeline_valves(
  1473. urlIdx: Optional[int],
  1474. pipeline_id: str,
  1475. user=Depends(get_admin_user),
  1476. ):
  1477. r = None
  1478. try:
  1479. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1480. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1481. headers = {"Authorization": f"Bearer {key}"}
  1482. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1483. r.raise_for_status()
  1484. data = r.json()
  1485. return {**data}
  1486. except Exception as e:
  1487. # Handle connection error here
  1488. print(f"Connection error: {e}")
  1489. detail = "Pipeline not found"
  1490. if r is not None:
  1491. try:
  1492. res = r.json()
  1493. if "detail" in res:
  1494. detail = res["detail"]
  1495. except Exception:
  1496. pass
  1497. raise HTTPException(
  1498. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1499. detail=detail,
  1500. )
  1501. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1502. async def get_pipeline_valves_spec(
  1503. urlIdx: Optional[int],
  1504. pipeline_id: str,
  1505. user=Depends(get_admin_user),
  1506. ):
  1507. r = None
  1508. try:
  1509. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1510. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1511. headers = {"Authorization": f"Bearer {key}"}
  1512. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1513. r.raise_for_status()
  1514. data = r.json()
  1515. return {**data}
  1516. except Exception as e:
  1517. # Handle connection error here
  1518. print(f"Connection error: {e}")
  1519. detail = "Pipeline not found"
  1520. if r is not None:
  1521. try:
  1522. res = r.json()
  1523. if "detail" in res:
  1524. detail = res["detail"]
  1525. except Exception:
  1526. pass
  1527. raise HTTPException(
  1528. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1529. detail=detail,
  1530. )
  1531. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1532. async def update_pipeline_valves(
  1533. urlIdx: Optional[int],
  1534. pipeline_id: str,
  1535. form_data: dict,
  1536. user=Depends(get_admin_user),
  1537. ):
  1538. r = None
  1539. try:
  1540. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1541. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1542. headers = {"Authorization": f"Bearer {key}"}
  1543. r = requests.post(
  1544. f"{url}/{pipeline_id}/valves/update",
  1545. headers=headers,
  1546. json={**form_data},
  1547. )
  1548. r.raise_for_status()
  1549. data = r.json()
  1550. return {**data}
  1551. except Exception as e:
  1552. # Handle connection error here
  1553. print(f"Connection error: {e}")
  1554. detail = "Pipeline not found"
  1555. if r is not None:
  1556. try:
  1557. res = r.json()
  1558. if "detail" in res:
  1559. detail = res["detail"]
  1560. except Exception:
  1561. pass
  1562. raise HTTPException(
  1563. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1564. detail=detail,
  1565. )
  1566. ##################################
  1567. #
  1568. # Config Endpoints
  1569. #
  1570. ##################################
  1571. @app.get("/api/config")
  1572. async def get_app_config():
  1573. return {
  1574. "status": True,
  1575. "name": WEBUI_NAME,
  1576. "version": VERSION,
  1577. "default_locale": str(DEFAULT_LOCALE),
  1578. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1579. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1580. "features": {
  1581. "auth": WEBUI_AUTH,
  1582. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1583. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1584. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1585. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1586. "enable_image_generation": images_app.state.config.ENABLED,
  1587. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1588. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1589. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1590. },
  1591. "audio": {
  1592. "tts": {
  1593. "engine": audio_app.state.config.TTS_ENGINE,
  1594. "voice": audio_app.state.config.TTS_VOICE,
  1595. },
  1596. "stt": {
  1597. "engine": audio_app.state.config.STT_ENGINE,
  1598. },
  1599. },
  1600. "oauth": {
  1601. "providers": {
  1602. name: config.get("name", name)
  1603. for name, config in OAUTH_PROVIDERS.items()
  1604. }
  1605. },
  1606. }
  1607. @app.get("/api/config/model/filter")
  1608. async def get_model_filter_config(user=Depends(get_admin_user)):
  1609. return {
  1610. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1611. "models": app.state.config.MODEL_FILTER_LIST,
  1612. }
  1613. class ModelFilterConfigForm(BaseModel):
  1614. enabled: bool
  1615. models: list[str]
  1616. @app.post("/api/config/model/filter")
  1617. async def update_model_filter_config(
  1618. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1619. ):
  1620. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1621. app.state.config.MODEL_FILTER_LIST = form_data.models
  1622. return {
  1623. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1624. "models": app.state.config.MODEL_FILTER_LIST,
  1625. }
  1626. # TODO: webhook endpoint should be under config endpoints
  1627. @app.get("/api/webhook")
  1628. async def get_webhook_url(user=Depends(get_admin_user)):
  1629. return {
  1630. "url": app.state.config.WEBHOOK_URL,
  1631. }
  1632. class UrlForm(BaseModel):
  1633. url: str
  1634. @app.post("/api/webhook")
  1635. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1636. app.state.config.WEBHOOK_URL = form_data.url
  1637. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1638. return {"url": app.state.config.WEBHOOK_URL}
  1639. @app.get("/api/version")
  1640. async def get_app_version():
  1641. return {
  1642. "version": VERSION,
  1643. }
  1644. @app.get("/api/changelog")
  1645. async def get_app_changelog():
  1646. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1647. @app.get("/api/version/updates")
  1648. async def get_app_latest_release_version():
  1649. try:
  1650. async with aiohttp.ClientSession(trust_env=True) as session:
  1651. async with session.get(
  1652. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1653. ) as response:
  1654. response.raise_for_status()
  1655. data = await response.json()
  1656. latest_version = data["tag_name"]
  1657. return {"current": VERSION, "latest": latest_version[1:]}
  1658. except aiohttp.ClientError:
  1659. raise HTTPException(
  1660. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1661. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1662. )
  1663. ############################
  1664. # OAuth Login & Callback
  1665. ############################
  1666. oauth = OAuth()
  1667. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1668. oauth.register(
  1669. name=provider_name,
  1670. client_id=provider_config["client_id"],
  1671. client_secret=provider_config["client_secret"],
  1672. server_metadata_url=provider_config["server_metadata_url"],
  1673. client_kwargs={
  1674. "scope": provider_config["scope"],
  1675. },
  1676. redirect_uri=provider_config["redirect_uri"],
  1677. )
  1678. # SessionMiddleware is used by authlib for oauth
  1679. if len(OAUTH_PROVIDERS) > 0:
  1680. app.add_middleware(
  1681. SessionMiddleware,
  1682. secret_key=WEBUI_SECRET_KEY,
  1683. session_cookie="oui-session",
  1684. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1685. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1686. )
  1687. @app.get("/oauth/{provider}/login")
  1688. async def oauth_login(provider: str, request: Request):
  1689. if provider not in OAUTH_PROVIDERS:
  1690. raise HTTPException(404)
  1691. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  1692. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  1693. "oauth_callback", provider=provider
  1694. )
  1695. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1696. # OAuth login logic is as follows:
  1697. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1698. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1699. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1700. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1701. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1702. @app.get("/oauth/{provider}/callback")
  1703. async def oauth_callback(provider: str, request: Request, response: Response):
  1704. if provider not in OAUTH_PROVIDERS:
  1705. raise HTTPException(404)
  1706. client = oauth.create_client(provider)
  1707. try:
  1708. token = await client.authorize_access_token(request)
  1709. except Exception as e:
  1710. log.warning(f"OAuth callback error: {e}")
  1711. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1712. user_data: UserInfo = token["userinfo"]
  1713. sub = user_data.get("sub")
  1714. if not sub:
  1715. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1716. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1717. provider_sub = f"{provider}@{sub}"
  1718. email_claim = webui_app.state.config.OAUTH_EMAIL_CLAIM
  1719. email = user_data.get(email_claim, "").lower()
  1720. # We currently mandate that email addresses are provided
  1721. if not email:
  1722. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1723. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1724. # Check if the user exists
  1725. user = Users.get_user_by_oauth_sub(provider_sub)
  1726. if not user:
  1727. # If the user does not exist, check if merging is enabled
  1728. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1729. # Check if the user exists by email
  1730. user = Users.get_user_by_email(email)
  1731. if user:
  1732. # Update the user with the new oauth sub
  1733. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1734. if not user:
  1735. # If the user does not exist, check if signups are enabled
  1736. if ENABLE_OAUTH_SIGNUP.value:
  1737. # Check if an existing user with the same email already exists
  1738. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1739. if existing_user:
  1740. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1741. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1742. picture_url = user_data.get(picture_claim, "")
  1743. if picture_url:
  1744. # Download the profile image into a base64 string
  1745. try:
  1746. async with aiohttp.ClientSession() as session:
  1747. async with session.get(picture_url) as resp:
  1748. picture = await resp.read()
  1749. base64_encoded_picture = base64.b64encode(picture).decode(
  1750. "utf-8"
  1751. )
  1752. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1753. if guessed_mime_type is None:
  1754. # assume JPG, browsers are tolerant enough of image formats
  1755. guessed_mime_type = "image/jpeg"
  1756. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1757. except Exception as e:
  1758. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1759. picture_url = ""
  1760. if not picture_url:
  1761. picture_url = "/user.png"
  1762. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1763. role = (
  1764. "admin"
  1765. if Users.get_num_users() == 0
  1766. else webui_app.state.config.DEFAULT_USER_ROLE
  1767. )
  1768. user = Auths.insert_new_auth(
  1769. email=email,
  1770. password=get_password_hash(
  1771. str(uuid.uuid4())
  1772. ), # Random password, not used
  1773. name=user_data.get(username_claim, "User"),
  1774. profile_image_url=picture_url,
  1775. role=role,
  1776. oauth_sub=provider_sub,
  1777. )
  1778. if webui_app.state.config.WEBHOOK_URL:
  1779. post_webhook(
  1780. webui_app.state.config.WEBHOOK_URL,
  1781. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1782. {
  1783. "action": "signup",
  1784. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1785. "user": user.model_dump_json(exclude_none=True),
  1786. },
  1787. )
  1788. else:
  1789. raise HTTPException(
  1790. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1791. )
  1792. jwt_token = create_token(
  1793. data={"id": user.id},
  1794. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1795. )
  1796. # Set the cookie token
  1797. response.set_cookie(
  1798. key="token",
  1799. value=jwt_token,
  1800. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1801. )
  1802. # Redirect back to the frontend with the JWT token
  1803. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1804. return RedirectResponse(url=redirect_url)
  1805. @app.get("/manifest.json")
  1806. async def get_manifest_json():
  1807. return {
  1808. "name": WEBUI_NAME,
  1809. "short_name": WEBUI_NAME,
  1810. "start_url": "/",
  1811. "display": "standalone",
  1812. "background_color": "#343541",
  1813. "orientation": "portrait-primary",
  1814. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1815. }
  1816. @app.get("/opensearch.xml")
  1817. async def get_opensearch_xml():
  1818. xml_content = rf"""
  1819. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1820. <ShortName>{WEBUI_NAME}</ShortName>
  1821. <Description>Search {WEBUI_NAME}</Description>
  1822. <InputEncoding>UTF-8</InputEncoding>
  1823. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1824. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1825. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1826. </OpenSearchDescription>
  1827. """
  1828. return Response(content=xml_content, media_type="application/xml")
  1829. @app.get("/health")
  1830. async def healthcheck():
  1831. return {"status": True}
  1832. @app.get("/health/db")
  1833. async def healthcheck_with_db():
  1834. Session.execute(text("SELECT 1;")).all()
  1835. return {"status": True}
  1836. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1837. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1838. if os.path.exists(FRONTEND_BUILD_DIR):
  1839. mimetypes.add_type("text/javascript", ".js")
  1840. app.mount(
  1841. "/",
  1842. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1843. name="spa-static-files",
  1844. )
  1845. else:
  1846. log.warning(
  1847. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1848. )