main.py 72 KB

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