main.py 66 KB

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