main.py 66 KB

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