main.py 73 KB

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