main.py 70 KB

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