main.py 73 KB

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