main.py 66 KB

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