main.py 67 KB

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