main.py 71 KB

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