main.py 73 KB

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