main.py 70 KB

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