main.py 71 KB

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