main.py 72 KB

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