main.py 70 KB

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