main.py 70 KB

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