main.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  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 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. ENABLE_OPENAI_API,
  96. ENABLE_OLLAMA_API,
  97. ENABLE_MODEL_FILTER,
  98. MODEL_FILTER_LIST,
  99. GLOBAL_LOG_LEVEL,
  100. SRC_LOG_LEVELS,
  101. WEBHOOK_URL,
  102. ENABLE_ADMIN_EXPORT,
  103. WEBUI_BUILD_HASH,
  104. TASK_MODEL,
  105. TASK_MODEL_EXTERNAL,
  106. TITLE_GENERATION_PROMPT_TEMPLATE,
  107. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  108. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  109. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  110. SAFE_MODE,
  111. OAUTH_PROVIDERS,
  112. ENABLE_OAUTH_SIGNUP,
  113. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  114. WEBUI_SECRET_KEY,
  115. WEBUI_SESSION_COOKIE_SAME_SITE,
  116. WEBUI_SESSION_COOKIE_SECURE,
  117. AppConfig,
  118. BACKEND_DIR,
  119. DATABASE_URL,
  120. )
  121. from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  122. from utils.webhook import post_webhook
  123. if SAFE_MODE:
  124. print("SAFE MODE ENABLED")
  125. Functions.deactivate_all_functions()
  126. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  127. log = logging.getLogger(__name__)
  128. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  129. class SPAStaticFiles(StaticFiles):
  130. async def get_response(self, path: str, scope):
  131. try:
  132. return await super().get_response(path, scope)
  133. except (HTTPException, StarletteHTTPException) as ex:
  134. if ex.status_code == 404:
  135. return await super().get_response("index.html", scope)
  136. else:
  137. raise ex
  138. print(
  139. rf"""
  140. ___ __ __ _ _ _ ___
  141. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  142. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  143. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  144. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  145. |_|
  146. v{VERSION} - building the best open-source AI user interface.
  147. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  148. https://github.com/open-webui/open-webui
  149. """
  150. )
  151. def run_migrations():
  152. env = os.environ.copy()
  153. env["DATABASE_URL"] = DATABASE_URL
  154. migration_task = subprocess.run(
  155. ["alembic", f"-c{BACKEND_DIR}/alembic.ini", "upgrade", "head"], env=env
  156. )
  157. if migration_task.returncode > 0:
  158. raise ValueError("Error running migrations")
  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. )
  630. try:
  631. data = filter_pipeline(data, user)
  632. except Exception as e:
  633. return JSONResponse(
  634. status_code=e.args[0],
  635. content={"detail": e.args[1]},
  636. )
  637. modified_body_bytes = json.dumps(data).encode("utf-8")
  638. # Replace the request body with the modified one
  639. request._body = modified_body_bytes
  640. # Set custom header to ensure content-length matches new body length
  641. request.headers.__dict__["_list"] = [
  642. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  643. *[
  644. (k, v)
  645. for k, v in request.headers.raw
  646. if k.lower() != b"content-length"
  647. ],
  648. ]
  649. response = await call_next(request)
  650. return response
  651. async def _receive(self, body: bytes):
  652. return {"type": "http.request", "body": body, "more_body": False}
  653. app.add_middleware(PipelineMiddleware)
  654. app.add_middleware(
  655. CORSMiddleware,
  656. allow_origins=origins,
  657. allow_credentials=True,
  658. allow_methods=["*"],
  659. allow_headers=["*"],
  660. )
  661. @app.middleware("http")
  662. async def commit_session_after_request(request: Request, call_next):
  663. response = await call_next(request)
  664. log.debug("Commit session after request")
  665. Session.commit()
  666. return response
  667. @app.middleware("http")
  668. async def check_url(request: Request, call_next):
  669. if len(app.state.MODELS) == 0:
  670. await get_all_models()
  671. else:
  672. pass
  673. start_time = int(time.time())
  674. response = await call_next(request)
  675. process_time = int(time.time()) - start_time
  676. response.headers["X-Process-Time"] = str(process_time)
  677. return response
  678. @app.middleware("http")
  679. async def update_embedding_function(request: Request, call_next):
  680. response = await call_next(request)
  681. if "/embedding/update" in request.url.path:
  682. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  683. return response
  684. app.mount("/ws", socket_app)
  685. app.mount("/ollama", ollama_app)
  686. app.mount("/openai", openai_app)
  687. app.mount("/images/api/v1", images_app)
  688. app.mount("/audio/api/v1", audio_app)
  689. app.mount("/rag/api/v1", rag_app)
  690. app.mount("/api/v1", webui_app)
  691. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  692. async def get_all_models():
  693. pipe_models = []
  694. openai_models = []
  695. ollama_models = []
  696. pipe_models = await get_pipe_models()
  697. if app.state.config.ENABLE_OPENAI_API:
  698. openai_models = await get_openai_models()
  699. openai_models = openai_models["data"]
  700. if app.state.config.ENABLE_OLLAMA_API:
  701. ollama_models = await get_ollama_models()
  702. ollama_models = [
  703. {
  704. "id": model["model"],
  705. "name": model["name"],
  706. "object": "model",
  707. "created": int(time.time()),
  708. "owned_by": "ollama",
  709. "ollama": model,
  710. }
  711. for model in ollama_models["models"]
  712. ]
  713. models = pipe_models + openai_models + ollama_models
  714. custom_models = Models.get_all_models()
  715. for custom_model in custom_models:
  716. if custom_model.base_model_id == None:
  717. for model in models:
  718. if (
  719. custom_model.id == model["id"]
  720. or custom_model.id == model["id"].split(":")[0]
  721. ):
  722. model["name"] = custom_model.name
  723. model["info"] = custom_model.model_dump()
  724. else:
  725. owned_by = "openai"
  726. for model in models:
  727. if (
  728. custom_model.base_model_id == model["id"]
  729. or custom_model.base_model_id == model["id"].split(":")[0]
  730. ):
  731. owned_by = model["owned_by"]
  732. break
  733. models.append(
  734. {
  735. "id": custom_model.id,
  736. "name": custom_model.name,
  737. "object": "model",
  738. "created": custom_model.created_at,
  739. "owned_by": owned_by,
  740. "info": custom_model.model_dump(),
  741. "preset": True,
  742. }
  743. )
  744. app.state.MODELS = {model["id"]: model for model in models}
  745. webui_app.state.MODELS = app.state.MODELS
  746. return models
  747. @app.get("/api/models")
  748. async def get_models(user=Depends(get_verified_user)):
  749. models = await get_all_models()
  750. # Filter out filter pipelines
  751. models = [
  752. model
  753. for model in models
  754. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  755. ]
  756. if app.state.config.ENABLE_MODEL_FILTER:
  757. if user.role == "user":
  758. models = list(
  759. filter(
  760. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  761. models,
  762. )
  763. )
  764. return {"data": models}
  765. return {"data": models}
  766. @app.post("/api/chat/completions")
  767. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  768. model_id = form_data["model"]
  769. if model_id not in app.state.MODELS:
  770. raise HTTPException(
  771. status_code=status.HTTP_404_NOT_FOUND,
  772. detail="Model not found",
  773. )
  774. model = app.state.MODELS[model_id]
  775. print(model)
  776. pipe = model.get("pipe")
  777. if pipe:
  778. return await generate_function_chat_completion(form_data, user=user)
  779. if model["owned_by"] == "ollama":
  780. return await generate_ollama_chat_completion(form_data, user=user)
  781. else:
  782. return await generate_openai_chat_completion(form_data, user=user)
  783. @app.post("/api/chat/completed")
  784. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  785. data = form_data
  786. model_id = data["model"]
  787. if model_id not in app.state.MODELS:
  788. raise HTTPException(
  789. status_code=status.HTTP_404_NOT_FOUND,
  790. detail="Model not found",
  791. )
  792. model = app.state.MODELS[model_id]
  793. filters = [
  794. model
  795. for model in app.state.MODELS.values()
  796. if "pipeline" in model
  797. and "type" in model["pipeline"]
  798. and model["pipeline"]["type"] == "filter"
  799. and (
  800. model["pipeline"]["pipelines"] == ["*"]
  801. or any(
  802. model_id == target_model_id
  803. for target_model_id in model["pipeline"]["pipelines"]
  804. )
  805. )
  806. ]
  807. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  808. if "pipeline" in model:
  809. sorted_filters = [model] + sorted_filters
  810. for filter in sorted_filters:
  811. r = None
  812. try:
  813. urlIdx = filter["urlIdx"]
  814. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  815. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  816. if key != "":
  817. headers = {"Authorization": f"Bearer {key}"}
  818. r = requests.post(
  819. f"{url}/{filter['id']}/filter/outlet",
  820. headers=headers,
  821. json={
  822. "user": {
  823. "id": user.id,
  824. "name": user.name,
  825. "email": user.email,
  826. "role": user.role,
  827. },
  828. "body": data,
  829. },
  830. )
  831. r.raise_for_status()
  832. data = r.json()
  833. except Exception as e:
  834. # Handle connection error here
  835. print(f"Connection error: {e}")
  836. if r is not None:
  837. try:
  838. res = r.json()
  839. if "detail" in res:
  840. return JSONResponse(
  841. status_code=r.status_code,
  842. content=res,
  843. )
  844. except:
  845. pass
  846. else:
  847. pass
  848. def get_priority(function_id):
  849. function = Functions.get_function_by_id(function_id)
  850. if function is not None and hasattr(function, "valves"):
  851. return (function.valves if function.valves else {}).get("priority", 0)
  852. return 0
  853. filter_ids = [
  854. function.id
  855. for function in Functions.get_functions_by_type("filter", active_only=True)
  856. ]
  857. # Check if the model has any filters
  858. if "info" in model and "meta" in model["info"]:
  859. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  860. filter_ids = list(set(filter_ids))
  861. # Sort filter_ids by priority, using the get_priority function
  862. filter_ids.sort(key=get_priority)
  863. for filter_id in filter_ids:
  864. filter = Functions.get_function_by_id(filter_id)
  865. if filter:
  866. if filter_id in webui_app.state.FUNCTIONS:
  867. function_module = webui_app.state.FUNCTIONS[filter_id]
  868. else:
  869. function_module, function_type, frontmatter = (
  870. load_function_module_by_id(filter_id)
  871. )
  872. webui_app.state.FUNCTIONS[filter_id] = function_module
  873. if hasattr(function_module, "valves") and hasattr(
  874. function_module, "Valves"
  875. ):
  876. valves = Functions.get_function_valves_by_id(filter_id)
  877. function_module.valves = function_module.Valves(
  878. **(valves if valves else {})
  879. )
  880. try:
  881. if hasattr(function_module, "outlet"):
  882. outlet = function_module.outlet
  883. # Get the signature of the function
  884. sig = inspect.signature(outlet)
  885. params = {"body": data}
  886. if "__user__" in sig.parameters:
  887. __user__ = {
  888. "id": user.id,
  889. "email": user.email,
  890. "name": user.name,
  891. "role": user.role,
  892. }
  893. try:
  894. if hasattr(function_module, "UserValves"):
  895. __user__["valves"] = function_module.UserValves(
  896. **Functions.get_user_valves_by_id_and_user_id(
  897. filter_id, user.id
  898. )
  899. )
  900. except Exception as e:
  901. print(e)
  902. params = {**params, "__user__": __user__}
  903. if "__id__" in sig.parameters:
  904. params = {
  905. **params,
  906. "__id__": filter_id,
  907. }
  908. if inspect.iscoroutinefunction(outlet):
  909. data = await outlet(**params)
  910. else:
  911. data = outlet(**params)
  912. except Exception as e:
  913. print(f"Error: {e}")
  914. return JSONResponse(
  915. status_code=status.HTTP_400_BAD_REQUEST,
  916. content={"detail": str(e)},
  917. )
  918. return data
  919. ##################################
  920. #
  921. # Task Endpoints
  922. #
  923. ##################################
  924. # TODO: Refactor task API endpoints below into a separate file
  925. @app.get("/api/task/config")
  926. async def get_task_config(user=Depends(get_verified_user)):
  927. return {
  928. "TASK_MODEL": app.state.config.TASK_MODEL,
  929. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  930. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  931. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  932. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  933. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  934. }
  935. class TaskConfigForm(BaseModel):
  936. TASK_MODEL: Optional[str]
  937. TASK_MODEL_EXTERNAL: Optional[str]
  938. TITLE_GENERATION_PROMPT_TEMPLATE: str
  939. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  940. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  941. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  942. @app.post("/api/task/config/update")
  943. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  944. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  945. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  946. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  947. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  948. )
  949. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  950. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  951. )
  952. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  953. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  954. )
  955. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  956. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  957. )
  958. return {
  959. "TASK_MODEL": app.state.config.TASK_MODEL,
  960. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  961. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  962. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  963. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  964. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  965. }
  966. @app.post("/api/task/title/completions")
  967. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  968. print("generate_title")
  969. model_id = form_data["model"]
  970. if model_id not in app.state.MODELS:
  971. raise HTTPException(
  972. status_code=status.HTTP_404_NOT_FOUND,
  973. detail="Model not found",
  974. )
  975. # Check if the user has a custom task model
  976. # If the user has a custom task model, use that model
  977. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  978. if app.state.config.TASK_MODEL:
  979. task_model_id = app.state.config.TASK_MODEL
  980. if task_model_id in app.state.MODELS:
  981. model_id = task_model_id
  982. else:
  983. if app.state.config.TASK_MODEL_EXTERNAL:
  984. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  985. if task_model_id in app.state.MODELS:
  986. model_id = task_model_id
  987. print(model_id)
  988. model = app.state.MODELS[model_id]
  989. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  990. content = title_generation_template(
  991. template,
  992. form_data["prompt"],
  993. {
  994. "name": user.name,
  995. "location": user.info.get("location") if user.info else None,
  996. },
  997. )
  998. payload = {
  999. "model": model_id,
  1000. "messages": [{"role": "user", "content": content}],
  1001. "stream": False,
  1002. "max_tokens": 50,
  1003. "chat_id": form_data.get("chat_id", None),
  1004. "title": True,
  1005. }
  1006. log.debug(payload)
  1007. try:
  1008. payload = filter_pipeline(payload, user)
  1009. except Exception as e:
  1010. return JSONResponse(
  1011. status_code=e.args[0],
  1012. content={"detail": e.args[1]},
  1013. )
  1014. return await generate_chat_completions(form_data=payload, user=user)
  1015. @app.post("/api/task/query/completions")
  1016. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1017. print("generate_search_query")
  1018. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1019. raise HTTPException(
  1020. status_code=status.HTTP_400_BAD_REQUEST,
  1021. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1022. )
  1023. model_id = form_data["model"]
  1024. if model_id not in app.state.MODELS:
  1025. raise HTTPException(
  1026. status_code=status.HTTP_404_NOT_FOUND,
  1027. detail="Model not found",
  1028. )
  1029. # Check if the user has a custom task model
  1030. # If the user has a custom task model, use that model
  1031. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1032. if app.state.config.TASK_MODEL:
  1033. task_model_id = app.state.config.TASK_MODEL
  1034. if task_model_id in app.state.MODELS:
  1035. model_id = task_model_id
  1036. else:
  1037. if app.state.config.TASK_MODEL_EXTERNAL:
  1038. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1039. if task_model_id in app.state.MODELS:
  1040. model_id = task_model_id
  1041. print(model_id)
  1042. model = app.state.MODELS[model_id]
  1043. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1044. content = search_query_generation_template(
  1045. template, form_data["prompt"], {"name": user.name}
  1046. )
  1047. payload = {
  1048. "model": model_id,
  1049. "messages": [{"role": "user", "content": content}],
  1050. "stream": False,
  1051. "max_tokens": 30,
  1052. "task": True,
  1053. }
  1054. print(payload)
  1055. try:
  1056. payload = filter_pipeline(payload, user)
  1057. except Exception as e:
  1058. return JSONResponse(
  1059. status_code=e.args[0],
  1060. content={"detail": e.args[1]},
  1061. )
  1062. return await generate_chat_completions(form_data=payload, user=user)
  1063. @app.post("/api/task/emoji/completions")
  1064. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1065. print("generate_emoji")
  1066. model_id = form_data["model"]
  1067. if model_id not in app.state.MODELS:
  1068. raise HTTPException(
  1069. status_code=status.HTTP_404_NOT_FOUND,
  1070. detail="Model not found",
  1071. )
  1072. # Check if the user has a custom task model
  1073. # If the user has a custom task model, use that model
  1074. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1075. if app.state.config.TASK_MODEL:
  1076. task_model_id = app.state.config.TASK_MODEL
  1077. if task_model_id in app.state.MODELS:
  1078. model_id = task_model_id
  1079. else:
  1080. if app.state.config.TASK_MODEL_EXTERNAL:
  1081. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1082. if task_model_id in app.state.MODELS:
  1083. model_id = task_model_id
  1084. print(model_id)
  1085. model = app.state.MODELS[model_id]
  1086. template = '''
  1087. 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., 😊, 😢, 😡, 😱).
  1088. Message: """{{prompt}}"""
  1089. '''
  1090. content = title_generation_template(
  1091. template,
  1092. form_data["prompt"],
  1093. {
  1094. "name": user.name,
  1095. "location": user.info.get("location") if user.info else None,
  1096. },
  1097. )
  1098. payload = {
  1099. "model": model_id,
  1100. "messages": [{"role": "user", "content": content}],
  1101. "stream": False,
  1102. "max_tokens": 4,
  1103. "chat_id": form_data.get("chat_id", None),
  1104. "task": True,
  1105. }
  1106. log.debug(payload)
  1107. try:
  1108. payload = filter_pipeline(payload, user)
  1109. except Exception as e:
  1110. return JSONResponse(
  1111. status_code=e.args[0],
  1112. content={"detail": e.args[1]},
  1113. )
  1114. return await generate_chat_completions(form_data=payload, user=user)
  1115. @app.post("/api/task/tools/completions")
  1116. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  1117. print("get_tools_function_calling")
  1118. model_id = form_data["model"]
  1119. if model_id not in app.state.MODELS:
  1120. raise HTTPException(
  1121. status_code=status.HTTP_404_NOT_FOUND,
  1122. detail="Model not found",
  1123. )
  1124. # Check if the user has a custom task model
  1125. # If the user has a custom task model, use that model
  1126. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1127. if app.state.config.TASK_MODEL:
  1128. task_model_id = app.state.config.TASK_MODEL
  1129. if task_model_id in app.state.MODELS:
  1130. model_id = task_model_id
  1131. else:
  1132. if app.state.config.TASK_MODEL_EXTERNAL:
  1133. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1134. if task_model_id in app.state.MODELS:
  1135. model_id = task_model_id
  1136. print(model_id)
  1137. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1138. try:
  1139. context, citation, file_handler = await get_function_call_response(
  1140. form_data["messages"],
  1141. form_data.get("files", []),
  1142. form_data["tool_id"],
  1143. template,
  1144. model_id,
  1145. user,
  1146. )
  1147. return context
  1148. except Exception as e:
  1149. return JSONResponse(
  1150. status_code=e.args[0],
  1151. content={"detail": e.args[1]},
  1152. )
  1153. ##################################
  1154. #
  1155. # Pipelines Endpoints
  1156. #
  1157. ##################################
  1158. # TODO: Refactor pipelines API endpoints below into a separate file
  1159. @app.get("/api/pipelines/list")
  1160. async def get_pipelines_list(user=Depends(get_admin_user)):
  1161. responses = await get_openai_models(raw=True)
  1162. print(responses)
  1163. urlIdxs = [
  1164. idx
  1165. for idx, response in enumerate(responses)
  1166. if response != None and "pipelines" in response
  1167. ]
  1168. return {
  1169. "data": [
  1170. {
  1171. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1172. "idx": urlIdx,
  1173. }
  1174. for urlIdx in urlIdxs
  1175. ]
  1176. }
  1177. @app.post("/api/pipelines/upload")
  1178. async def upload_pipeline(
  1179. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1180. ):
  1181. print("upload_pipeline", urlIdx, file.filename)
  1182. # Check if the uploaded file is a python file
  1183. if not file.filename.endswith(".py"):
  1184. raise HTTPException(
  1185. status_code=status.HTTP_400_BAD_REQUEST,
  1186. detail="Only Python (.py) files are allowed.",
  1187. )
  1188. upload_folder = f"{CACHE_DIR}/pipelines"
  1189. os.makedirs(upload_folder, exist_ok=True)
  1190. file_path = os.path.join(upload_folder, file.filename)
  1191. try:
  1192. # Save the uploaded file
  1193. with open(file_path, "wb") as buffer:
  1194. shutil.copyfileobj(file.file, buffer)
  1195. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1196. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1197. headers = {"Authorization": f"Bearer {key}"}
  1198. with open(file_path, "rb") as f:
  1199. files = {"file": f}
  1200. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1201. r.raise_for_status()
  1202. data = r.json()
  1203. return {**data}
  1204. except Exception as e:
  1205. # Handle connection error here
  1206. print(f"Connection error: {e}")
  1207. detail = "Pipeline not found"
  1208. if r is not None:
  1209. try:
  1210. res = r.json()
  1211. if "detail" in res:
  1212. detail = res["detail"]
  1213. except:
  1214. pass
  1215. raise HTTPException(
  1216. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1217. detail=detail,
  1218. )
  1219. finally:
  1220. # Ensure the file is deleted after the upload is completed or on failure
  1221. if os.path.exists(file_path):
  1222. os.remove(file_path)
  1223. class AddPipelineForm(BaseModel):
  1224. url: str
  1225. urlIdx: int
  1226. @app.post("/api/pipelines/add")
  1227. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1228. r = None
  1229. try:
  1230. urlIdx = form_data.urlIdx
  1231. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1232. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1233. headers = {"Authorization": f"Bearer {key}"}
  1234. r = requests.post(
  1235. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1236. )
  1237. r.raise_for_status()
  1238. data = r.json()
  1239. return {**data}
  1240. except Exception as e:
  1241. # Handle connection error here
  1242. print(f"Connection error: {e}")
  1243. detail = "Pipeline not found"
  1244. if r is not None:
  1245. try:
  1246. res = r.json()
  1247. if "detail" in res:
  1248. detail = res["detail"]
  1249. except:
  1250. pass
  1251. raise HTTPException(
  1252. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1253. detail=detail,
  1254. )
  1255. class DeletePipelineForm(BaseModel):
  1256. id: str
  1257. urlIdx: int
  1258. @app.delete("/api/pipelines/delete")
  1259. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1260. r = None
  1261. try:
  1262. urlIdx = form_data.urlIdx
  1263. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1264. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1265. headers = {"Authorization": f"Bearer {key}"}
  1266. r = requests.delete(
  1267. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1268. )
  1269. r.raise_for_status()
  1270. data = r.json()
  1271. return {**data}
  1272. except Exception as e:
  1273. # Handle connection error here
  1274. print(f"Connection error: {e}")
  1275. detail = "Pipeline not found"
  1276. if r is not None:
  1277. try:
  1278. res = r.json()
  1279. if "detail" in res:
  1280. detail = res["detail"]
  1281. except:
  1282. pass
  1283. raise HTTPException(
  1284. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1285. detail=detail,
  1286. )
  1287. @app.get("/api/pipelines")
  1288. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1289. r = None
  1290. try:
  1291. urlIdx
  1292. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1293. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1294. headers = {"Authorization": f"Bearer {key}"}
  1295. r = requests.get(f"{url}/pipelines", headers=headers)
  1296. r.raise_for_status()
  1297. data = r.json()
  1298. return {**data}
  1299. except Exception as e:
  1300. # Handle connection error here
  1301. print(f"Connection error: {e}")
  1302. detail = "Pipeline not found"
  1303. if r is not None:
  1304. try:
  1305. res = r.json()
  1306. if "detail" in res:
  1307. detail = res["detail"]
  1308. except:
  1309. pass
  1310. raise HTTPException(
  1311. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1312. detail=detail,
  1313. )
  1314. @app.get("/api/pipelines/{pipeline_id}/valves")
  1315. async def get_pipeline_valves(
  1316. urlIdx: Optional[int],
  1317. pipeline_id: str,
  1318. user=Depends(get_admin_user),
  1319. ):
  1320. models = await get_all_models()
  1321. r = None
  1322. try:
  1323. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1324. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1325. headers = {"Authorization": f"Bearer {key}"}
  1326. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1327. r.raise_for_status()
  1328. data = r.json()
  1329. return {**data}
  1330. except Exception as e:
  1331. # Handle connection error here
  1332. print(f"Connection error: {e}")
  1333. detail = "Pipeline not found"
  1334. if r is not None:
  1335. try:
  1336. res = r.json()
  1337. if "detail" in res:
  1338. detail = res["detail"]
  1339. except:
  1340. pass
  1341. raise HTTPException(
  1342. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1343. detail=detail,
  1344. )
  1345. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1346. async def get_pipeline_valves_spec(
  1347. urlIdx: Optional[int],
  1348. pipeline_id: str,
  1349. user=Depends(get_admin_user),
  1350. ):
  1351. models = await get_all_models()
  1352. r = None
  1353. try:
  1354. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1355. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1356. headers = {"Authorization": f"Bearer {key}"}
  1357. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1358. r.raise_for_status()
  1359. data = r.json()
  1360. return {**data}
  1361. except Exception as e:
  1362. # Handle connection error here
  1363. print(f"Connection error: {e}")
  1364. detail = "Pipeline not found"
  1365. if r is not None:
  1366. try:
  1367. res = r.json()
  1368. if "detail" in res:
  1369. detail = res["detail"]
  1370. except:
  1371. pass
  1372. raise HTTPException(
  1373. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1374. detail=detail,
  1375. )
  1376. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1377. async def update_pipeline_valves(
  1378. urlIdx: Optional[int],
  1379. pipeline_id: str,
  1380. form_data: dict,
  1381. user=Depends(get_admin_user),
  1382. ):
  1383. models = await get_all_models()
  1384. r = None
  1385. try:
  1386. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1387. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1388. headers = {"Authorization": f"Bearer {key}"}
  1389. r = requests.post(
  1390. f"{url}/{pipeline_id}/valves/update",
  1391. headers=headers,
  1392. json={**form_data},
  1393. )
  1394. r.raise_for_status()
  1395. data = r.json()
  1396. return {**data}
  1397. except Exception as e:
  1398. # Handle connection error here
  1399. print(f"Connection error: {e}")
  1400. detail = "Pipeline not found"
  1401. if r is not None:
  1402. try:
  1403. res = r.json()
  1404. if "detail" in res:
  1405. detail = res["detail"]
  1406. except:
  1407. pass
  1408. raise HTTPException(
  1409. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1410. detail=detail,
  1411. )
  1412. ##################################
  1413. #
  1414. # Config Endpoints
  1415. #
  1416. ##################################
  1417. @app.get("/api/config")
  1418. async def get_app_config():
  1419. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  1420. default_locale = "en-US"
  1421. if "ui" in CONFIG_DATA:
  1422. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  1423. # The Rest of the Function Now Uses the Variables Defined Above
  1424. return {
  1425. "status": True,
  1426. "name": WEBUI_NAME,
  1427. "version": VERSION,
  1428. "default_locale": default_locale,
  1429. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1430. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1431. "features": {
  1432. "auth": WEBUI_AUTH,
  1433. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1434. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1435. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1436. "enable_image_generation": images_app.state.config.ENABLED,
  1437. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1438. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1439. },
  1440. "audio": {
  1441. "tts": {
  1442. "engine": audio_app.state.config.TTS_ENGINE,
  1443. "voice": audio_app.state.config.TTS_VOICE,
  1444. },
  1445. "stt": {
  1446. "engine": audio_app.state.config.STT_ENGINE,
  1447. },
  1448. },
  1449. "oauth": {
  1450. "providers": {
  1451. name: config.get("name", name)
  1452. for name, config in OAUTH_PROVIDERS.items()
  1453. }
  1454. },
  1455. }
  1456. @app.get("/api/config/model/filter")
  1457. async def get_model_filter_config(user=Depends(get_admin_user)):
  1458. return {
  1459. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1460. "models": app.state.config.MODEL_FILTER_LIST,
  1461. }
  1462. class ModelFilterConfigForm(BaseModel):
  1463. enabled: bool
  1464. models: List[str]
  1465. @app.post("/api/config/model/filter")
  1466. async def update_model_filter_config(
  1467. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1468. ):
  1469. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1470. app.state.config.MODEL_FILTER_LIST = form_data.models
  1471. return {
  1472. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1473. "models": app.state.config.MODEL_FILTER_LIST,
  1474. }
  1475. # TODO: webhook endpoint should be under config endpoints
  1476. @app.get("/api/webhook")
  1477. async def get_webhook_url(user=Depends(get_admin_user)):
  1478. return {
  1479. "url": app.state.config.WEBHOOK_URL,
  1480. }
  1481. class UrlForm(BaseModel):
  1482. url: str
  1483. @app.post("/api/webhook")
  1484. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1485. app.state.config.WEBHOOK_URL = form_data.url
  1486. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1487. return {"url": app.state.config.WEBHOOK_URL}
  1488. @app.get("/api/version")
  1489. async def get_app_config():
  1490. return {
  1491. "version": VERSION,
  1492. }
  1493. @app.get("/api/changelog")
  1494. async def get_app_changelog():
  1495. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1496. @app.get("/api/version/updates")
  1497. async def get_app_latest_release_version():
  1498. try:
  1499. async with aiohttp.ClientSession(trust_env=True) as session:
  1500. async with session.get(
  1501. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1502. ) as response:
  1503. response.raise_for_status()
  1504. data = await response.json()
  1505. latest_version = data["tag_name"]
  1506. return {"current": VERSION, "latest": latest_version[1:]}
  1507. except aiohttp.ClientError as e:
  1508. raise HTTPException(
  1509. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1510. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1511. )
  1512. ############################
  1513. # OAuth Login & Callback
  1514. ############################
  1515. oauth = OAuth()
  1516. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1517. oauth.register(
  1518. name=provider_name,
  1519. client_id=provider_config["client_id"],
  1520. client_secret=provider_config["client_secret"],
  1521. server_metadata_url=provider_config["server_metadata_url"],
  1522. client_kwargs={
  1523. "scope": provider_config["scope"],
  1524. },
  1525. )
  1526. # SessionMiddleware is used by authlib for oauth
  1527. if len(OAUTH_PROVIDERS) > 0:
  1528. app.add_middleware(
  1529. SessionMiddleware,
  1530. secret_key=WEBUI_SECRET_KEY,
  1531. session_cookie="oui-session",
  1532. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1533. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1534. )
  1535. @app.get("/oauth/{provider}/login")
  1536. async def oauth_login(provider: str, request: Request):
  1537. if provider not in OAUTH_PROVIDERS:
  1538. raise HTTPException(404)
  1539. redirect_uri = request.url_for("oauth_callback", provider=provider)
  1540. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1541. # OAuth login logic is as follows:
  1542. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1543. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1544. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1545. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1546. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1547. @app.get("/oauth/{provider}/callback")
  1548. async def oauth_callback(provider: str, request: Request, response: Response):
  1549. if provider not in OAUTH_PROVIDERS:
  1550. raise HTTPException(404)
  1551. client = oauth.create_client(provider)
  1552. try:
  1553. token = await client.authorize_access_token(request)
  1554. except Exception as e:
  1555. log.warning(f"OAuth callback error: {e}")
  1556. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1557. user_data: UserInfo = token["userinfo"]
  1558. sub = user_data.get("sub")
  1559. if not sub:
  1560. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1561. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1562. provider_sub = f"{provider}@{sub}"
  1563. email = user_data.get("email", "").lower()
  1564. # We currently mandate that email addresses are provided
  1565. if not email:
  1566. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1567. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1568. # Check if the user exists
  1569. user = Users.get_user_by_oauth_sub(provider_sub)
  1570. if not user:
  1571. # If the user does not exist, check if merging is enabled
  1572. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1573. # Check if the user exists by email
  1574. user = Users.get_user_by_email(email)
  1575. if user:
  1576. # Update the user with the new oauth sub
  1577. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1578. if not user:
  1579. # If the user does not exist, check if signups are enabled
  1580. if ENABLE_OAUTH_SIGNUP.value:
  1581. # Check if an existing user with the same email already exists
  1582. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1583. if existing_user:
  1584. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1585. picture_url = user_data.get("picture", "")
  1586. if picture_url:
  1587. # Download the profile image into a base64 string
  1588. try:
  1589. async with aiohttp.ClientSession() as session:
  1590. async with session.get(picture_url) as resp:
  1591. picture = await resp.read()
  1592. base64_encoded_picture = base64.b64encode(picture).decode(
  1593. "utf-8"
  1594. )
  1595. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1596. if guessed_mime_type is None:
  1597. # assume JPG, browsers are tolerant enough of image formats
  1598. guessed_mime_type = "image/jpeg"
  1599. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1600. except Exception as e:
  1601. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1602. picture_url = ""
  1603. if not picture_url:
  1604. picture_url = "/user.png"
  1605. user = Auths.insert_new_auth(
  1606. email=email,
  1607. password=get_password_hash(
  1608. str(uuid.uuid4())
  1609. ), # Random password, not used
  1610. name=user_data.get("name", "User"),
  1611. profile_image_url=picture_url,
  1612. role=webui_app.state.config.DEFAULT_USER_ROLE,
  1613. oauth_sub=provider_sub,
  1614. )
  1615. if webui_app.state.config.WEBHOOK_URL:
  1616. post_webhook(
  1617. webui_app.state.config.WEBHOOK_URL,
  1618. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1619. {
  1620. "action": "signup",
  1621. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1622. "user": user.model_dump_json(exclude_none=True),
  1623. },
  1624. )
  1625. else:
  1626. raise HTTPException(
  1627. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1628. )
  1629. jwt_token = create_token(
  1630. data={"id": user.id},
  1631. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1632. )
  1633. # Set the cookie token
  1634. response.set_cookie(
  1635. key="token",
  1636. value=token,
  1637. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1638. )
  1639. # Redirect back to the frontend with the JWT token
  1640. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1641. return RedirectResponse(url=redirect_url)
  1642. @app.get("/manifest.json")
  1643. async def get_manifest_json():
  1644. return {
  1645. "name": WEBUI_NAME,
  1646. "short_name": WEBUI_NAME,
  1647. "start_url": "/",
  1648. "display": "standalone",
  1649. "background_color": "#343541",
  1650. "orientation": "portrait-primary",
  1651. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1652. }
  1653. @app.get("/opensearch.xml")
  1654. async def get_opensearch_xml():
  1655. xml_content = rf"""
  1656. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1657. <ShortName>{WEBUI_NAME}</ShortName>
  1658. <Description>Search {WEBUI_NAME}</Description>
  1659. <InputEncoding>UTF-8</InputEncoding>
  1660. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1661. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1662. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1663. </OpenSearchDescription>
  1664. """
  1665. return Response(content=xml_content, media_type="application/xml")
  1666. @app.get("/health")
  1667. async def healthcheck():
  1668. return {"status": True}
  1669. @app.get("/health/db")
  1670. async def healthcheck_with_db():
  1671. Session.execute(text("SELECT 1;")).all()
  1672. return {"status": True}
  1673. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1674. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1675. if os.path.exists(FRONTEND_BUILD_DIR):
  1676. mimetypes.add_type("text/javascript", ".js")
  1677. app.mount(
  1678. "/",
  1679. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1680. name="spa-static-files",
  1681. )
  1682. else:
  1683. log.warning(
  1684. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1685. )