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