main.py 72 KB

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