main.py 70 KB

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