main.py 66 KB

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