main.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684
  1. import asyncio
  2. import inspect
  3. import json
  4. import logging
  5. import mimetypes
  6. import os
  7. import shutil
  8. import sys
  9. import time
  10. import random
  11. from contextlib import asynccontextmanager
  12. from typing import Optional
  13. from aiocache import cached
  14. import aiohttp
  15. import requests
  16. from fastapi import (
  17. Depends,
  18. FastAPI,
  19. File,
  20. Form,
  21. HTTPException,
  22. Request,
  23. UploadFile,
  24. status,
  25. )
  26. from fastapi.middleware.cors import CORSMiddleware
  27. from fastapi.responses import JSONResponse, RedirectResponse
  28. from fastapi.staticfiles import StaticFiles
  29. from pydantic import BaseModel
  30. from sqlalchemy import text
  31. from starlette.exceptions import HTTPException as StarletteHTTPException
  32. from starlette.middleware.base import BaseHTTPMiddleware
  33. from starlette.middleware.sessions import SessionMiddleware
  34. from starlette.responses import Response, StreamingResponse
  35. from open_webui.apps.audio.main import app as audio_app
  36. from open_webui.apps.images.main import app as images_app
  37. from open_webui.apps.ollama.main import (
  38. app as ollama_app,
  39. get_all_models as get_ollama_models,
  40. generate_chat_completion as generate_ollama_chat_completion,
  41. GenerateChatCompletionForm,
  42. )
  43. from open_webui.apps.openai.main import (
  44. app as openai_app,
  45. generate_chat_completion as generate_openai_chat_completion,
  46. get_all_models as get_openai_models,
  47. get_all_models_responses as get_openai_models_responses,
  48. )
  49. from open_webui.apps.retrieval.main import app as retrieval_app
  50. from open_webui.apps.retrieval.utils import get_sources_from_files
  51. from open_webui.apps.socket.main import (
  52. app as socket_app,
  53. periodic_usage_pool_cleanup,
  54. get_event_call,
  55. get_event_emitter,
  56. )
  57. from open_webui.apps.webui.internal.db import Session
  58. from open_webui.apps.webui.main import (
  59. app as webui_app,
  60. generate_function_chat_completion,
  61. get_all_models as get_open_webui_models,
  62. )
  63. from open_webui.apps.webui.models.functions import Functions
  64. from open_webui.apps.webui.models.models import Models
  65. from open_webui.apps.webui.models.users import UserModel, Users
  66. from open_webui.apps.webui.utils import load_function_module_by_id
  67. from open_webui.config import (
  68. CACHE_DIR,
  69. CORS_ALLOW_ORIGIN,
  70. DEFAULT_LOCALE,
  71. ENABLE_ADMIN_CHAT_ACCESS,
  72. ENABLE_ADMIN_EXPORT,
  73. ENABLE_OLLAMA_API,
  74. ENABLE_OPENAI_API,
  75. ENABLE_TAGS_GENERATION,
  76. ENV,
  77. FRONTEND_BUILD_DIR,
  78. OAUTH_PROVIDERS,
  79. STATIC_DIR,
  80. TASK_MODEL,
  81. TASK_MODEL_EXTERNAL,
  82. ENABLE_SEARCH_QUERY_GENERATION,
  83. ENABLE_RETRIEVAL_QUERY_GENERATION,
  84. QUERY_GENERATION_PROMPT_TEMPLATE,
  85. DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE,
  86. TITLE_GENERATION_PROMPT_TEMPLATE,
  87. TAGS_GENERATION_PROMPT_TEMPLATE,
  88. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  89. WEBHOOK_URL,
  90. WEBUI_AUTH,
  91. WEBUI_NAME,
  92. AppConfig,
  93. reset_config,
  94. )
  95. from open_webui.constants import TASKS
  96. from open_webui.env import (
  97. CHANGELOG,
  98. GLOBAL_LOG_LEVEL,
  99. SAFE_MODE,
  100. SRC_LOG_LEVELS,
  101. VERSION,
  102. WEBUI_BUILD_HASH,
  103. WEBUI_SECRET_KEY,
  104. WEBUI_SESSION_COOKIE_SAME_SITE,
  105. WEBUI_SESSION_COOKIE_SECURE,
  106. WEBUI_URL,
  107. RESET_CONFIG_ON_START,
  108. OFFLINE_MODE,
  109. )
  110. from open_webui.utils.misc import (
  111. add_or_update_system_message,
  112. get_last_user_message,
  113. prepend_to_first_user_message_content,
  114. )
  115. from open_webui.utils.oauth import oauth_manager
  116. from open_webui.utils.payload import convert_payload_openai_to_ollama
  117. from open_webui.utils.response import (
  118. convert_response_ollama_to_openai,
  119. convert_streaming_response_ollama_to_openai,
  120. )
  121. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  122. from open_webui.utils.task import (
  123. rag_template,
  124. title_generation_template,
  125. query_generation_template,
  126. tags_generation_template,
  127. emoji_generation_template,
  128. moa_response_generation_template,
  129. tools_function_calling_generation_template,
  130. )
  131. from open_webui.utils.tools import get_tools
  132. from open_webui.utils.utils import (
  133. decode_token,
  134. get_admin_user,
  135. get_current_user,
  136. get_http_authorization_cred,
  137. get_verified_user,
  138. )
  139. from open_webui.utils.access_control import has_access
  140. if SAFE_MODE:
  141. print("SAFE MODE ENABLED")
  142. Functions.deactivate_all_functions()
  143. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  144. log = logging.getLogger(__name__)
  145. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  146. class SPAStaticFiles(StaticFiles):
  147. async def get_response(self, path: str, scope):
  148. try:
  149. return await super().get_response(path, scope)
  150. except (HTTPException, StarletteHTTPException) as ex:
  151. if ex.status_code == 404:
  152. return await super().get_response("index.html", scope)
  153. else:
  154. raise ex
  155. print(
  156. rf"""
  157. ___ __ __ _ _ _ ___
  158. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  159. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  160. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  161. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  162. |_|
  163. v{VERSION} - building the best open-source AI user interface.
  164. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  165. https://github.com/open-webui/open-webui
  166. """
  167. )
  168. @asynccontextmanager
  169. async def lifespan(app: FastAPI):
  170. if RESET_CONFIG_ON_START:
  171. reset_config()
  172. asyncio.create_task(periodic_usage_pool_cleanup())
  173. yield
  174. app = FastAPI(
  175. docs_url="/docs" if ENV == "dev" else None,
  176. openapi_url="/openapi.json" if ENV == "dev" else None,
  177. redoc_url=None,
  178. lifespan=lifespan,
  179. )
  180. app.state.config = AppConfig()
  181. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  182. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  183. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  184. app.state.config.TASK_MODEL = TASK_MODEL
  185. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  186. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  187. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  188. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  189. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  190. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  191. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  192. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  193. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  194. )
  195. ##################################
  196. #
  197. # ChatCompletion Middleware
  198. #
  199. ##################################
  200. def get_filter_function_ids(model):
  201. def get_priority(function_id):
  202. function = Functions.get_function_by_id(function_id)
  203. if function is not None and hasattr(function, "valves"):
  204. # TODO: Fix FunctionModel
  205. return (function.valves if function.valves else {}).get("priority", 0)
  206. return 0
  207. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  208. if "info" in model and "meta" in model["info"]:
  209. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  210. filter_ids = list(set(filter_ids))
  211. enabled_filter_ids = [
  212. function.id
  213. for function in Functions.get_functions_by_type("filter", active_only=True)
  214. ]
  215. filter_ids = [
  216. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  217. ]
  218. filter_ids.sort(key=get_priority)
  219. return filter_ids
  220. async def chat_completion_filter_functions_handler(body, model, extra_params):
  221. skip_files = None
  222. filter_ids = get_filter_function_ids(model)
  223. for filter_id in filter_ids:
  224. filter = Functions.get_function_by_id(filter_id)
  225. if not filter:
  226. continue
  227. if filter_id in webui_app.state.FUNCTIONS:
  228. function_module = webui_app.state.FUNCTIONS[filter_id]
  229. else:
  230. function_module, _, _ = load_function_module_by_id(filter_id)
  231. webui_app.state.FUNCTIONS[filter_id] = function_module
  232. # Check if the function has a file_handler variable
  233. if hasattr(function_module, "file_handler"):
  234. skip_files = function_module.file_handler
  235. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  236. valves = Functions.get_function_valves_by_id(filter_id)
  237. function_module.valves = function_module.Valves(
  238. **(valves if valves else {})
  239. )
  240. if not hasattr(function_module, "inlet"):
  241. continue
  242. try:
  243. inlet = function_module.inlet
  244. # Get the signature of the function
  245. sig = inspect.signature(inlet)
  246. params = {"body": body} | {
  247. k: v
  248. for k, v in {
  249. **extra_params,
  250. "__model__": model,
  251. "__id__": filter_id,
  252. }.items()
  253. if k in sig.parameters
  254. }
  255. if "__user__" in params and hasattr(function_module, "UserValves"):
  256. try:
  257. params["__user__"]["valves"] = function_module.UserValves(
  258. **Functions.get_user_valves_by_id_and_user_id(
  259. filter_id, params["__user__"]["id"]
  260. )
  261. )
  262. except Exception as e:
  263. print(e)
  264. if inspect.iscoroutinefunction(inlet):
  265. body = await inlet(**params)
  266. else:
  267. body = inlet(**params)
  268. except Exception as e:
  269. print(f"Error: {e}")
  270. raise e
  271. if skip_files and "files" in body.get("metadata", {}):
  272. del body["metadata"]["files"]
  273. return body, {}
  274. def get_tools_function_calling_payload(messages, task_model_id, content):
  275. user_message = get_last_user_message(messages)
  276. history = "\n".join(
  277. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  278. for message in messages[::-1][:4]
  279. )
  280. prompt = f"History:\n{history}\nQuery: {user_message}"
  281. return {
  282. "model": task_model_id,
  283. "messages": [
  284. {"role": "system", "content": content},
  285. {"role": "user", "content": f"Query: {prompt}"},
  286. ],
  287. "stream": False,
  288. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  289. }
  290. async def get_content_from_response(response) -> Optional[str]:
  291. content = None
  292. if hasattr(response, "body_iterator"):
  293. async for chunk in response.body_iterator:
  294. data = json.loads(chunk.decode("utf-8"))
  295. content = data["choices"][0]["message"]["content"]
  296. # Cleanup any remaining background tasks if necessary
  297. if response.background is not None:
  298. await response.background()
  299. else:
  300. content = response["choices"][0]["message"]["content"]
  301. return content
  302. def get_task_model_id(
  303. default_model_id: str, task_model: str, task_model_external: str, models
  304. ) -> str:
  305. # Set the task model
  306. task_model_id = default_model_id
  307. # Check if the user has a custom task model and use that model
  308. if models[task_model_id]["owned_by"] == "ollama":
  309. if task_model and task_model in models:
  310. task_model_id = task_model
  311. else:
  312. if task_model_external and task_model_external in models:
  313. task_model_id = task_model_external
  314. return task_model_id
  315. async def chat_completion_tools_handler(
  316. body: dict, user: UserModel, models, extra_params: dict
  317. ) -> tuple[dict, dict]:
  318. # If tool_ids field is present, call the functions
  319. metadata = body.get("metadata", {})
  320. tool_ids = metadata.get("tool_ids", None)
  321. log.debug(f"{tool_ids=}")
  322. if not tool_ids:
  323. return body, {}
  324. skip_files = False
  325. sources = []
  326. task_model_id = get_task_model_id(
  327. body["model"],
  328. app.state.config.TASK_MODEL,
  329. app.state.config.TASK_MODEL_EXTERNAL,
  330. models,
  331. )
  332. tools = get_tools(
  333. webui_app,
  334. tool_ids,
  335. user,
  336. {
  337. **extra_params,
  338. "__model__": models[task_model_id],
  339. "__messages__": body["messages"],
  340. "__files__": metadata.get("files", []),
  341. },
  342. )
  343. log.info(f"{tools=}")
  344. specs = [tool["spec"] for tool in tools.values()]
  345. tools_specs = json.dumps(specs)
  346. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  347. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  348. else:
  349. template = """Available Tools: {{TOOLS}}\nReturn an empty string if no tools match the query. If a function tool matches, construct and return a JSON object in the format {\"name\": \"functionName\", \"parameters\": {\"requiredFunctionParamKey\": \"requiredFunctionParamValue\"}} using the appropriate tool and its parameters. Only return the object and limit the response to the JSON object without additional text."""
  350. tools_function_calling_prompt = tools_function_calling_generation_template(
  351. template, tools_specs
  352. )
  353. log.info(f"{tools_function_calling_prompt=}")
  354. payload = get_tools_function_calling_payload(
  355. body["messages"], task_model_id, tools_function_calling_prompt
  356. )
  357. try:
  358. payload = filter_pipeline(payload, user, models)
  359. except Exception as e:
  360. raise e
  361. try:
  362. response = await generate_chat_completions(form_data=payload, user=user)
  363. log.debug(f"{response=}")
  364. content = await get_content_from_response(response)
  365. log.debug(f"{content=}")
  366. if not content:
  367. return body, {}
  368. try:
  369. content = content[content.find("{") : content.rfind("}") + 1]
  370. if not content:
  371. raise Exception("No JSON object found in the response")
  372. result = json.loads(content)
  373. tool_function_name = result.get("name", None)
  374. if tool_function_name not in tools:
  375. return body, {}
  376. tool_function_params = result.get("parameters", {})
  377. try:
  378. required_params = (
  379. tools[tool_function_name]
  380. .get("spec", {})
  381. .get("parameters", {})
  382. .get("required", [])
  383. )
  384. tool_function = tools[tool_function_name]["callable"]
  385. tool_function_params = {
  386. k: v
  387. for k, v in tool_function_params.items()
  388. if k in required_params
  389. }
  390. tool_output = await tool_function(**tool_function_params)
  391. except Exception as e:
  392. tool_output = str(e)
  393. print(tools[tool_function_name]["citation"])
  394. if isinstance(tool_output, str):
  395. if tools[tool_function_name]["citation"]:
  396. sources.append(
  397. {
  398. "source": {
  399. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  400. },
  401. "document": [tool_output],
  402. "metadata": [
  403. {
  404. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  405. }
  406. ],
  407. }
  408. )
  409. else:
  410. sources.append(
  411. {
  412. "source": {},
  413. "document": [tool_output],
  414. "metadata": [
  415. {
  416. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  417. }
  418. ],
  419. }
  420. )
  421. if tools[tool_function_name]["file_handler"]:
  422. skip_files = True
  423. except Exception as e:
  424. log.exception(f"Error: {e}")
  425. content = None
  426. except Exception as e:
  427. log.exception(f"Error: {e}")
  428. content = None
  429. log.debug(f"tool_contexts: {sources}")
  430. if skip_files and "files" in body.get("metadata", {}):
  431. del body["metadata"]["files"]
  432. return body, {"sources": sources}
  433. async def chat_completion_files_handler(
  434. body: dict, user: UserModel
  435. ) -> tuple[dict, dict[str, list]]:
  436. sources = []
  437. if files := body.get("metadata", {}).get("files", None):
  438. try:
  439. queries_response = await generate_queries(
  440. {
  441. "model": body["model"],
  442. "messages": body["messages"],
  443. "type": "retrieval",
  444. },
  445. user,
  446. )
  447. queries_response = queries_response["choices"][0]["message"]["content"]
  448. try:
  449. queries_response = json.loads(queries_response)
  450. except Exception as e:
  451. queries_response = {"queries": []}
  452. queries = queries_response.get("queries", [])
  453. except Exception as e:
  454. queries = []
  455. if len(queries) == 0:
  456. queries = [get_last_user_message(body["messages"])]
  457. sources = get_sources_from_files(
  458. files=files,
  459. queries=queries,
  460. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  461. k=retrieval_app.state.config.TOP_K,
  462. reranking_function=retrieval_app.state.sentence_transformer_rf,
  463. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  464. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  465. )
  466. log.debug(f"rag_contexts:sources: {sources}")
  467. return body, {"sources": sources}
  468. def is_chat_completion_request(request):
  469. return request.method == "POST" and any(
  470. endpoint in request.url.path
  471. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  472. )
  473. async def get_body_and_model_and_user(request, models):
  474. # Read the original request body
  475. body = await request.body()
  476. body_str = body.decode("utf-8")
  477. body = json.loads(body_str) if body_str else {}
  478. model_id = body["model"]
  479. if model_id not in models:
  480. raise Exception("Model not found")
  481. model = models[model_id]
  482. user = get_current_user(
  483. request,
  484. get_http_authorization_cred(request.headers.get("Authorization")),
  485. )
  486. return body, model, user
  487. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  488. async def dispatch(self, request: Request, call_next):
  489. if not is_chat_completion_request(request):
  490. return await call_next(request)
  491. log.debug(f"request.url.path: {request.url.path}")
  492. model_list = await get_all_models()
  493. models = {model["id"]: model for model in model_list}
  494. try:
  495. body, model, user = await get_body_and_model_and_user(request, models)
  496. except Exception as e:
  497. return JSONResponse(
  498. status_code=status.HTTP_400_BAD_REQUEST,
  499. content={"detail": str(e)},
  500. )
  501. model_info = Models.get_model_by_id(model["id"])
  502. if user.role == "user":
  503. if model.get("arena"):
  504. if not has_access(
  505. user.id,
  506. type="read",
  507. access_control=model.get("info", {})
  508. .get("meta", {})
  509. .get("access_control", {}),
  510. ):
  511. raise HTTPException(
  512. status_code=403,
  513. detail="Model not found",
  514. )
  515. else:
  516. if not model_info:
  517. return JSONResponse(
  518. status_code=status.HTTP_404_NOT_FOUND,
  519. content={"detail": "Model not found"},
  520. )
  521. elif not (
  522. user.id == model_info.user_id
  523. or has_access(
  524. user.id, type="read", access_control=model_info.access_control
  525. )
  526. ):
  527. return JSONResponse(
  528. status_code=status.HTTP_403_FORBIDDEN,
  529. content={"detail": "User does not have access to the model"},
  530. )
  531. metadata = {
  532. "chat_id": body.pop("chat_id", None),
  533. "message_id": body.pop("id", None),
  534. "session_id": body.pop("session_id", None),
  535. "tool_ids": body.get("tool_ids", None),
  536. "files": body.get("files", None),
  537. }
  538. body["metadata"] = metadata
  539. extra_params = {
  540. "__event_emitter__": get_event_emitter(metadata),
  541. "__event_call__": get_event_call(metadata),
  542. "__user__": {
  543. "id": user.id,
  544. "email": user.email,
  545. "name": user.name,
  546. "role": user.role,
  547. },
  548. "__metadata__": metadata,
  549. }
  550. # Initialize data_items to store additional data to be sent to the client
  551. # Initialize contexts and citation
  552. data_items = []
  553. sources = []
  554. try:
  555. body, flags = await chat_completion_filter_functions_handler(
  556. body, model, extra_params
  557. )
  558. except Exception as e:
  559. return JSONResponse(
  560. status_code=status.HTTP_400_BAD_REQUEST,
  561. content={"detail": str(e)},
  562. )
  563. tool_ids = body.pop("tool_ids", None)
  564. files = body.pop("files", None)
  565. metadata = {
  566. **metadata,
  567. "tool_ids": tool_ids,
  568. "files": files,
  569. }
  570. body["metadata"] = metadata
  571. try:
  572. body, flags = await chat_completion_tools_handler(
  573. body, user, models, extra_params
  574. )
  575. sources.extend(flags.get("sources", []))
  576. except Exception as e:
  577. log.exception(e)
  578. try:
  579. body, flags = await chat_completion_files_handler(body, user)
  580. sources.extend(flags.get("sources", []))
  581. except Exception as e:
  582. log.exception(e)
  583. # If context is not empty, insert it into the messages
  584. if len(sources) > 0:
  585. context_string = ""
  586. for source_idx, source in enumerate(sources):
  587. source_id = source.get("source", {}).get("name", "")
  588. if "document" in source:
  589. for doc_idx, doc_context in enumerate(source["document"]):
  590. metadata = source.get("metadata")
  591. doc_source_id = None
  592. if metadata:
  593. doc_source_id = metadata[doc_idx].get("source", source_id)
  594. if source_id:
  595. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  596. else:
  597. # If there is no source_id, then do not include the source_id tag
  598. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  599. context_string = context_string.strip()
  600. prompt = get_last_user_message(body["messages"])
  601. if prompt is None:
  602. raise Exception("No user message found")
  603. if (
  604. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  605. and context_string.strip() == ""
  606. ):
  607. log.debug(
  608. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  609. )
  610. # Workaround for Ollama 2.0+ system prompt issue
  611. # TODO: replace with add_or_update_system_message
  612. if model["owned_by"] == "ollama":
  613. body["messages"] = prepend_to_first_user_message_content(
  614. rag_template(
  615. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  616. ),
  617. body["messages"],
  618. )
  619. else:
  620. body["messages"] = add_or_update_system_message(
  621. rag_template(
  622. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  623. ),
  624. body["messages"],
  625. )
  626. # If there are citations, add them to the data_items
  627. sources = [
  628. source for source in sources if source.get("source", {}).get("name", "")
  629. ]
  630. if len(sources) > 0:
  631. data_items.append({"sources": sources})
  632. modified_body_bytes = json.dumps(body).encode("utf-8")
  633. # Replace the request body with the modified one
  634. request._body = modified_body_bytes
  635. # Set custom header to ensure content-length matches new body length
  636. request.headers.__dict__["_list"] = [
  637. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  638. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  639. ]
  640. response = await call_next(request)
  641. if not isinstance(response, StreamingResponse):
  642. return response
  643. content_type = response.headers["Content-Type"]
  644. is_openai = "text/event-stream" in content_type
  645. is_ollama = "application/x-ndjson" in content_type
  646. if not is_openai and not is_ollama:
  647. return response
  648. def wrap_item(item):
  649. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  650. async def stream_wrapper(original_generator, data_items):
  651. for item in data_items:
  652. yield wrap_item(json.dumps(item))
  653. async for data in original_generator:
  654. yield data
  655. return StreamingResponse(
  656. stream_wrapper(response.body_iterator, data_items),
  657. headers=dict(response.headers),
  658. )
  659. async def _receive(self, body: bytes):
  660. return {"type": "http.request", "body": body, "more_body": False}
  661. app.add_middleware(ChatCompletionMiddleware)
  662. ##################################
  663. #
  664. # Pipeline Middleware
  665. #
  666. ##################################
  667. def get_sorted_filters(model_id, models):
  668. filters = [
  669. model
  670. for model in models.values()
  671. if "pipeline" in model
  672. and "type" in model["pipeline"]
  673. and model["pipeline"]["type"] == "filter"
  674. and (
  675. model["pipeline"]["pipelines"] == ["*"]
  676. or any(
  677. model_id == target_model_id
  678. for target_model_id in model["pipeline"]["pipelines"]
  679. )
  680. )
  681. ]
  682. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  683. return sorted_filters
  684. def filter_pipeline(payload, user, models):
  685. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  686. model_id = payload["model"]
  687. sorted_filters = get_sorted_filters(model_id, models)
  688. model = models[model_id]
  689. if "pipeline" in model:
  690. sorted_filters.append(model)
  691. for filter in sorted_filters:
  692. r = None
  693. try:
  694. urlIdx = filter["urlIdx"]
  695. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  696. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  697. if key == "":
  698. continue
  699. headers = {"Authorization": f"Bearer {key}"}
  700. r = requests.post(
  701. f"{url}/{filter['id']}/filter/inlet",
  702. headers=headers,
  703. json={
  704. "user": user,
  705. "body": payload,
  706. },
  707. )
  708. r.raise_for_status()
  709. payload = r.json()
  710. except Exception as e:
  711. # Handle connection error here
  712. print(f"Connection error: {e}")
  713. if r is not None:
  714. res = r.json()
  715. if "detail" in res:
  716. raise Exception(r.status_code, res["detail"])
  717. return payload
  718. class PipelineMiddleware(BaseHTTPMiddleware):
  719. async def dispatch(self, request: Request, call_next):
  720. if not is_chat_completion_request(request):
  721. return await call_next(request)
  722. log.debug(f"request.url.path: {request.url.path}")
  723. # Read the original request body
  724. body = await request.body()
  725. # Decode body to string
  726. body_str = body.decode("utf-8")
  727. # Parse string to JSON
  728. data = json.loads(body_str) if body_str else {}
  729. try:
  730. user = get_current_user(
  731. request,
  732. get_http_authorization_cred(request.headers["Authorization"]),
  733. )
  734. except KeyError as e:
  735. if len(e.args) > 1:
  736. return JSONResponse(
  737. status_code=e.args[0],
  738. content={"detail": e.args[1]},
  739. )
  740. else:
  741. return JSONResponse(
  742. status_code=status.HTTP_401_UNAUTHORIZED,
  743. content={"detail": "Not authenticated"},
  744. )
  745. except HTTPException as e:
  746. return JSONResponse(
  747. status_code=e.status_code,
  748. content={"detail": e.detail},
  749. )
  750. model_list = await get_all_models()
  751. models = {model["id"]: model for model in model_list}
  752. try:
  753. data = filter_pipeline(data, user, models)
  754. except Exception as e:
  755. if len(e.args) > 1:
  756. return JSONResponse(
  757. status_code=e.args[0],
  758. content={"detail": e.args[1]},
  759. )
  760. else:
  761. return JSONResponse(
  762. status_code=status.HTTP_400_BAD_REQUEST,
  763. content={"detail": str(e)},
  764. )
  765. modified_body_bytes = json.dumps(data).encode("utf-8")
  766. # Replace the request body with the modified one
  767. request._body = modified_body_bytes
  768. # Set custom header to ensure content-length matches new body length
  769. request.headers.__dict__["_list"] = [
  770. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  771. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  772. ]
  773. response = await call_next(request)
  774. return response
  775. async def _receive(self, body: bytes):
  776. return {"type": "http.request", "body": body, "more_body": False}
  777. app.add_middleware(PipelineMiddleware)
  778. from urllib.parse import urlencode, parse_qs, urlparse
  779. class RedirectMiddleware(BaseHTTPMiddleware):
  780. async def dispatch(self, request: Request, call_next):
  781. # Check if the request is a GET request
  782. if request.method == "GET":
  783. path = request.url.path
  784. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  785. # Check for the specific watch path and the presence of 'v' parameter
  786. if path.endswith("/watch") and "v" in query_params:
  787. video_id = query_params["v"][0] # Extract the first 'v' parameter
  788. encoded_video_id = urlencode({"youtube": video_id})
  789. redirect_url = f"/?{encoded_video_id}"
  790. return RedirectResponse(url=redirect_url)
  791. # Proceed with the normal flow of other requests
  792. response = await call_next(request)
  793. return response
  794. # Add the middleware to the app
  795. app.add_middleware(RedirectMiddleware)
  796. app.add_middleware(
  797. CORSMiddleware,
  798. allow_origins=CORS_ALLOW_ORIGIN,
  799. allow_credentials=True,
  800. allow_methods=["*"],
  801. allow_headers=["*"],
  802. )
  803. app.add_middleware(SecurityHeadersMiddleware)
  804. @app.middleware("http")
  805. async def commit_session_after_request(request: Request, call_next):
  806. response = await call_next(request)
  807. # log.debug("Commit session after request")
  808. Session.commit()
  809. return response
  810. @app.middleware("http")
  811. async def check_url(request: Request, call_next):
  812. start_time = int(time.time())
  813. request.state.enable_api_key = webui_app.state.config.ENABLE_API_KEY
  814. response = await call_next(request)
  815. process_time = int(time.time()) - start_time
  816. response.headers["X-Process-Time"] = str(process_time)
  817. return response
  818. @app.middleware("http")
  819. async def update_embedding_function(request: Request, call_next):
  820. response = await call_next(request)
  821. if "/embedding/update" in request.url.path:
  822. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  823. return response
  824. @app.middleware("http")
  825. async def inspect_websocket(request: Request, call_next):
  826. if (
  827. "/ws/socket.io" in request.url.path
  828. and request.query_params.get("transport") == "websocket"
  829. ):
  830. upgrade = (request.headers.get("Upgrade") or "").lower()
  831. connection = (request.headers.get("Connection") or "").lower().split(",")
  832. # Check that there's the correct headers for an upgrade, else reject the connection
  833. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  834. if upgrade != "websocket" or "upgrade" not in connection:
  835. return JSONResponse(
  836. status_code=status.HTTP_400_BAD_REQUEST,
  837. content={"detail": "Invalid WebSocket upgrade request"},
  838. )
  839. return await call_next(request)
  840. app.mount("/ws", socket_app)
  841. app.mount("/ollama", ollama_app)
  842. app.mount("/openai", openai_app)
  843. app.mount("/images/api/v1", images_app)
  844. app.mount("/audio/api/v1", audio_app)
  845. app.mount("/retrieval/api/v1", retrieval_app)
  846. app.mount("/api/v1", webui_app)
  847. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  848. async def get_all_base_models():
  849. open_webui_models = []
  850. openai_models = []
  851. ollama_models = []
  852. if app.state.config.ENABLE_OPENAI_API:
  853. openai_models = await get_openai_models()
  854. openai_models = openai_models["data"]
  855. if app.state.config.ENABLE_OLLAMA_API:
  856. ollama_models = await get_ollama_models()
  857. ollama_models = [
  858. {
  859. "id": model["model"],
  860. "name": model["name"],
  861. "object": "model",
  862. "created": int(time.time()),
  863. "owned_by": "ollama",
  864. "ollama": model,
  865. }
  866. for model in ollama_models["models"]
  867. ]
  868. open_webui_models = await get_open_webui_models()
  869. models = open_webui_models + openai_models + ollama_models
  870. return models
  871. @cached(ttl=3)
  872. async def get_all_models():
  873. models = await get_all_base_models()
  874. # If there are no models, return an empty list
  875. if len([model for model in models if not model.get("arena", False)]) == 0:
  876. return []
  877. global_action_ids = [
  878. function.id for function in Functions.get_global_action_functions()
  879. ]
  880. enabled_action_ids = [
  881. function.id
  882. for function in Functions.get_functions_by_type("action", active_only=True)
  883. ]
  884. custom_models = Models.get_all_models()
  885. for custom_model in custom_models:
  886. if custom_model.base_model_id is None:
  887. for model in models:
  888. if (
  889. custom_model.id == model["id"]
  890. or custom_model.id == model["id"].split(":")[0]
  891. ):
  892. if custom_model.is_active:
  893. model["name"] = custom_model.name
  894. model["info"] = custom_model.model_dump()
  895. action_ids = []
  896. if "info" in model and "meta" in model["info"]:
  897. action_ids.extend(
  898. model["info"]["meta"].get("actionIds", [])
  899. )
  900. model["action_ids"] = action_ids
  901. else:
  902. models.remove(model)
  903. elif custom_model.is_active and (
  904. custom_model.id not in [model["id"] for model in models]
  905. ):
  906. owned_by = "openai"
  907. pipe = None
  908. action_ids = []
  909. for model in models:
  910. if (
  911. custom_model.base_model_id == model["id"]
  912. or custom_model.base_model_id == model["id"].split(":")[0]
  913. ):
  914. owned_by = model["owned_by"]
  915. if "pipe" in model:
  916. pipe = model["pipe"]
  917. break
  918. if custom_model.meta:
  919. meta = custom_model.meta.model_dump()
  920. if "actionIds" in meta:
  921. action_ids.extend(meta["actionIds"])
  922. models.append(
  923. {
  924. "id": f"{custom_model.id}",
  925. "name": custom_model.name,
  926. "object": "model",
  927. "created": custom_model.created_at,
  928. "owned_by": owned_by,
  929. "info": custom_model.model_dump(),
  930. "preset": True,
  931. **({"pipe": pipe} if pipe is not None else {}),
  932. "action_ids": action_ids,
  933. }
  934. )
  935. # Process action_ids to get the actions
  936. def get_action_items_from_module(function, module):
  937. actions = []
  938. if hasattr(module, "actions"):
  939. actions = module.actions
  940. return [
  941. {
  942. "id": f"{function.id}.{action['id']}",
  943. "name": action.get("name", f"{function.name} ({action['id']})"),
  944. "description": function.meta.description,
  945. "icon_url": action.get(
  946. "icon_url", function.meta.manifest.get("icon_url", None)
  947. ),
  948. }
  949. for action in actions
  950. ]
  951. else:
  952. return [
  953. {
  954. "id": function.id,
  955. "name": function.name,
  956. "description": function.meta.description,
  957. "icon_url": function.meta.manifest.get("icon_url", None),
  958. }
  959. ]
  960. def get_function_module_by_id(function_id):
  961. if function_id in webui_app.state.FUNCTIONS:
  962. function_module = webui_app.state.FUNCTIONS[function_id]
  963. else:
  964. function_module, _, _ = load_function_module_by_id(function_id)
  965. webui_app.state.FUNCTIONS[function_id] = function_module
  966. for model in models:
  967. action_ids = [
  968. action_id
  969. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  970. if action_id in enabled_action_ids
  971. ]
  972. model["actions"] = []
  973. for action_id in action_ids:
  974. action_function = Functions.get_function_by_id(action_id)
  975. if action_function is None:
  976. raise Exception(f"Action not found: {action_id}")
  977. function_module = get_function_module_by_id(action_id)
  978. model["actions"].extend(
  979. get_action_items_from_module(action_function, function_module)
  980. )
  981. log.debug(f"get_all_models() returned {len(models)} models")
  982. return models
  983. @app.get("/api/models")
  984. async def get_models(user=Depends(get_verified_user)):
  985. models = await get_all_models()
  986. # Filter out filter pipelines
  987. models = [
  988. model
  989. for model in models
  990. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  991. ]
  992. model_order_list = webui_app.state.config.MODEL_ORDER_LIST
  993. if model_order_list:
  994. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  995. # Sort models by order list priority, with fallback for those not in the list
  996. models.sort(
  997. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  998. )
  999. # Filter out models that the user does not have access to
  1000. if user.role == "user":
  1001. filtered_models = []
  1002. for model in models:
  1003. if model.get("arena"):
  1004. if has_access(
  1005. user.id,
  1006. type="read",
  1007. access_control=model.get("info", {})
  1008. .get("meta", {})
  1009. .get("access_control", {}),
  1010. ):
  1011. filtered_models.append(model)
  1012. continue
  1013. model_info = Models.get_model_by_id(model["id"])
  1014. if model_info:
  1015. if user.id == model_info.user_id or has_access(
  1016. user.id, type="read", access_control=model_info.access_control
  1017. ):
  1018. filtered_models.append(model)
  1019. models = filtered_models
  1020. log.debug(
  1021. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  1022. )
  1023. return {"data": models}
  1024. @app.get("/api/models/base")
  1025. async def get_base_models(user=Depends(get_admin_user)):
  1026. models = await get_all_base_models()
  1027. # Filter out arena models
  1028. models = [model for model in models if not model.get("arena", False)]
  1029. return {"data": models}
  1030. @app.post("/api/chat/completions")
  1031. async def generate_chat_completions(
  1032. form_data: dict, user=Depends(get_verified_user), bypass_filter: bool = False
  1033. ):
  1034. model_list = await get_all_models()
  1035. models = {model["id"]: model for model in model_list}
  1036. model_id = form_data["model"]
  1037. if model_id not in models:
  1038. raise HTTPException(
  1039. status_code=status.HTTP_404_NOT_FOUND,
  1040. detail="Model not found",
  1041. )
  1042. model = models[model_id]
  1043. # Check if user has access to the model
  1044. if not bypass_filter and user.role == "user":
  1045. if model.get("arena"):
  1046. if not has_access(
  1047. user.id,
  1048. type="read",
  1049. access_control=model.get("info", {})
  1050. .get("meta", {})
  1051. .get("access_control", {}),
  1052. ):
  1053. raise HTTPException(
  1054. status_code=403,
  1055. detail="Model not found",
  1056. )
  1057. else:
  1058. model_info = Models.get_model_by_id(model_id)
  1059. if not model_info:
  1060. raise HTTPException(
  1061. status_code=404,
  1062. detail="Model not found",
  1063. )
  1064. elif not (
  1065. user.id == model_info.user_id
  1066. or has_access(
  1067. user.id, type="read", access_control=model_info.access_control
  1068. )
  1069. ):
  1070. raise HTTPException(
  1071. status_code=403,
  1072. detail="Model not found",
  1073. )
  1074. if model["owned_by"] == "arena":
  1075. model_ids = model.get("info", {}).get("meta", {}).get("model_ids")
  1076. filter_mode = model.get("info", {}).get("meta", {}).get("filter_mode")
  1077. if model_ids and filter_mode == "exclude":
  1078. model_ids = [
  1079. model["id"]
  1080. for model in await get_all_models()
  1081. if model.get("owned_by") != "arena" and model["id"] not in model_ids
  1082. ]
  1083. selected_model_id = None
  1084. if isinstance(model_ids, list) and model_ids:
  1085. selected_model_id = random.choice(model_ids)
  1086. else:
  1087. model_ids = [
  1088. model["id"]
  1089. for model in await get_all_models()
  1090. if model.get("owned_by") != "arena"
  1091. ]
  1092. selected_model_id = random.choice(model_ids)
  1093. form_data["model"] = selected_model_id
  1094. if form_data.get("stream") == True:
  1095. async def stream_wrapper(stream):
  1096. yield f"data: {json.dumps({'selected_model_id': selected_model_id})}\n\n"
  1097. async for chunk in stream:
  1098. yield chunk
  1099. response = await generate_chat_completions(
  1100. form_data, user, bypass_filter=True
  1101. )
  1102. return StreamingResponse(
  1103. stream_wrapper(response.body_iterator), media_type="text/event-stream"
  1104. )
  1105. else:
  1106. return {
  1107. **(
  1108. await generate_chat_completions(form_data, user, bypass_filter=True)
  1109. ),
  1110. "selected_model_id": selected_model_id,
  1111. }
  1112. if model.get("pipe"):
  1113. # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
  1114. return await generate_function_chat_completion(
  1115. form_data, user=user, models=models
  1116. )
  1117. if model["owned_by"] == "ollama":
  1118. # Using /ollama/api/chat endpoint
  1119. form_data = convert_payload_openai_to_ollama(form_data)
  1120. form_data = GenerateChatCompletionForm(**form_data)
  1121. response = await generate_ollama_chat_completion(
  1122. form_data=form_data, user=user, bypass_filter=bypass_filter
  1123. )
  1124. if form_data.stream:
  1125. response.headers["content-type"] = "text/event-stream"
  1126. return StreamingResponse(
  1127. convert_streaming_response_ollama_to_openai(response),
  1128. headers=dict(response.headers),
  1129. )
  1130. else:
  1131. return convert_response_ollama_to_openai(response)
  1132. else:
  1133. return await generate_openai_chat_completion(
  1134. form_data, user=user, bypass_filter=bypass_filter
  1135. )
  1136. @app.post("/api/chat/completed")
  1137. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  1138. model_list = await get_all_models()
  1139. models = {model["id"]: model for model in model_list}
  1140. data = form_data
  1141. model_id = data["model"]
  1142. if model_id not in models:
  1143. raise HTTPException(
  1144. status_code=status.HTTP_404_NOT_FOUND,
  1145. detail="Model not found",
  1146. )
  1147. model = models[model_id]
  1148. sorted_filters = get_sorted_filters(model_id, models)
  1149. if "pipeline" in model:
  1150. sorted_filters = [model] + sorted_filters
  1151. for filter in sorted_filters:
  1152. r = None
  1153. try:
  1154. urlIdx = filter["urlIdx"]
  1155. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1156. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1157. if key != "":
  1158. headers = {"Authorization": f"Bearer {key}"}
  1159. r = requests.post(
  1160. f"{url}/{filter['id']}/filter/outlet",
  1161. headers=headers,
  1162. json={
  1163. "user": {
  1164. "id": user.id,
  1165. "name": user.name,
  1166. "email": user.email,
  1167. "role": user.role,
  1168. },
  1169. "body": data,
  1170. },
  1171. )
  1172. r.raise_for_status()
  1173. data = r.json()
  1174. except Exception as e:
  1175. # Handle connection error here
  1176. print(f"Connection error: {e}")
  1177. if r is not None:
  1178. try:
  1179. res = r.json()
  1180. if "detail" in res:
  1181. return JSONResponse(
  1182. status_code=r.status_code,
  1183. content=res,
  1184. )
  1185. except Exception:
  1186. pass
  1187. else:
  1188. pass
  1189. __event_emitter__ = get_event_emitter(
  1190. {
  1191. "chat_id": data["chat_id"],
  1192. "message_id": data["id"],
  1193. "session_id": data["session_id"],
  1194. }
  1195. )
  1196. __event_call__ = get_event_call(
  1197. {
  1198. "chat_id": data["chat_id"],
  1199. "message_id": data["id"],
  1200. "session_id": data["session_id"],
  1201. }
  1202. )
  1203. def get_priority(function_id):
  1204. function = Functions.get_function_by_id(function_id)
  1205. if function is not None and hasattr(function, "valves"):
  1206. # TODO: Fix FunctionModel to include vavles
  1207. return (function.valves if function.valves else {}).get("priority", 0)
  1208. return 0
  1209. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  1210. if "info" in model and "meta" in model["info"]:
  1211. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  1212. filter_ids = list(set(filter_ids))
  1213. enabled_filter_ids = [
  1214. function.id
  1215. for function in Functions.get_functions_by_type("filter", active_only=True)
  1216. ]
  1217. filter_ids = [
  1218. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  1219. ]
  1220. # Sort filter_ids by priority, using the get_priority function
  1221. filter_ids.sort(key=get_priority)
  1222. for filter_id in filter_ids:
  1223. filter = Functions.get_function_by_id(filter_id)
  1224. if not filter:
  1225. continue
  1226. if filter_id in webui_app.state.FUNCTIONS:
  1227. function_module = webui_app.state.FUNCTIONS[filter_id]
  1228. else:
  1229. function_module, _, _ = load_function_module_by_id(filter_id)
  1230. webui_app.state.FUNCTIONS[filter_id] = function_module
  1231. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1232. valves = Functions.get_function_valves_by_id(filter_id)
  1233. function_module.valves = function_module.Valves(
  1234. **(valves if valves else {})
  1235. )
  1236. if not hasattr(function_module, "outlet"):
  1237. continue
  1238. try:
  1239. outlet = function_module.outlet
  1240. # Get the signature of the function
  1241. sig = inspect.signature(outlet)
  1242. params = {"body": data}
  1243. # Extra parameters to be passed to the function
  1244. extra_params = {
  1245. "__model__": model,
  1246. "__id__": filter_id,
  1247. "__event_emitter__": __event_emitter__,
  1248. "__event_call__": __event_call__,
  1249. }
  1250. # Add extra params in contained in function signature
  1251. for key, value in extra_params.items():
  1252. if key in sig.parameters:
  1253. params[key] = value
  1254. if "__user__" in sig.parameters:
  1255. __user__ = {
  1256. "id": user.id,
  1257. "email": user.email,
  1258. "name": user.name,
  1259. "role": user.role,
  1260. }
  1261. try:
  1262. if hasattr(function_module, "UserValves"):
  1263. __user__["valves"] = function_module.UserValves(
  1264. **Functions.get_user_valves_by_id_and_user_id(
  1265. filter_id, user.id
  1266. )
  1267. )
  1268. except Exception as e:
  1269. print(e)
  1270. params = {**params, "__user__": __user__}
  1271. if inspect.iscoroutinefunction(outlet):
  1272. data = await outlet(**params)
  1273. else:
  1274. data = outlet(**params)
  1275. except Exception as e:
  1276. print(f"Error: {e}")
  1277. return JSONResponse(
  1278. status_code=status.HTTP_400_BAD_REQUEST,
  1279. content={"detail": str(e)},
  1280. )
  1281. return data
  1282. @app.post("/api/chat/actions/{action_id}")
  1283. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1284. if "." in action_id:
  1285. action_id, sub_action_id = action_id.split(".")
  1286. else:
  1287. sub_action_id = None
  1288. action = Functions.get_function_by_id(action_id)
  1289. if not action:
  1290. raise HTTPException(
  1291. status_code=status.HTTP_404_NOT_FOUND,
  1292. detail="Action not found",
  1293. )
  1294. model_list = await get_all_models()
  1295. models = {model["id"]: model for model in model_list}
  1296. data = form_data
  1297. model_id = data["model"]
  1298. if model_id not in models:
  1299. raise HTTPException(
  1300. status_code=status.HTTP_404_NOT_FOUND,
  1301. detail="Model not found",
  1302. )
  1303. model = models[model_id]
  1304. __event_emitter__ = get_event_emitter(
  1305. {
  1306. "chat_id": data["chat_id"],
  1307. "message_id": data["id"],
  1308. "session_id": data["session_id"],
  1309. }
  1310. )
  1311. __event_call__ = get_event_call(
  1312. {
  1313. "chat_id": data["chat_id"],
  1314. "message_id": data["id"],
  1315. "session_id": data["session_id"],
  1316. }
  1317. )
  1318. if action_id in webui_app.state.FUNCTIONS:
  1319. function_module = webui_app.state.FUNCTIONS[action_id]
  1320. else:
  1321. function_module, _, _ = load_function_module_by_id(action_id)
  1322. webui_app.state.FUNCTIONS[action_id] = function_module
  1323. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1324. valves = Functions.get_function_valves_by_id(action_id)
  1325. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1326. if hasattr(function_module, "action"):
  1327. try:
  1328. action = function_module.action
  1329. # Get the signature of the function
  1330. sig = inspect.signature(action)
  1331. params = {"body": data}
  1332. # Extra parameters to be passed to the function
  1333. extra_params = {
  1334. "__model__": model,
  1335. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1336. "__event_emitter__": __event_emitter__,
  1337. "__event_call__": __event_call__,
  1338. }
  1339. # Add extra params in contained in function signature
  1340. for key, value in extra_params.items():
  1341. if key in sig.parameters:
  1342. params[key] = value
  1343. if "__user__" in sig.parameters:
  1344. __user__ = {
  1345. "id": user.id,
  1346. "email": user.email,
  1347. "name": user.name,
  1348. "role": user.role,
  1349. }
  1350. try:
  1351. if hasattr(function_module, "UserValves"):
  1352. __user__["valves"] = function_module.UserValves(
  1353. **Functions.get_user_valves_by_id_and_user_id(
  1354. action_id, user.id
  1355. )
  1356. )
  1357. except Exception as e:
  1358. print(e)
  1359. params = {**params, "__user__": __user__}
  1360. if inspect.iscoroutinefunction(action):
  1361. data = await action(**params)
  1362. else:
  1363. data = action(**params)
  1364. except Exception as e:
  1365. print(f"Error: {e}")
  1366. return JSONResponse(
  1367. status_code=status.HTTP_400_BAD_REQUEST,
  1368. content={"detail": str(e)},
  1369. )
  1370. return data
  1371. ##################################
  1372. #
  1373. # Task Endpoints
  1374. #
  1375. ##################################
  1376. # TODO: Refactor task API endpoints below into a separate file
  1377. @app.get("/api/task/config")
  1378. async def get_task_config(user=Depends(get_verified_user)):
  1379. return {
  1380. "TASK_MODEL": app.state.config.TASK_MODEL,
  1381. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1382. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1383. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1384. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1385. "ENABLE_SEARCH_QUERY_GENERATION": app.state.config.ENABLE_SEARCH_QUERY_GENERATION,
  1386. "ENABLE_RETRIEVAL_QUERY_GENERATION": app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION,
  1387. "QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE,
  1388. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1389. }
  1390. class TaskConfigForm(BaseModel):
  1391. TASK_MODEL: Optional[str]
  1392. TASK_MODEL_EXTERNAL: Optional[str]
  1393. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1394. TAGS_GENERATION_PROMPT_TEMPLATE: str
  1395. ENABLE_TAGS_GENERATION: bool
  1396. ENABLE_SEARCH_QUERY_GENERATION: bool
  1397. ENABLE_RETRIEVAL_QUERY_GENERATION: bool
  1398. QUERY_GENERATION_PROMPT_TEMPLATE: str
  1399. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1400. @app.post("/api/task/config/update")
  1401. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1402. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1403. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1404. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1405. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1406. )
  1407. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = (
  1408. form_data.TAGS_GENERATION_PROMPT_TEMPLATE
  1409. )
  1410. app.state.config.ENABLE_TAGS_GENERATION = form_data.ENABLE_TAGS_GENERATION
  1411. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = (
  1412. form_data.ENABLE_SEARCH_QUERY_GENERATION
  1413. )
  1414. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = (
  1415. form_data.ENABLE_RETRIEVAL_QUERY_GENERATION
  1416. )
  1417. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = (
  1418. form_data.QUERY_GENERATION_PROMPT_TEMPLATE
  1419. )
  1420. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1421. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1422. )
  1423. return {
  1424. "TASK_MODEL": app.state.config.TASK_MODEL,
  1425. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1426. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1427. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1428. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1429. "ENABLE_SEARCH_QUERY_GENERATION": app.state.config.ENABLE_SEARCH_QUERY_GENERATION,
  1430. "ENABLE_RETRIEVAL_QUERY_GENERATION": app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION,
  1431. "QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE,
  1432. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1433. }
  1434. @app.post("/api/task/title/completions")
  1435. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1436. model_list = await get_all_models()
  1437. models = {model["id"]: model for model in model_list}
  1438. model_id = form_data["model"]
  1439. if model_id not in models:
  1440. raise HTTPException(
  1441. status_code=status.HTTP_404_NOT_FOUND,
  1442. detail="Model not found",
  1443. )
  1444. # Check if the user has a custom task model
  1445. # If the user has a custom task model, use that model
  1446. task_model_id = get_task_model_id(
  1447. model_id,
  1448. app.state.config.TASK_MODEL,
  1449. app.state.config.TASK_MODEL_EXTERNAL,
  1450. models,
  1451. )
  1452. log.debug(
  1453. f"generating chat title using model {task_model_id} for user {user.email} "
  1454. )
  1455. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1456. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1457. else:
  1458. template = """Create a concise, 3-5 word title with an emoji as a title for the chat history, in the given language. Suitable Emojis for the summary can be used to enhance understanding but avoid quotation marks or special formatting. RESPOND ONLY WITH THE TITLE TEXT.
  1459. Examples of titles:
  1460. 📉 Stock Market Trends
  1461. 🍪 Perfect Chocolate Chip Recipe
  1462. Evolution of Music Streaming
  1463. Remote Work Productivity Tips
  1464. Artificial Intelligence in Healthcare
  1465. 🎮 Video Game Development Insights
  1466. <chat_history>
  1467. {{MESSAGES:END:2}}
  1468. </chat_history>"""
  1469. content = title_generation_template(
  1470. template,
  1471. form_data["messages"],
  1472. {
  1473. "name": user.name,
  1474. "location": user.info.get("location") if user.info else None,
  1475. },
  1476. )
  1477. payload = {
  1478. "model": task_model_id,
  1479. "messages": [{"role": "user", "content": content}],
  1480. "stream": False,
  1481. **(
  1482. {"max_tokens": 50}
  1483. if models[task_model_id]["owned_by"] == "ollama"
  1484. else {
  1485. "max_completion_tokens": 50,
  1486. }
  1487. ),
  1488. "metadata": {
  1489. "task": str(TASKS.TITLE_GENERATION),
  1490. "task_body": form_data,
  1491. "chat_id": form_data.get("chat_id", None),
  1492. },
  1493. }
  1494. # Handle pipeline filters
  1495. try:
  1496. payload = filter_pipeline(payload, user, models)
  1497. except Exception as e:
  1498. if len(e.args) > 1:
  1499. return JSONResponse(
  1500. status_code=e.args[0],
  1501. content={"detail": e.args[1]},
  1502. )
  1503. else:
  1504. return JSONResponse(
  1505. status_code=status.HTTP_400_BAD_REQUEST,
  1506. content={"detail": str(e)},
  1507. )
  1508. if "chat_id" in payload:
  1509. del payload["chat_id"]
  1510. return await generate_chat_completions(form_data=payload, user=user)
  1511. @app.post("/api/task/tags/completions")
  1512. async def generate_chat_tags(form_data: dict, user=Depends(get_verified_user)):
  1513. if not app.state.config.ENABLE_TAGS_GENERATION:
  1514. return JSONResponse(
  1515. status_code=status.HTTP_200_OK,
  1516. content={"detail": "Tags generation is disabled"},
  1517. )
  1518. model_list = await get_all_models()
  1519. models = {model["id"]: model for model in model_list}
  1520. model_id = form_data["model"]
  1521. if model_id not in models:
  1522. raise HTTPException(
  1523. status_code=status.HTTP_404_NOT_FOUND,
  1524. detail="Model not found",
  1525. )
  1526. # Check if the user has a custom task model
  1527. # If the user has a custom task model, use that model
  1528. task_model_id = get_task_model_id(
  1529. model_id,
  1530. app.state.config.TASK_MODEL,
  1531. app.state.config.TASK_MODEL_EXTERNAL,
  1532. models,
  1533. )
  1534. log.debug(
  1535. f"generating chat tags using model {task_model_id} for user {user.email} "
  1536. )
  1537. if app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE != "":
  1538. template = app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE
  1539. else:
  1540. template = """### Task:
  1541. Generate 1-3 broad tags categorizing the main themes of the chat history, along with 1-3 more specific subtopic tags.
  1542. ### Guidelines:
  1543. - Start with high-level domains (e.g. Science, Technology, Philosophy, Arts, Politics, Business, Health, Sports, Entertainment, Education)
  1544. - Consider including relevant subfields/subdomains if they are strongly represented throughout the conversation
  1545. - If content is too short (less than 3 messages) or too diverse, use only ["General"]
  1546. - Use the chat's primary language; default to English if multilingual
  1547. - Prioritize accuracy over specificity
  1548. ### Output:
  1549. JSON format: { "tags": ["tag1", "tag2", "tag3"] }
  1550. ### Chat History:
  1551. <chat_history>
  1552. {{MESSAGES:END:6}}
  1553. </chat_history>"""
  1554. content = tags_generation_template(
  1555. template, form_data["messages"], {"name": user.name}
  1556. )
  1557. payload = {
  1558. "model": task_model_id,
  1559. "messages": [{"role": "user", "content": content}],
  1560. "stream": False,
  1561. "metadata": {
  1562. "task": str(TASKS.TAGS_GENERATION),
  1563. "task_body": form_data,
  1564. "chat_id": form_data.get("chat_id", None),
  1565. },
  1566. }
  1567. # Handle pipeline filters
  1568. try:
  1569. payload = filter_pipeline(payload, user, models)
  1570. except Exception as e:
  1571. if len(e.args) > 1:
  1572. return JSONResponse(
  1573. status_code=e.args[0],
  1574. content={"detail": e.args[1]},
  1575. )
  1576. else:
  1577. return JSONResponse(
  1578. status_code=status.HTTP_400_BAD_REQUEST,
  1579. content={"detail": str(e)},
  1580. )
  1581. if "chat_id" in payload:
  1582. del payload["chat_id"]
  1583. return await generate_chat_completions(form_data=payload, user=user)
  1584. @app.post("/api/task/queries/completions")
  1585. async def generate_queries(form_data: dict, user=Depends(get_verified_user)):
  1586. type = form_data.get("type")
  1587. if type == "web_search":
  1588. if not app.state.config.ENABLE_SEARCH_QUERY_GENERATION:
  1589. raise HTTPException(
  1590. status_code=status.HTTP_400_BAD_REQUEST,
  1591. detail=f"Search query generation is disabled",
  1592. )
  1593. elif type == "retrieval":
  1594. if not app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION:
  1595. raise HTTPException(
  1596. status_code=status.HTTP_400_BAD_REQUEST,
  1597. detail=f"Query generation is disabled",
  1598. )
  1599. model_list = await get_all_models()
  1600. models = {model["id"]: model for model in model_list}
  1601. model_id = form_data["model"]
  1602. if model_id not in models:
  1603. raise HTTPException(
  1604. status_code=status.HTTP_404_NOT_FOUND,
  1605. detail="Model not found",
  1606. )
  1607. # Check if the user has a custom task model
  1608. # If the user has a custom task model, use that model
  1609. task_model_id = get_task_model_id(
  1610. model_id,
  1611. app.state.config.TASK_MODEL,
  1612. app.state.config.TASK_MODEL_EXTERNAL,
  1613. models,
  1614. )
  1615. log.debug(
  1616. f"generating {type} queries using model {task_model_id} for user {user.email}"
  1617. )
  1618. if app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE != "":
  1619. template = app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE
  1620. else:
  1621. template = DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE
  1622. content = query_generation_template(
  1623. template, form_data["messages"], {"name": user.name}
  1624. )
  1625. payload = {
  1626. "model": task_model_id,
  1627. "messages": [{"role": "user", "content": content}],
  1628. "stream": False,
  1629. "metadata": {
  1630. "task": str(TASKS.QUERY_GENERATION),
  1631. "task_body": form_data,
  1632. "chat_id": form_data.get("chat_id", None),
  1633. },
  1634. }
  1635. # Handle pipeline filters
  1636. try:
  1637. payload = filter_pipeline(payload, user, models)
  1638. except Exception as e:
  1639. if len(e.args) > 1:
  1640. return JSONResponse(
  1641. status_code=e.args[0],
  1642. content={"detail": e.args[1]},
  1643. )
  1644. else:
  1645. return JSONResponse(
  1646. status_code=status.HTTP_400_BAD_REQUEST,
  1647. content={"detail": str(e)},
  1648. )
  1649. if "chat_id" in payload:
  1650. del payload["chat_id"]
  1651. return await generate_chat_completions(form_data=payload, user=user)
  1652. @app.post("/api/task/emoji/completions")
  1653. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1654. model_list = await get_all_models()
  1655. models = {model["id"]: model for model in model_list}
  1656. model_id = form_data["model"]
  1657. if model_id not in models:
  1658. raise HTTPException(
  1659. status_code=status.HTTP_404_NOT_FOUND,
  1660. detail="Model not found",
  1661. )
  1662. # Check if the user has a custom task model
  1663. # If the user has a custom task model, use that model
  1664. task_model_id = get_task_model_id(
  1665. model_id,
  1666. app.state.config.TASK_MODEL,
  1667. app.state.config.TASK_MODEL_EXTERNAL,
  1668. models,
  1669. )
  1670. log.debug(f"generating emoji using model {task_model_id} for user {user.email} ")
  1671. template = '''
  1672. 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., 😊, 😢, 😡, 😱).
  1673. Message: """{{prompt}}"""
  1674. '''
  1675. content = emoji_generation_template(
  1676. template,
  1677. form_data["prompt"],
  1678. {
  1679. "name": user.name,
  1680. "location": user.info.get("location") if user.info else None,
  1681. },
  1682. )
  1683. payload = {
  1684. "model": task_model_id,
  1685. "messages": [{"role": "user", "content": content}],
  1686. "stream": False,
  1687. **(
  1688. {"max_tokens": 4}
  1689. if models[task_model_id]["owned_by"] == "ollama"
  1690. else {
  1691. "max_completion_tokens": 4,
  1692. }
  1693. ),
  1694. "chat_id": form_data.get("chat_id", None),
  1695. "metadata": {"task": str(TASKS.EMOJI_GENERATION), "task_body": form_data},
  1696. }
  1697. # Handle pipeline filters
  1698. try:
  1699. payload = filter_pipeline(payload, user, models)
  1700. except Exception as e:
  1701. if len(e.args) > 1:
  1702. return JSONResponse(
  1703. status_code=e.args[0],
  1704. content={"detail": e.args[1]},
  1705. )
  1706. else:
  1707. return JSONResponse(
  1708. status_code=status.HTTP_400_BAD_REQUEST,
  1709. content={"detail": str(e)},
  1710. )
  1711. if "chat_id" in payload:
  1712. del payload["chat_id"]
  1713. return await generate_chat_completions(form_data=payload, user=user)
  1714. @app.post("/api/task/moa/completions")
  1715. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1716. model_list = await get_all_models()
  1717. models = {model["id"]: model for model in model_list}
  1718. model_id = form_data["model"]
  1719. if model_id not in models:
  1720. raise HTTPException(
  1721. status_code=status.HTTP_404_NOT_FOUND,
  1722. detail="Model not found",
  1723. )
  1724. # Check if the user has a custom task model
  1725. # If the user has a custom task model, use that model
  1726. task_model_id = get_task_model_id(
  1727. model_id,
  1728. app.state.config.TASK_MODEL,
  1729. app.state.config.TASK_MODEL_EXTERNAL,
  1730. models,
  1731. )
  1732. log.debug(f"generating MOA model {task_model_id} for user {user.email} ")
  1733. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1734. Your task is to synthesize these responses into a single, high-quality response. It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect. Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction. Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability.
  1735. Responses from models: {{responses}}"""
  1736. content = moa_response_generation_template(
  1737. template,
  1738. form_data["prompt"],
  1739. form_data["responses"],
  1740. )
  1741. payload = {
  1742. "model": task_model_id,
  1743. "messages": [{"role": "user", "content": content}],
  1744. "stream": form_data.get("stream", False),
  1745. "chat_id": form_data.get("chat_id", None),
  1746. "metadata": {
  1747. "task": str(TASKS.MOA_RESPONSE_GENERATION),
  1748. "task_body": form_data,
  1749. },
  1750. }
  1751. try:
  1752. payload = filter_pipeline(payload, user, models)
  1753. except Exception as e:
  1754. if len(e.args) > 1:
  1755. return JSONResponse(
  1756. status_code=e.args[0],
  1757. content={"detail": e.args[1]},
  1758. )
  1759. else:
  1760. return JSONResponse(
  1761. status_code=status.HTTP_400_BAD_REQUEST,
  1762. content={"detail": str(e)},
  1763. )
  1764. if "chat_id" in payload:
  1765. del payload["chat_id"]
  1766. return await generate_chat_completions(form_data=payload, user=user)
  1767. ##################################
  1768. #
  1769. # Pipelines Endpoints
  1770. #
  1771. ##################################
  1772. # TODO: Refactor pipelines API endpoints below into a separate file
  1773. @app.get("/api/pipelines/list")
  1774. async def get_pipelines_list(user=Depends(get_admin_user)):
  1775. responses = await get_openai_models_responses()
  1776. log.debug(f"get_pipelines_list: get_openai_models_responses returned {responses}")
  1777. urlIdxs = [
  1778. idx
  1779. for idx, response in enumerate(responses)
  1780. if response is not None and "pipelines" in response
  1781. ]
  1782. return {
  1783. "data": [
  1784. {
  1785. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1786. "idx": urlIdx,
  1787. }
  1788. for urlIdx in urlIdxs
  1789. ]
  1790. }
  1791. @app.post("/api/pipelines/upload")
  1792. async def upload_pipeline(
  1793. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1794. ):
  1795. print("upload_pipeline", urlIdx, file.filename)
  1796. # Check if the uploaded file is a python file
  1797. if not (file.filename and file.filename.endswith(".py")):
  1798. raise HTTPException(
  1799. status_code=status.HTTP_400_BAD_REQUEST,
  1800. detail="Only Python (.py) files are allowed.",
  1801. )
  1802. upload_folder = f"{CACHE_DIR}/pipelines"
  1803. os.makedirs(upload_folder, exist_ok=True)
  1804. file_path = os.path.join(upload_folder, file.filename)
  1805. r = None
  1806. try:
  1807. # Save the uploaded file
  1808. with open(file_path, "wb") as buffer:
  1809. shutil.copyfileobj(file.file, buffer)
  1810. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1811. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1812. headers = {"Authorization": f"Bearer {key}"}
  1813. with open(file_path, "rb") as f:
  1814. files = {"file": f}
  1815. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1816. r.raise_for_status()
  1817. data = r.json()
  1818. return {**data}
  1819. except Exception as e:
  1820. # Handle connection error here
  1821. print(f"Connection error: {e}")
  1822. detail = "Pipeline not found"
  1823. status_code = status.HTTP_404_NOT_FOUND
  1824. if r is not None:
  1825. status_code = r.status_code
  1826. try:
  1827. res = r.json()
  1828. if "detail" in res:
  1829. detail = res["detail"]
  1830. except Exception:
  1831. pass
  1832. raise HTTPException(
  1833. status_code=status_code,
  1834. detail=detail,
  1835. )
  1836. finally:
  1837. # Ensure the file is deleted after the upload is completed or on failure
  1838. if os.path.exists(file_path):
  1839. os.remove(file_path)
  1840. class AddPipelineForm(BaseModel):
  1841. url: str
  1842. urlIdx: int
  1843. @app.post("/api/pipelines/add")
  1844. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1845. r = None
  1846. try:
  1847. urlIdx = form_data.urlIdx
  1848. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1849. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1850. headers = {"Authorization": f"Bearer {key}"}
  1851. r = requests.post(
  1852. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1853. )
  1854. r.raise_for_status()
  1855. data = r.json()
  1856. return {**data}
  1857. except Exception as e:
  1858. # Handle connection error here
  1859. print(f"Connection error: {e}")
  1860. detail = "Pipeline not found"
  1861. if r is not None:
  1862. try:
  1863. res = r.json()
  1864. if "detail" in res:
  1865. detail = res["detail"]
  1866. except Exception:
  1867. pass
  1868. raise HTTPException(
  1869. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1870. detail=detail,
  1871. )
  1872. class DeletePipelineForm(BaseModel):
  1873. id: str
  1874. urlIdx: int
  1875. @app.delete("/api/pipelines/delete")
  1876. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1877. r = None
  1878. try:
  1879. urlIdx = form_data.urlIdx
  1880. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1881. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1882. headers = {"Authorization": f"Bearer {key}"}
  1883. r = requests.delete(
  1884. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1885. )
  1886. r.raise_for_status()
  1887. data = r.json()
  1888. return {**data}
  1889. except Exception as e:
  1890. # Handle connection error here
  1891. print(f"Connection error: {e}")
  1892. detail = "Pipeline not found"
  1893. if r is not None:
  1894. try:
  1895. res = r.json()
  1896. if "detail" in res:
  1897. detail = res["detail"]
  1898. except Exception:
  1899. pass
  1900. raise HTTPException(
  1901. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1902. detail=detail,
  1903. )
  1904. @app.get("/api/pipelines")
  1905. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1906. r = None
  1907. try:
  1908. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1909. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1910. headers = {"Authorization": f"Bearer {key}"}
  1911. r = requests.get(f"{url}/pipelines", headers=headers)
  1912. r.raise_for_status()
  1913. data = r.json()
  1914. return {**data}
  1915. except Exception as e:
  1916. # Handle connection error here
  1917. print(f"Connection error: {e}")
  1918. detail = "Pipeline not found"
  1919. if r is not None:
  1920. try:
  1921. res = r.json()
  1922. if "detail" in res:
  1923. detail = res["detail"]
  1924. except Exception:
  1925. pass
  1926. raise HTTPException(
  1927. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1928. detail=detail,
  1929. )
  1930. @app.get("/api/pipelines/{pipeline_id}/valves")
  1931. async def get_pipeline_valves(
  1932. urlIdx: Optional[int],
  1933. pipeline_id: str,
  1934. user=Depends(get_admin_user),
  1935. ):
  1936. r = None
  1937. try:
  1938. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1939. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1940. headers = {"Authorization": f"Bearer {key}"}
  1941. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1942. r.raise_for_status()
  1943. data = r.json()
  1944. return {**data}
  1945. except Exception as e:
  1946. # Handle connection error here
  1947. print(f"Connection error: {e}")
  1948. detail = "Pipeline not found"
  1949. if r is not None:
  1950. try:
  1951. res = r.json()
  1952. if "detail" in res:
  1953. detail = res["detail"]
  1954. except Exception:
  1955. pass
  1956. raise HTTPException(
  1957. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1958. detail=detail,
  1959. )
  1960. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1961. async def get_pipeline_valves_spec(
  1962. urlIdx: Optional[int],
  1963. pipeline_id: str,
  1964. user=Depends(get_admin_user),
  1965. ):
  1966. r = None
  1967. try:
  1968. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1969. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1970. headers = {"Authorization": f"Bearer {key}"}
  1971. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1972. r.raise_for_status()
  1973. data = r.json()
  1974. return {**data}
  1975. except Exception as e:
  1976. # Handle connection error here
  1977. print(f"Connection error: {e}")
  1978. detail = "Pipeline not found"
  1979. if r is not None:
  1980. try:
  1981. res = r.json()
  1982. if "detail" in res:
  1983. detail = res["detail"]
  1984. except Exception:
  1985. pass
  1986. raise HTTPException(
  1987. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1988. detail=detail,
  1989. )
  1990. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1991. async def update_pipeline_valves(
  1992. urlIdx: Optional[int],
  1993. pipeline_id: str,
  1994. form_data: dict,
  1995. user=Depends(get_admin_user),
  1996. ):
  1997. r = None
  1998. try:
  1999. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  2000. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  2001. headers = {"Authorization": f"Bearer {key}"}
  2002. r = requests.post(
  2003. f"{url}/{pipeline_id}/valves/update",
  2004. headers=headers,
  2005. json={**form_data},
  2006. )
  2007. r.raise_for_status()
  2008. data = r.json()
  2009. return {**data}
  2010. except Exception as e:
  2011. # Handle connection error here
  2012. print(f"Connection error: {e}")
  2013. detail = "Pipeline not found"
  2014. if r is not None:
  2015. try:
  2016. res = r.json()
  2017. if "detail" in res:
  2018. detail = res["detail"]
  2019. except Exception:
  2020. pass
  2021. raise HTTPException(
  2022. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2023. detail=detail,
  2024. )
  2025. ##################################
  2026. #
  2027. # Config Endpoints
  2028. #
  2029. ##################################
  2030. @app.get("/api/config")
  2031. async def get_app_config(request: Request):
  2032. user = None
  2033. if "token" in request.cookies:
  2034. token = request.cookies.get("token")
  2035. try:
  2036. data = decode_token(token)
  2037. except Exception as e:
  2038. log.debug(e)
  2039. raise HTTPException(
  2040. status_code=status.HTTP_401_UNAUTHORIZED,
  2041. detail="Invalid token",
  2042. )
  2043. if data is not None and "id" in data:
  2044. user = Users.get_user_by_id(data["id"])
  2045. onboarding = False
  2046. if user is None:
  2047. user_count = Users.get_num_users()
  2048. onboarding = user_count == 0
  2049. return {
  2050. **({"onboarding": True} if onboarding else {}),
  2051. "status": True,
  2052. "name": WEBUI_NAME,
  2053. "version": VERSION,
  2054. "default_locale": str(DEFAULT_LOCALE),
  2055. "oauth": {
  2056. "providers": {
  2057. name: config.get("name", name)
  2058. for name, config in OAUTH_PROVIDERS.items()
  2059. }
  2060. },
  2061. "features": {
  2062. "auth": WEBUI_AUTH,
  2063. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  2064. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  2065. "enable_api_key": webui_app.state.config.ENABLE_API_KEY,
  2066. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  2067. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  2068. **(
  2069. {
  2070. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  2071. "enable_image_generation": images_app.state.config.ENABLED,
  2072. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  2073. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  2074. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  2075. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  2076. }
  2077. if user is not None
  2078. else {}
  2079. ),
  2080. },
  2081. **(
  2082. {
  2083. "default_models": webui_app.state.config.DEFAULT_MODELS,
  2084. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  2085. "audio": {
  2086. "tts": {
  2087. "engine": audio_app.state.config.TTS_ENGINE,
  2088. "voice": audio_app.state.config.TTS_VOICE,
  2089. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  2090. },
  2091. "stt": {
  2092. "engine": audio_app.state.config.STT_ENGINE,
  2093. },
  2094. },
  2095. "file": {
  2096. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  2097. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  2098. },
  2099. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  2100. }
  2101. if user is not None
  2102. else {}
  2103. ),
  2104. }
  2105. # TODO: webhook endpoint should be under config endpoints
  2106. @app.get("/api/webhook")
  2107. async def get_webhook_url(user=Depends(get_admin_user)):
  2108. return {
  2109. "url": app.state.config.WEBHOOK_URL,
  2110. }
  2111. class UrlForm(BaseModel):
  2112. url: str
  2113. @app.post("/api/webhook")
  2114. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  2115. app.state.config.WEBHOOK_URL = form_data.url
  2116. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  2117. return {"url": app.state.config.WEBHOOK_URL}
  2118. @app.get("/api/version")
  2119. async def get_app_version():
  2120. return {
  2121. "version": VERSION,
  2122. }
  2123. @app.get("/api/changelog")
  2124. async def get_app_changelog():
  2125. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  2126. @app.get("/api/version/updates")
  2127. async def get_app_latest_release_version():
  2128. if OFFLINE_MODE:
  2129. log.debug(
  2130. f"Offline mode is enabled, returning current version as latest version"
  2131. )
  2132. return {"current": VERSION, "latest": VERSION}
  2133. try:
  2134. timeout = aiohttp.ClientTimeout(total=1)
  2135. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  2136. async with session.get(
  2137. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  2138. ) as response:
  2139. response.raise_for_status()
  2140. data = await response.json()
  2141. latest_version = data["tag_name"]
  2142. return {"current": VERSION, "latest": latest_version[1:]}
  2143. except Exception as e:
  2144. log.debug(e)
  2145. return {"current": VERSION, "latest": VERSION}
  2146. ############################
  2147. # OAuth Login & Callback
  2148. ############################
  2149. # SessionMiddleware is used by authlib for oauth
  2150. if len(OAUTH_PROVIDERS) > 0:
  2151. app.add_middleware(
  2152. SessionMiddleware,
  2153. secret_key=WEBUI_SECRET_KEY,
  2154. session_cookie="oui-session",
  2155. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  2156. https_only=WEBUI_SESSION_COOKIE_SECURE,
  2157. )
  2158. @app.get("/oauth/{provider}/login")
  2159. async def oauth_login(provider: str, request: Request):
  2160. return await oauth_manager.handle_login(provider, request)
  2161. # OAuth login logic is as follows:
  2162. # 1. Attempt to find a user with matching subject ID, tied to the provider
  2163. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  2164. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  2165. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  2166. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  2167. @app.get("/oauth/{provider}/callback")
  2168. async def oauth_callback(provider: str, request: Request, response: Response):
  2169. return await oauth_manager.handle_callback(provider, request, response)
  2170. @app.get("/manifest.json")
  2171. async def get_manifest_json():
  2172. return {
  2173. "name": WEBUI_NAME,
  2174. "short_name": WEBUI_NAME,
  2175. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  2176. "start_url": "/",
  2177. "display": "standalone",
  2178. "background_color": "#343541",
  2179. "orientation": "natural",
  2180. "icons": [
  2181. {
  2182. "src": "/static/logo.png",
  2183. "type": "image/png",
  2184. "sizes": "500x500",
  2185. "purpose": "any",
  2186. },
  2187. {
  2188. "src": "/static/logo.png",
  2189. "type": "image/png",
  2190. "sizes": "500x500",
  2191. "purpose": "maskable",
  2192. },
  2193. ],
  2194. }
  2195. @app.get("/opensearch.xml")
  2196. async def get_opensearch_xml():
  2197. xml_content = rf"""
  2198. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  2199. <ShortName>{WEBUI_NAME}</ShortName>
  2200. <Description>Search {WEBUI_NAME}</Description>
  2201. <InputEncoding>UTF-8</InputEncoding>
  2202. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  2203. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  2204. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  2205. </OpenSearchDescription>
  2206. """
  2207. return Response(content=xml_content, media_type="application/xml")
  2208. @app.get("/health")
  2209. async def healthcheck():
  2210. return {"status": True}
  2211. @app.get("/health/db")
  2212. async def healthcheck_with_db():
  2213. Session.execute(text("SELECT 1;")).all()
  2214. return {"status": True}
  2215. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  2216. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  2217. if os.path.exists(FRONTEND_BUILD_DIR):
  2218. mimetypes.add_type("text/javascript", ".js")
  2219. app.mount(
  2220. "/",
  2221. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  2222. name="spa-static-files",
  2223. )
  2224. else:
  2225. log.warning(
  2226. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  2227. )