main.py 72 KB

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