main.py 71 KB

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