main.py 71 KB

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