main.py 69 KB

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