main.py 70 KB

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