main.py 66 KB

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