main.py 70 KB

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