main.py 70 KB

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