main.py 71 KB

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