main.py 66 KB

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