main.py 71 KB

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