main.py 72 KB

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