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_content_from_response(response) -> Optional[str]:
  231. content = None
  232. if hasattr(response, "body_iterator"):
  233. async for chunk in response.body_iterator:
  234. data = json.loads(chunk.decode("utf-8"))
  235. content = data["choices"][0]["message"]["content"]
  236. # Cleanup any remaining background tasks if necessary
  237. if response.background is not None:
  238. await response.background()
  239. else:
  240. content = response["choices"][0]["message"]["content"]
  241. return content
  242. async def call_tool_from_completion(
  243. result: dict, extra_params: dict, toolkit_module
  244. ) -> Optional[str]:
  245. if "name" not in result:
  246. return None
  247. tool = getattr(toolkit_module, result["name"])
  248. try:
  249. # Get the signature of the function
  250. sig = inspect.signature(tool)
  251. params = result["parameters"]
  252. for key, value in extra_params.items():
  253. if key in sig.parameters:
  254. params[key] = value
  255. if inspect.iscoroutinefunction(tool):
  256. return await tool(**params)
  257. else:
  258. return tool(**params)
  259. except Exception as e:
  260. print(f"Error: {e}")
  261. return None
  262. async def get_function_call_response(
  263. messages,
  264. files,
  265. tool_id,
  266. template,
  267. task_model_id,
  268. user,
  269. __event_emitter__=None,
  270. __event_call__=None,
  271. ) -> tuple[Optional[str], Optional[dict], bool]:
  272. tool = Tools.get_tool_by_id(tool_id)
  273. if tool is None:
  274. return None, None, False
  275. tools_specs = json.dumps(tool.specs, indent=2)
  276. content = tools_function_calling_generation_template(template, tools_specs)
  277. user_message = get_last_user_message(messages)
  278. prompt = (
  279. "History:\n"
  280. + "\n".join(
  281. [
  282. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  283. for message in messages[::-1][:4]
  284. ]
  285. )
  286. + f"\nQuery: {user_message}"
  287. )
  288. print(prompt)
  289. payload = {
  290. "model": task_model_id,
  291. "messages": [
  292. {"role": "system", "content": content},
  293. {"role": "user", "content": f"Query: {prompt}"},
  294. ],
  295. "stream": False,
  296. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  297. }
  298. try:
  299. payload = filter_pipeline(payload, user)
  300. except Exception as e:
  301. raise e
  302. if tool_id in webui_app.state.TOOLS:
  303. toolkit_module = webui_app.state.TOOLS[tool_id]
  304. else:
  305. toolkit_module, _ = load_toolkit_module_by_id(tool_id)
  306. webui_app.state.TOOLS[tool_id] = toolkit_module
  307. __user__ = {
  308. "id": user.id,
  309. "email": user.email,
  310. "name": user.name,
  311. "role": user.role,
  312. }
  313. try:
  314. if hasattr(toolkit_module, "UserValves"):
  315. __user__["valves"] = toolkit_module.UserValves(
  316. **Tools.get_user_valves_by_id_and_user_id(tool_id, user.id)
  317. )
  318. except Exception as e:
  319. print(e)
  320. extra_params = {
  321. "__model__": app.state.MODELS[task_model_id],
  322. "__id__": tool_id,
  323. "__messages__": messages,
  324. "__files__": files,
  325. "__event_emitter__": __event_emitter__,
  326. "__event_call__": __event_call__,
  327. "__user__": __user__,
  328. }
  329. file_handler = hasattr(toolkit_module, "file_handler")
  330. if hasattr(toolkit_module, "valves") and hasattr(toolkit_module, "Valves"):
  331. valves = Tools.get_tool_valves_by_id(tool_id)
  332. toolkit_module.valves = toolkit_module.Valves(**(valves if valves else {}))
  333. try:
  334. response = await generate_chat_completions(form_data=payload, user=user)
  335. content = await get_content_from_response(response)
  336. if content is None:
  337. return None, None, False
  338. # Parse the function response
  339. log.debug(f"content: {content}")
  340. result = json.loads(content)
  341. function_result = await call_tool_from_completion(
  342. result, extra_params, toolkit_module
  343. )
  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. else:
  351. citation = None
  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. return await generate_ollama_chat_completion(form_data, user=user)
  884. else:
  885. return await generate_openai_chat_completion(form_data, user=user)
  886. @app.post("/api/chat/completed")
  887. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  888. data = form_data
  889. model_id = data["model"]
  890. if model_id not in app.state.MODELS:
  891. raise HTTPException(
  892. status_code=status.HTTP_404_NOT_FOUND,
  893. detail="Model not found",
  894. )
  895. model = app.state.MODELS[model_id]
  896. sorted_filters = get_sorted_filters(model_id)
  897. if "pipeline" in model:
  898. sorted_filters = [model] + sorted_filters
  899. for filter in sorted_filters:
  900. r = None
  901. try:
  902. urlIdx = filter["urlIdx"]
  903. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  904. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  905. if key != "":
  906. headers = {"Authorization": f"Bearer {key}"}
  907. r = requests.post(
  908. f"{url}/{filter['id']}/filter/outlet",
  909. headers=headers,
  910. json={
  911. "user": {
  912. "id": user.id,
  913. "name": user.name,
  914. "email": user.email,
  915. "role": user.role,
  916. },
  917. "body": data,
  918. },
  919. )
  920. r.raise_for_status()
  921. data = r.json()
  922. except Exception as e:
  923. # Handle connection error here
  924. print(f"Connection error: {e}")
  925. if r is not None:
  926. try:
  927. res = r.json()
  928. if "detail" in res:
  929. return JSONResponse(
  930. status_code=r.status_code,
  931. content=res,
  932. )
  933. except Exception:
  934. pass
  935. else:
  936. pass
  937. __event_emitter__ = get_event_emitter(
  938. {
  939. "chat_id": data["chat_id"],
  940. "message_id": data["id"],
  941. "session_id": data["session_id"],
  942. }
  943. )
  944. __event_call__ = get_event_call(
  945. {
  946. "chat_id": data["chat_id"],
  947. "message_id": data["id"],
  948. "session_id": data["session_id"],
  949. }
  950. )
  951. def get_priority(function_id):
  952. function = Functions.get_function_by_id(function_id)
  953. if function is not None and hasattr(function, "valves"):
  954. return (function.valves if function.valves else {}).get("priority", 0)
  955. return 0
  956. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  957. if "info" in model and "meta" in model["info"]:
  958. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  959. filter_ids = list(set(filter_ids))
  960. enabled_filter_ids = [
  961. function.id
  962. for function in Functions.get_functions_by_type("filter", active_only=True)
  963. ]
  964. filter_ids = [
  965. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  966. ]
  967. # Sort filter_ids by priority, using the get_priority function
  968. filter_ids.sort(key=get_priority)
  969. for filter_id in filter_ids:
  970. filter = Functions.get_function_by_id(filter_id)
  971. if not filter:
  972. continue
  973. if filter_id in webui_app.state.FUNCTIONS:
  974. function_module = webui_app.state.FUNCTIONS[filter_id]
  975. else:
  976. function_module, _, _ = load_function_module_by_id(filter_id)
  977. webui_app.state.FUNCTIONS[filter_id] = function_module
  978. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  979. valves = Functions.get_function_valves_by_id(filter_id)
  980. function_module.valves = function_module.Valves(
  981. **(valves if valves else {})
  982. )
  983. if not hasattr(function_module, "outlet"):
  984. continue
  985. try:
  986. outlet = function_module.outlet
  987. # Get the signature of the function
  988. sig = inspect.signature(outlet)
  989. params = {"body": data}
  990. # Extra parameters to be passed to the function
  991. extra_params = {
  992. "__model__": model,
  993. "__id__": filter_id,
  994. "__event_emitter__": __event_emitter__,
  995. "__event_call__": __event_call__,
  996. }
  997. # Add extra params in contained in function signature
  998. for key, value in extra_params.items():
  999. if key in sig.parameters:
  1000. params[key] = value
  1001. if "__user__" in sig.parameters:
  1002. __user__ = {
  1003. "id": user.id,
  1004. "email": user.email,
  1005. "name": user.name,
  1006. "role": user.role,
  1007. }
  1008. try:
  1009. if hasattr(function_module, "UserValves"):
  1010. __user__["valves"] = function_module.UserValves(
  1011. **Functions.get_user_valves_by_id_and_user_id(
  1012. filter_id, user.id
  1013. )
  1014. )
  1015. except Exception as e:
  1016. print(e)
  1017. params = {**params, "__user__": __user__}
  1018. if inspect.iscoroutinefunction(outlet):
  1019. data = await outlet(**params)
  1020. else:
  1021. data = outlet(**params)
  1022. except Exception as e:
  1023. print(f"Error: {e}")
  1024. return JSONResponse(
  1025. status_code=status.HTTP_400_BAD_REQUEST,
  1026. content={"detail": str(e)},
  1027. )
  1028. return data
  1029. @app.post("/api/chat/actions/{action_id}")
  1030. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1031. if "." in action_id:
  1032. action_id, sub_action_id = action_id.split(".")
  1033. else:
  1034. sub_action_id = None
  1035. action = Functions.get_function_by_id(action_id)
  1036. if not action:
  1037. raise HTTPException(
  1038. status_code=status.HTTP_404_NOT_FOUND,
  1039. detail="Action not found",
  1040. )
  1041. data = form_data
  1042. model_id = data["model"]
  1043. if model_id not in app.state.MODELS:
  1044. raise HTTPException(
  1045. status_code=status.HTTP_404_NOT_FOUND,
  1046. detail="Model not found",
  1047. )
  1048. model = app.state.MODELS[model_id]
  1049. __event_emitter__ = get_event_emitter(
  1050. {
  1051. "chat_id": data["chat_id"],
  1052. "message_id": data["id"],
  1053. "session_id": data["session_id"],
  1054. }
  1055. )
  1056. __event_call__ = get_event_call(
  1057. {
  1058. "chat_id": data["chat_id"],
  1059. "message_id": data["id"],
  1060. "session_id": data["session_id"],
  1061. }
  1062. )
  1063. if action_id in webui_app.state.FUNCTIONS:
  1064. function_module = webui_app.state.FUNCTIONS[action_id]
  1065. else:
  1066. function_module, _, _ = load_function_module_by_id(action_id)
  1067. webui_app.state.FUNCTIONS[action_id] = function_module
  1068. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1069. valves = Functions.get_function_valves_by_id(action_id)
  1070. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1071. if hasattr(function_module, "action"):
  1072. try:
  1073. action = function_module.action
  1074. # Get the signature of the function
  1075. sig = inspect.signature(action)
  1076. params = {"body": data}
  1077. # Extra parameters to be passed to the function
  1078. extra_params = {
  1079. "__model__": model,
  1080. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1081. "__event_emitter__": __event_emitter__,
  1082. "__event_call__": __event_call__,
  1083. }
  1084. # Add extra params in contained in function signature
  1085. for key, value in extra_params.items():
  1086. if key in sig.parameters:
  1087. params[key] = value
  1088. if "__user__" in sig.parameters:
  1089. __user__ = {
  1090. "id": user.id,
  1091. "email": user.email,
  1092. "name": user.name,
  1093. "role": user.role,
  1094. }
  1095. try:
  1096. if hasattr(function_module, "UserValves"):
  1097. __user__["valves"] = function_module.UserValves(
  1098. **Functions.get_user_valves_by_id_and_user_id(
  1099. action_id, user.id
  1100. )
  1101. )
  1102. except Exception as e:
  1103. print(e)
  1104. params = {**params, "__user__": __user__}
  1105. if inspect.iscoroutinefunction(action):
  1106. data = await action(**params)
  1107. else:
  1108. data = action(**params)
  1109. except Exception as e:
  1110. print(f"Error: {e}")
  1111. return JSONResponse(
  1112. status_code=status.HTTP_400_BAD_REQUEST,
  1113. content={"detail": str(e)},
  1114. )
  1115. return data
  1116. ##################################
  1117. #
  1118. # Task Endpoints
  1119. #
  1120. ##################################
  1121. # TODO: Refactor task API endpoints below into a separate file
  1122. @app.get("/api/task/config")
  1123. async def get_task_config(user=Depends(get_verified_user)):
  1124. return {
  1125. "TASK_MODEL": app.state.config.TASK_MODEL,
  1126. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1127. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1128. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1129. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1130. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1131. }
  1132. class TaskConfigForm(BaseModel):
  1133. TASK_MODEL: Optional[str]
  1134. TASK_MODEL_EXTERNAL: Optional[str]
  1135. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1136. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1137. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  1138. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1139. @app.post("/api/task/config/update")
  1140. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1141. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1142. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1143. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1144. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1145. )
  1146. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1147. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1148. )
  1149. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  1150. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  1151. )
  1152. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1153. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1154. )
  1155. return {
  1156. "TASK_MODEL": app.state.config.TASK_MODEL,
  1157. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1158. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1159. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1160. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1161. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1162. }
  1163. @app.post("/api/task/title/completions")
  1164. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1165. print("generate_title")
  1166. model_id = form_data["model"]
  1167. if model_id not in app.state.MODELS:
  1168. raise HTTPException(
  1169. status_code=status.HTTP_404_NOT_FOUND,
  1170. detail="Model not found",
  1171. )
  1172. # Check if the user has a custom task model
  1173. # If the user has a custom task model, use that model
  1174. model_id = get_task_model_id(model_id)
  1175. print(model_id)
  1176. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1177. content = title_generation_template(
  1178. template,
  1179. form_data["prompt"],
  1180. {
  1181. "name": user.name,
  1182. "location": user.info.get("location") if user.info else None,
  1183. },
  1184. )
  1185. payload = {
  1186. "model": model_id,
  1187. "messages": [{"role": "user", "content": content}],
  1188. "stream": False,
  1189. "max_tokens": 50,
  1190. "chat_id": form_data.get("chat_id", None),
  1191. "metadata": {"task": str(TASKS.TITLE_GENERATION)},
  1192. }
  1193. log.debug(payload)
  1194. try:
  1195. payload = filter_pipeline(payload, user)
  1196. except Exception as e:
  1197. return JSONResponse(
  1198. status_code=e.args[0],
  1199. content={"detail": e.args[1]},
  1200. )
  1201. if "chat_id" in payload:
  1202. del payload["chat_id"]
  1203. return await generate_chat_completions(form_data=payload, user=user)
  1204. @app.post("/api/task/query/completions")
  1205. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1206. print("generate_search_query")
  1207. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1208. raise HTTPException(
  1209. status_code=status.HTTP_400_BAD_REQUEST,
  1210. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1211. )
  1212. model_id = form_data["model"]
  1213. if model_id not in app.state.MODELS:
  1214. raise HTTPException(
  1215. status_code=status.HTTP_404_NOT_FOUND,
  1216. detail="Model not found",
  1217. )
  1218. # Check if the user has a custom task model
  1219. # If the user has a custom task model, use that model
  1220. model_id = get_task_model_id(model_id)
  1221. print(model_id)
  1222. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1223. content = search_query_generation_template(
  1224. template, form_data["prompt"], {"name": user.name}
  1225. )
  1226. payload = {
  1227. "model": model_id,
  1228. "messages": [{"role": "user", "content": content}],
  1229. "stream": False,
  1230. "max_tokens": 30,
  1231. "metadata": {"task": str(TASKS.QUERY_GENERATION)},
  1232. }
  1233. print(payload)
  1234. try:
  1235. payload = filter_pipeline(payload, user)
  1236. except Exception as e:
  1237. return JSONResponse(
  1238. status_code=e.args[0],
  1239. content={"detail": e.args[1]},
  1240. )
  1241. if "chat_id" in payload:
  1242. del payload["chat_id"]
  1243. return await generate_chat_completions(form_data=payload, user=user)
  1244. @app.post("/api/task/emoji/completions")
  1245. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1246. print("generate_emoji")
  1247. model_id = form_data["model"]
  1248. if model_id not in app.state.MODELS:
  1249. raise HTTPException(
  1250. status_code=status.HTTP_404_NOT_FOUND,
  1251. detail="Model not found",
  1252. )
  1253. # Check if the user has a custom task model
  1254. # If the user has a custom task model, use that model
  1255. model_id = get_task_model_id(model_id)
  1256. print(model_id)
  1257. template = '''
  1258. 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., 😊, 😢, 😡, 😱).
  1259. Message: """{{prompt}}"""
  1260. '''
  1261. content = title_generation_template(
  1262. template,
  1263. form_data["prompt"],
  1264. {
  1265. "name": user.name,
  1266. "location": user.info.get("location") if user.info else None,
  1267. },
  1268. )
  1269. payload = {
  1270. "model": model_id,
  1271. "messages": [{"role": "user", "content": content}],
  1272. "stream": False,
  1273. "max_tokens": 4,
  1274. "chat_id": form_data.get("chat_id", None),
  1275. "metadata": {"task": str(TASKS.EMOJI_GENERATION)},
  1276. }
  1277. log.debug(payload)
  1278. try:
  1279. payload = filter_pipeline(payload, user)
  1280. except Exception as e:
  1281. return JSONResponse(
  1282. status_code=e.args[0],
  1283. content={"detail": e.args[1]},
  1284. )
  1285. if "chat_id" in payload:
  1286. del payload["chat_id"]
  1287. return await generate_chat_completions(form_data=payload, user=user)
  1288. ##################################
  1289. #
  1290. # Pipelines Endpoints
  1291. #
  1292. ##################################
  1293. # TODO: Refactor pipelines API endpoints below into a separate file
  1294. @app.get("/api/pipelines/list")
  1295. async def get_pipelines_list(user=Depends(get_admin_user)):
  1296. responses = await get_openai_models(raw=True)
  1297. print(responses)
  1298. urlIdxs = [
  1299. idx
  1300. for idx, response in enumerate(responses)
  1301. if response is not None and "pipelines" in response
  1302. ]
  1303. return {
  1304. "data": [
  1305. {
  1306. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1307. "idx": urlIdx,
  1308. }
  1309. for urlIdx in urlIdxs
  1310. ]
  1311. }
  1312. @app.post("/api/pipelines/upload")
  1313. async def upload_pipeline(
  1314. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1315. ):
  1316. print("upload_pipeline", urlIdx, file.filename)
  1317. # Check if the uploaded file is a python file
  1318. if not file.filename.endswith(".py"):
  1319. raise HTTPException(
  1320. status_code=status.HTTP_400_BAD_REQUEST,
  1321. detail="Only Python (.py) files are allowed.",
  1322. )
  1323. upload_folder = f"{CACHE_DIR}/pipelines"
  1324. os.makedirs(upload_folder, exist_ok=True)
  1325. file_path = os.path.join(upload_folder, file.filename)
  1326. r = None
  1327. try:
  1328. # Save the uploaded file
  1329. with open(file_path, "wb") as buffer:
  1330. shutil.copyfileobj(file.file, buffer)
  1331. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1332. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1333. headers = {"Authorization": f"Bearer {key}"}
  1334. with open(file_path, "rb") as f:
  1335. files = {"file": f}
  1336. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1337. r.raise_for_status()
  1338. data = r.json()
  1339. return {**data}
  1340. except Exception as e:
  1341. # Handle connection error here
  1342. print(f"Connection error: {e}")
  1343. detail = "Pipeline not found"
  1344. status_code = status.HTTP_404_NOT_FOUND
  1345. if r is not None:
  1346. status_code = r.status_code
  1347. try:
  1348. res = r.json()
  1349. if "detail" in res:
  1350. detail = res["detail"]
  1351. except Exception:
  1352. pass
  1353. raise HTTPException(
  1354. status_code=status_code,
  1355. detail=detail,
  1356. )
  1357. finally:
  1358. # Ensure the file is deleted after the upload is completed or on failure
  1359. if os.path.exists(file_path):
  1360. os.remove(file_path)
  1361. class AddPipelineForm(BaseModel):
  1362. url: str
  1363. urlIdx: int
  1364. @app.post("/api/pipelines/add")
  1365. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1366. r = None
  1367. try:
  1368. urlIdx = form_data.urlIdx
  1369. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1370. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1371. headers = {"Authorization": f"Bearer {key}"}
  1372. r = requests.post(
  1373. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1374. )
  1375. r.raise_for_status()
  1376. data = r.json()
  1377. return {**data}
  1378. except Exception as e:
  1379. # Handle connection error here
  1380. print(f"Connection error: {e}")
  1381. detail = "Pipeline not found"
  1382. if r is not None:
  1383. try:
  1384. res = r.json()
  1385. if "detail" in res:
  1386. detail = res["detail"]
  1387. except Exception:
  1388. pass
  1389. raise HTTPException(
  1390. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1391. detail=detail,
  1392. )
  1393. class DeletePipelineForm(BaseModel):
  1394. id: str
  1395. urlIdx: int
  1396. @app.delete("/api/pipelines/delete")
  1397. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1398. r = None
  1399. try:
  1400. urlIdx = form_data.urlIdx
  1401. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1402. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1403. headers = {"Authorization": f"Bearer {key}"}
  1404. r = requests.delete(
  1405. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1406. )
  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")
  1426. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1427. r = None
  1428. try:
  1429. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1430. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1431. headers = {"Authorization": f"Bearer {key}"}
  1432. r = requests.get(f"{url}/pipelines", headers=headers)
  1433. r.raise_for_status()
  1434. data = r.json()
  1435. return {**data}
  1436. except Exception as e:
  1437. # Handle connection error here
  1438. print(f"Connection error: {e}")
  1439. detail = "Pipeline not found"
  1440. if r is not None:
  1441. try:
  1442. res = r.json()
  1443. if "detail" in res:
  1444. detail = res["detail"]
  1445. except Exception:
  1446. pass
  1447. raise HTTPException(
  1448. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1449. detail=detail,
  1450. )
  1451. @app.get("/api/pipelines/{pipeline_id}/valves")
  1452. async def get_pipeline_valves(
  1453. urlIdx: Optional[int],
  1454. pipeline_id: str,
  1455. user=Depends(get_admin_user),
  1456. ):
  1457. r = None
  1458. try:
  1459. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1460. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1461. headers = {"Authorization": f"Bearer {key}"}
  1462. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1463. r.raise_for_status()
  1464. data = r.json()
  1465. return {**data}
  1466. except Exception as e:
  1467. # Handle connection error here
  1468. print(f"Connection error: {e}")
  1469. detail = "Pipeline not found"
  1470. if r is not None:
  1471. try:
  1472. res = r.json()
  1473. if "detail" in res:
  1474. detail = res["detail"]
  1475. except Exception:
  1476. pass
  1477. raise HTTPException(
  1478. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1479. detail=detail,
  1480. )
  1481. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1482. async def get_pipeline_valves_spec(
  1483. urlIdx: Optional[int],
  1484. pipeline_id: str,
  1485. user=Depends(get_admin_user),
  1486. ):
  1487. r = None
  1488. try:
  1489. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1490. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1491. headers = {"Authorization": f"Bearer {key}"}
  1492. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1493. r.raise_for_status()
  1494. data = r.json()
  1495. return {**data}
  1496. except Exception as e:
  1497. # Handle connection error here
  1498. print(f"Connection error: {e}")
  1499. detail = "Pipeline not found"
  1500. if r is not None:
  1501. try:
  1502. res = r.json()
  1503. if "detail" in res:
  1504. detail = res["detail"]
  1505. except Exception:
  1506. pass
  1507. raise HTTPException(
  1508. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1509. detail=detail,
  1510. )
  1511. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1512. async def update_pipeline_valves(
  1513. urlIdx: Optional[int],
  1514. pipeline_id: str,
  1515. form_data: dict,
  1516. user=Depends(get_admin_user),
  1517. ):
  1518. r = None
  1519. try:
  1520. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1521. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1522. headers = {"Authorization": f"Bearer {key}"}
  1523. r = requests.post(
  1524. f"{url}/{pipeline_id}/valves/update",
  1525. headers=headers,
  1526. json={**form_data},
  1527. )
  1528. r.raise_for_status()
  1529. data = r.json()
  1530. return {**data}
  1531. except Exception as e:
  1532. # Handle connection error here
  1533. print(f"Connection error: {e}")
  1534. detail = "Pipeline not found"
  1535. if r is not None:
  1536. try:
  1537. res = r.json()
  1538. if "detail" in res:
  1539. detail = res["detail"]
  1540. except Exception:
  1541. pass
  1542. raise HTTPException(
  1543. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1544. detail=detail,
  1545. )
  1546. ##################################
  1547. #
  1548. # Config Endpoints
  1549. #
  1550. ##################################
  1551. @app.get("/api/config")
  1552. async def get_app_config():
  1553. return {
  1554. "status": True,
  1555. "name": WEBUI_NAME,
  1556. "version": VERSION,
  1557. "default_locale": str(DEFAULT_LOCALE),
  1558. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1559. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1560. "features": {
  1561. "auth": WEBUI_AUTH,
  1562. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1563. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1564. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1565. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1566. "enable_image_generation": images_app.state.config.ENABLED,
  1567. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1568. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1569. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1570. },
  1571. "audio": {
  1572. "tts": {
  1573. "engine": audio_app.state.config.TTS_ENGINE,
  1574. "voice": audio_app.state.config.TTS_VOICE,
  1575. },
  1576. "stt": {
  1577. "engine": audio_app.state.config.STT_ENGINE,
  1578. },
  1579. },
  1580. "oauth": {
  1581. "providers": {
  1582. name: config.get("name", name)
  1583. for name, config in OAUTH_PROVIDERS.items()
  1584. }
  1585. },
  1586. }
  1587. @app.get("/api/config/model/filter")
  1588. async def get_model_filter_config(user=Depends(get_admin_user)):
  1589. return {
  1590. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1591. "models": app.state.config.MODEL_FILTER_LIST,
  1592. }
  1593. class ModelFilterConfigForm(BaseModel):
  1594. enabled: bool
  1595. models: list[str]
  1596. @app.post("/api/config/model/filter")
  1597. async def update_model_filter_config(
  1598. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1599. ):
  1600. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1601. app.state.config.MODEL_FILTER_LIST = form_data.models
  1602. return {
  1603. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1604. "models": app.state.config.MODEL_FILTER_LIST,
  1605. }
  1606. # TODO: webhook endpoint should be under config endpoints
  1607. @app.get("/api/webhook")
  1608. async def get_webhook_url(user=Depends(get_admin_user)):
  1609. return {
  1610. "url": app.state.config.WEBHOOK_URL,
  1611. }
  1612. class UrlForm(BaseModel):
  1613. url: str
  1614. @app.post("/api/webhook")
  1615. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1616. app.state.config.WEBHOOK_URL = form_data.url
  1617. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1618. return {"url": app.state.config.WEBHOOK_URL}
  1619. @app.get("/api/version")
  1620. async def get_app_version():
  1621. return {
  1622. "version": VERSION,
  1623. }
  1624. @app.get("/api/changelog")
  1625. async def get_app_changelog():
  1626. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1627. @app.get("/api/version/updates")
  1628. async def get_app_latest_release_version():
  1629. try:
  1630. async with aiohttp.ClientSession(trust_env=True) as session:
  1631. async with session.get(
  1632. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1633. ) as response:
  1634. response.raise_for_status()
  1635. data = await response.json()
  1636. latest_version = data["tag_name"]
  1637. return {"current": VERSION, "latest": latest_version[1:]}
  1638. except aiohttp.ClientError:
  1639. raise HTTPException(
  1640. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1641. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1642. )
  1643. ############################
  1644. # OAuth Login & Callback
  1645. ############################
  1646. oauth = OAuth()
  1647. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1648. oauth.register(
  1649. name=provider_name,
  1650. client_id=provider_config["client_id"],
  1651. client_secret=provider_config["client_secret"],
  1652. server_metadata_url=provider_config["server_metadata_url"],
  1653. client_kwargs={
  1654. "scope": provider_config["scope"],
  1655. },
  1656. redirect_uri=provider_config["redirect_uri"],
  1657. )
  1658. # SessionMiddleware is used by authlib for oauth
  1659. if len(OAUTH_PROVIDERS) > 0:
  1660. app.add_middleware(
  1661. SessionMiddleware,
  1662. secret_key=WEBUI_SECRET_KEY,
  1663. session_cookie="oui-session",
  1664. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1665. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1666. )
  1667. @app.get("/oauth/{provider}/login")
  1668. async def oauth_login(provider: str, request: Request):
  1669. if provider not in OAUTH_PROVIDERS:
  1670. raise HTTPException(404)
  1671. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  1672. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  1673. "oauth_callback", provider=provider
  1674. )
  1675. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1676. # OAuth login logic is as follows:
  1677. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1678. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1679. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1680. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1681. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1682. @app.get("/oauth/{provider}/callback")
  1683. async def oauth_callback(provider: str, request: Request, response: Response):
  1684. if provider not in OAUTH_PROVIDERS:
  1685. raise HTTPException(404)
  1686. client = oauth.create_client(provider)
  1687. try:
  1688. token = await client.authorize_access_token(request)
  1689. except Exception as e:
  1690. log.warning(f"OAuth callback error: {e}")
  1691. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1692. user_data: UserInfo = token["userinfo"]
  1693. sub = user_data.get("sub")
  1694. if not sub:
  1695. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1696. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1697. provider_sub = f"{provider}@{sub}"
  1698. email_claim = webui_app.state.config.OAUTH_EMAIL_CLAIM
  1699. email = user_data.get(email_claim, "").lower()
  1700. # We currently mandate that email addresses are provided
  1701. if not email:
  1702. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1703. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1704. # Check if the user exists
  1705. user = Users.get_user_by_oauth_sub(provider_sub)
  1706. if not user:
  1707. # If the user does not exist, check if merging is enabled
  1708. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1709. # Check if the user exists by email
  1710. user = Users.get_user_by_email(email)
  1711. if user:
  1712. # Update the user with the new oauth sub
  1713. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1714. if not user:
  1715. # If the user does not exist, check if signups are enabled
  1716. if ENABLE_OAUTH_SIGNUP.value:
  1717. # Check if an existing user with the same email already exists
  1718. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1719. if existing_user:
  1720. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1721. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1722. picture_url = user_data.get(picture_claim, "")
  1723. if picture_url:
  1724. # Download the profile image into a base64 string
  1725. try:
  1726. async with aiohttp.ClientSession() as session:
  1727. async with session.get(picture_url) as resp:
  1728. picture = await resp.read()
  1729. base64_encoded_picture = base64.b64encode(picture).decode(
  1730. "utf-8"
  1731. )
  1732. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1733. if guessed_mime_type is None:
  1734. # assume JPG, browsers are tolerant enough of image formats
  1735. guessed_mime_type = "image/jpeg"
  1736. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1737. except Exception as e:
  1738. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1739. picture_url = ""
  1740. if not picture_url:
  1741. picture_url = "/user.png"
  1742. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1743. role = (
  1744. "admin"
  1745. if Users.get_num_users() == 0
  1746. else webui_app.state.config.DEFAULT_USER_ROLE
  1747. )
  1748. user = Auths.insert_new_auth(
  1749. email=email,
  1750. password=get_password_hash(
  1751. str(uuid.uuid4())
  1752. ), # Random password, not used
  1753. name=user_data.get(username_claim, "User"),
  1754. profile_image_url=picture_url,
  1755. role=role,
  1756. oauth_sub=provider_sub,
  1757. )
  1758. if webui_app.state.config.WEBHOOK_URL:
  1759. post_webhook(
  1760. webui_app.state.config.WEBHOOK_URL,
  1761. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1762. {
  1763. "action": "signup",
  1764. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1765. "user": user.model_dump_json(exclude_none=True),
  1766. },
  1767. )
  1768. else:
  1769. raise HTTPException(
  1770. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1771. )
  1772. jwt_token = create_token(
  1773. data={"id": user.id},
  1774. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1775. )
  1776. # Set the cookie token
  1777. response.set_cookie(
  1778. key="token",
  1779. value=jwt_token,
  1780. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1781. )
  1782. # Redirect back to the frontend with the JWT token
  1783. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1784. return RedirectResponse(url=redirect_url)
  1785. @app.get("/manifest.json")
  1786. async def get_manifest_json():
  1787. return {
  1788. "name": WEBUI_NAME,
  1789. "short_name": WEBUI_NAME,
  1790. "start_url": "/",
  1791. "display": "standalone",
  1792. "background_color": "#343541",
  1793. "orientation": "portrait-primary",
  1794. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1795. }
  1796. @app.get("/opensearch.xml")
  1797. async def get_opensearch_xml():
  1798. xml_content = rf"""
  1799. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1800. <ShortName>{WEBUI_NAME}</ShortName>
  1801. <Description>Search {WEBUI_NAME}</Description>
  1802. <InputEncoding>UTF-8</InputEncoding>
  1803. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1804. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1805. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1806. </OpenSearchDescription>
  1807. """
  1808. return Response(content=xml_content, media_type="application/xml")
  1809. @app.get("/health")
  1810. async def healthcheck():
  1811. return {"status": True}
  1812. @app.get("/health/db")
  1813. async def healthcheck_with_db():
  1814. Session.execute(text("SELECT 1;")).all()
  1815. return {"status": True}
  1816. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1817. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1818. if os.path.exists(FRONTEND_BUILD_DIR):
  1819. mimetypes.add_type("text/javascript", ".js")
  1820. app.mount(
  1821. "/",
  1822. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1823. name="spa-static-files",
  1824. )
  1825. else:
  1826. log.warning(
  1827. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1828. )