main.py 70 KB

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