main.py 71 KB

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