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 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_db, 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. from alembic.config import Config
  154. from alembic import command
  155. alembic_cfg = Config(f"{BACKEND_DIR}/alembic.ini")
  156. alembic_cfg.set_main_option("sqlalchemy.url", DATABASE_URL)
  157. alembic_cfg.set_main_option("script_location", f"{BACKEND_DIR}/migrations")
  158. command.upgrade(alembic_cfg, "head")
  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. SessionLocal(),
  344. )
  345. # Flag to skip RAG completions if file_handler is present in tools/functions
  346. skip_files = False
  347. if data.get("citations"):
  348. show_citations = True
  349. del data["citations"]
  350. model_id = data["model"]
  351. if model_id not in app.state.MODELS:
  352. raise HTTPException(
  353. status_code=status.HTTP_404_NOT_FOUND,
  354. detail="Model not found",
  355. )
  356. model = app.state.MODELS[model_id]
  357. def get_priority(function_id):
  358. function = Functions.get_function_by_id(function_id)
  359. if function is not None and hasattr(function, "valves"):
  360. return (function.valves if function.valves else {}).get(
  361. "priority", 0
  362. )
  363. return 0
  364. filter_ids = [
  365. function.id
  366. for function in Functions.get_functions_by_type(
  367. "filter", active_only=True
  368. )
  369. ]
  370. # Check if the model has any filters
  371. if "info" in model and "meta" in model["info"]:
  372. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  373. filter_ids = list(set(filter_ids))
  374. filter_ids.sort(key=get_priority)
  375. for filter_id in filter_ids:
  376. filter = Functions.get_function_by_id(filter_id)
  377. if filter:
  378. if filter_id in webui_app.state.FUNCTIONS:
  379. function_module = webui_app.state.FUNCTIONS[filter_id]
  380. else:
  381. function_module, function_type, frontmatter = (
  382. load_function_module_by_id(filter_id)
  383. )
  384. webui_app.state.FUNCTIONS[filter_id] = function_module
  385. # Check if the function has a file_handler variable
  386. if hasattr(function_module, "file_handler"):
  387. skip_files = function_module.file_handler
  388. if hasattr(function_module, "valves") and hasattr(
  389. function_module, "Valves"
  390. ):
  391. valves = Functions.get_function_valves_by_id(filter_id)
  392. function_module.valves = function_module.Valves(
  393. **(valves if valves else {})
  394. )
  395. try:
  396. if hasattr(function_module, "inlet"):
  397. inlet = function_module.inlet
  398. # Get the signature of the function
  399. sig = inspect.signature(inlet)
  400. params = {"body": data}
  401. if "__user__" in sig.parameters:
  402. __user__ = {
  403. "id": user.id,
  404. "email": user.email,
  405. "name": user.name,
  406. "role": user.role,
  407. }
  408. try:
  409. if hasattr(function_module, "UserValves"):
  410. __user__["valves"] = function_module.UserValves(
  411. **Functions.get_user_valves_by_id_and_user_id(
  412. filter_id, user.id
  413. )
  414. )
  415. except Exception as e:
  416. print(e)
  417. params = {**params, "__user__": __user__}
  418. if "__id__" in sig.parameters:
  419. params = {
  420. **params,
  421. "__id__": filter_id,
  422. }
  423. if inspect.iscoroutinefunction(inlet):
  424. data = await inlet(**params)
  425. else:
  426. data = inlet(**params)
  427. except Exception as e:
  428. print(f"Error: {e}")
  429. return JSONResponse(
  430. status_code=status.HTTP_400_BAD_REQUEST,
  431. content={"detail": str(e)},
  432. )
  433. # Set the task model
  434. task_model_id = data["model"]
  435. # Check if the user has a custom task model and use that model
  436. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  437. if (
  438. app.state.config.TASK_MODEL
  439. and app.state.config.TASK_MODEL in app.state.MODELS
  440. ):
  441. task_model_id = app.state.config.TASK_MODEL
  442. else:
  443. if (
  444. app.state.config.TASK_MODEL_EXTERNAL
  445. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  446. ):
  447. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  448. prompt = get_last_user_message(data["messages"])
  449. context = ""
  450. # If tool_ids field is present, call the functions
  451. if "tool_ids" in data:
  452. print(data["tool_ids"])
  453. for tool_id in data["tool_ids"]:
  454. print(tool_id)
  455. try:
  456. response, citation, file_handler = (
  457. await get_function_call_response(
  458. messages=data["messages"],
  459. files=data.get("files", []),
  460. tool_id=tool_id,
  461. template=app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  462. task_model_id=task_model_id,
  463. user=user,
  464. )
  465. )
  466. print(file_handler)
  467. if isinstance(response, str):
  468. context += ("\n" if context != "" else "") + response
  469. if citation:
  470. citations.append(citation)
  471. show_citations = True
  472. if file_handler:
  473. skip_files = True
  474. except Exception as e:
  475. print(f"Error: {e}")
  476. del data["tool_ids"]
  477. print(f"tool_context: {context}")
  478. # If files field is present, generate RAG completions
  479. # If skip_files is True, skip the RAG completions
  480. if "files" in data:
  481. if not skip_files:
  482. data = {**data}
  483. rag_context, rag_citations = get_rag_context(
  484. files=data["files"],
  485. messages=data["messages"],
  486. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  487. k=rag_app.state.config.TOP_K,
  488. reranking_function=rag_app.state.sentence_transformer_rf,
  489. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  490. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  491. )
  492. if rag_context:
  493. context += ("\n" if context != "" else "") + rag_context
  494. log.debug(f"rag_context: {rag_context}, citations: {citations}")
  495. if rag_citations:
  496. citations.extend(rag_citations)
  497. del data["files"]
  498. if show_citations and len(citations) > 0:
  499. data_items.append({"citations": citations})
  500. if context != "":
  501. system_prompt = rag_template(
  502. rag_app.state.config.RAG_TEMPLATE, context, prompt
  503. )
  504. print(system_prompt)
  505. data["messages"] = add_or_update_system_message(
  506. system_prompt, data["messages"]
  507. )
  508. modified_body_bytes = json.dumps(data).encode("utf-8")
  509. # Replace the request body with the modified one
  510. request._body = modified_body_bytes
  511. # Set custom header to ensure content-length matches new body length
  512. request.headers.__dict__["_list"] = [
  513. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  514. *[
  515. (k, v)
  516. for k, v in request.headers.raw
  517. if k.lower() != b"content-length"
  518. ],
  519. ]
  520. response = await call_next(request)
  521. if isinstance(response, StreamingResponse):
  522. # If it's a streaming response, inject it as SSE event or NDJSON line
  523. content_type = response.headers.get("Content-Type")
  524. if "text/event-stream" in content_type:
  525. return StreamingResponse(
  526. self.openai_stream_wrapper(response.body_iterator, data_items),
  527. )
  528. if "application/x-ndjson" in content_type:
  529. return StreamingResponse(
  530. self.ollama_stream_wrapper(response.body_iterator, data_items),
  531. )
  532. else:
  533. return response
  534. # If it's not a chat completion request, just pass it through
  535. response = await call_next(request)
  536. return response
  537. async def _receive(self, body: bytes):
  538. return {"type": "http.request", "body": body, "more_body": False}
  539. async def openai_stream_wrapper(self, original_generator, data_items):
  540. for item in data_items:
  541. yield f"data: {json.dumps(item)}\n\n"
  542. async for data in original_generator:
  543. yield data
  544. async def ollama_stream_wrapper(self, original_generator, data_items):
  545. for item in data_items:
  546. yield f"{json.dumps(item)}\n"
  547. async for data in original_generator:
  548. yield data
  549. app.add_middleware(ChatCompletionMiddleware)
  550. ##################################
  551. #
  552. # Pipeline Middleware
  553. #
  554. ##################################
  555. def filter_pipeline(payload, user):
  556. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  557. model_id = payload["model"]
  558. filters = [
  559. model
  560. for model in app.state.MODELS.values()
  561. if "pipeline" in model
  562. and "type" in model["pipeline"]
  563. and model["pipeline"]["type"] == "filter"
  564. and (
  565. model["pipeline"]["pipelines"] == ["*"]
  566. or any(
  567. model_id == target_model_id
  568. for target_model_id in model["pipeline"]["pipelines"]
  569. )
  570. )
  571. ]
  572. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  573. model = app.state.MODELS[model_id]
  574. if "pipeline" in model:
  575. sorted_filters.append(model)
  576. for filter in sorted_filters:
  577. r = None
  578. try:
  579. urlIdx = filter["urlIdx"]
  580. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  581. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  582. if key != "":
  583. headers = {"Authorization": f"Bearer {key}"}
  584. r = requests.post(
  585. f"{url}/{filter['id']}/filter/inlet",
  586. headers=headers,
  587. json={
  588. "user": user,
  589. "body": payload,
  590. },
  591. )
  592. r.raise_for_status()
  593. payload = r.json()
  594. except Exception as e:
  595. # Handle connection error here
  596. print(f"Connection error: {e}")
  597. if r is not None:
  598. try:
  599. res = r.json()
  600. except:
  601. pass
  602. if "detail" in res:
  603. raise Exception(r.status_code, res["detail"])
  604. else:
  605. pass
  606. if "pipeline" not in app.state.MODELS[model_id]:
  607. if "chat_id" in payload:
  608. del payload["chat_id"]
  609. if "title" in payload:
  610. del payload["title"]
  611. if "task" in payload:
  612. del payload["task"]
  613. return payload
  614. class PipelineMiddleware(BaseHTTPMiddleware):
  615. async def dispatch(self, request: Request, call_next):
  616. if request.method == "POST" and (
  617. "/ollama/api/chat" in request.url.path
  618. or "/chat/completions" in request.url.path
  619. ):
  620. log.debug(f"request.url.path: {request.url.path}")
  621. # Read the original request body
  622. body = await request.body()
  623. # Decode body to string
  624. body_str = body.decode("utf-8")
  625. # Parse string to JSON
  626. data = json.loads(body_str) if body_str else {}
  627. user = get_current_user(
  628. request,
  629. get_http_authorization_cred(request.headers.get("Authorization")),
  630. SessionLocal(),
  631. )
  632. try:
  633. data = filter_pipeline(data, user)
  634. except Exception as e:
  635. return JSONResponse(
  636. status_code=e.args[0],
  637. content={"detail": e.args[1]},
  638. )
  639. modified_body_bytes = json.dumps(data).encode("utf-8")
  640. # Replace the request body with the modified one
  641. request._body = modified_body_bytes
  642. # Set custom header to ensure content-length matches new body length
  643. request.headers.__dict__["_list"] = [
  644. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  645. *[
  646. (k, v)
  647. for k, v in request.headers.raw
  648. if k.lower() != b"content-length"
  649. ],
  650. ]
  651. response = await call_next(request)
  652. return response
  653. async def _receive(self, body: bytes):
  654. return {"type": "http.request", "body": body, "more_body": False}
  655. app.add_middleware(PipelineMiddleware)
  656. app.add_middleware(
  657. CORSMiddleware,
  658. allow_origins=origins,
  659. allow_credentials=True,
  660. allow_methods=["*"],
  661. allow_headers=["*"],
  662. )
  663. @app.middleware("http")
  664. async def check_url(request: Request, call_next):
  665. if len(app.state.MODELS) == 0:
  666. db = SessionLocal()
  667. await get_all_models(db)
  668. db.commit()
  669. else:
  670. pass
  671. start_time = int(time.time())
  672. response = await call_next(request)
  673. process_time = int(time.time()) - start_time
  674. response.headers["X-Process-Time"] = str(process_time)
  675. return response
  676. @app.middleware("http")
  677. async def update_embedding_function(request: Request, call_next):
  678. response = await call_next(request)
  679. if "/embedding/update" in request.url.path:
  680. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  681. return response
  682. app.mount("/ws", socket_app)
  683. app.mount("/ollama", ollama_app)
  684. app.mount("/openai", openai_app)
  685. app.mount("/images/api/v1", images_app)
  686. app.mount("/audio/api/v1", audio_app)
  687. app.mount("/rag/api/v1", rag_app)
  688. app.mount("/api/v1", webui_app)
  689. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  690. async def get_all_models(db: Session):
  691. pipe_models = []
  692. openai_models = []
  693. ollama_models = []
  694. pipe_models = await get_pipe_models(db)
  695. if app.state.config.ENABLE_OPENAI_API:
  696. openai_models = await get_openai_models()
  697. openai_models = openai_models["data"]
  698. if app.state.config.ENABLE_OLLAMA_API:
  699. ollama_models = await get_ollama_models()
  700. ollama_models = [
  701. {
  702. "id": model["model"],
  703. "name": model["name"],
  704. "object": "model",
  705. "created": int(time.time()),
  706. "owned_by": "ollama",
  707. "ollama": model,
  708. }
  709. for model in ollama_models["models"]
  710. ]
  711. models = pipe_models + openai_models + ollama_models
  712. custom_models = Models.get_all_models(db)
  713. for custom_model in custom_models:
  714. if custom_model.base_model_id == None:
  715. for model in models:
  716. if (
  717. custom_model.id == model["id"]
  718. or custom_model.id == model["id"].split(":")[0]
  719. ):
  720. model["name"] = custom_model.name
  721. model["info"] = custom_model.model_dump()
  722. else:
  723. owned_by = "openai"
  724. for model in models:
  725. if (
  726. custom_model.base_model_id == model["id"]
  727. or custom_model.base_model_id == model["id"].split(":")[0]
  728. ):
  729. owned_by = model["owned_by"]
  730. break
  731. models.append(
  732. {
  733. "id": custom_model.id,
  734. "name": custom_model.name,
  735. "object": "model",
  736. "created": custom_model.created_at,
  737. "owned_by": owned_by,
  738. "info": custom_model.model_dump(),
  739. "preset": True,
  740. }
  741. )
  742. app.state.MODELS = {model["id"]: model for model in models}
  743. webui_app.state.MODELS = app.state.MODELS
  744. return models
  745. @app.get("/api/models")
  746. async def get_models(user=Depends(get_verified_user), db=Depends(get_db)):
  747. models = await get_all_models(db)
  748. # Filter out filter pipelines
  749. models = [
  750. model
  751. for model in models
  752. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  753. ]
  754. if app.state.config.ENABLE_MODEL_FILTER:
  755. if user.role == "user":
  756. models = list(
  757. filter(
  758. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  759. models,
  760. )
  761. )
  762. return {"data": models}
  763. return {"data": models}
  764. @app.post("/api/chat/completions")
  765. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  766. model_id = form_data["model"]
  767. if model_id not in app.state.MODELS:
  768. raise HTTPException(
  769. status_code=status.HTTP_404_NOT_FOUND,
  770. detail="Model not found",
  771. )
  772. model = app.state.MODELS[model_id]
  773. print(model)
  774. pipe = model.get("pipe")
  775. if pipe:
  776. return await generate_function_chat_completion(form_data, user=user)
  777. if model["owned_by"] == "ollama":
  778. return await generate_ollama_chat_completion(form_data, user=user)
  779. else:
  780. return await generate_openai_chat_completion(form_data, user=user)
  781. @app.post("/api/chat/completed")
  782. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  783. data = form_data
  784. model_id = data["model"]
  785. if model_id not in app.state.MODELS:
  786. raise HTTPException(
  787. status_code=status.HTTP_404_NOT_FOUND,
  788. detail="Model not found",
  789. )
  790. model = app.state.MODELS[model_id]
  791. filters = [
  792. model
  793. for model in app.state.MODELS.values()
  794. if "pipeline" in model
  795. and "type" in model["pipeline"]
  796. and model["pipeline"]["type"] == "filter"
  797. and (
  798. model["pipeline"]["pipelines"] == ["*"]
  799. or any(
  800. model_id == target_model_id
  801. for target_model_id in model["pipeline"]["pipelines"]
  802. )
  803. )
  804. ]
  805. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  806. if "pipeline" in model:
  807. sorted_filters = [model] + sorted_filters
  808. for filter in sorted_filters:
  809. r = None
  810. try:
  811. urlIdx = filter["urlIdx"]
  812. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  813. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  814. if key != "":
  815. headers = {"Authorization": f"Bearer {key}"}
  816. r = requests.post(
  817. f"{url}/{filter['id']}/filter/outlet",
  818. headers=headers,
  819. json={
  820. "user": {
  821. "id": user.id,
  822. "name": user.name,
  823. "email": user.email,
  824. "role": user.role,
  825. },
  826. "body": data,
  827. },
  828. )
  829. r.raise_for_status()
  830. data = r.json()
  831. except Exception as e:
  832. # Handle connection error here
  833. print(f"Connection error: {e}")
  834. if r is not None:
  835. try:
  836. res = r.json()
  837. if "detail" in res:
  838. return JSONResponse(
  839. status_code=r.status_code,
  840. content=res,
  841. )
  842. except:
  843. pass
  844. else:
  845. pass
  846. def get_priority(function_id):
  847. function = Functions.get_function_by_id(function_id)
  848. if function is not None and hasattr(function, "valves"):
  849. return (function.valves if function.valves else {}).get("priority", 0)
  850. return 0
  851. filter_ids = [
  852. function.id
  853. for function in Functions.get_functions_by_type("filter", active_only=True)
  854. ]
  855. # Check if the model has any filters
  856. if "info" in model and "meta" in model["info"]:
  857. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  858. filter_ids = list(set(filter_ids))
  859. # Sort filter_ids by priority, using the get_priority function
  860. filter_ids.sort(key=get_priority)
  861. for filter_id in filter_ids:
  862. filter = Functions.get_function_by_id(filter_id)
  863. if filter:
  864. if filter_id in webui_app.state.FUNCTIONS:
  865. function_module = webui_app.state.FUNCTIONS[filter_id]
  866. else:
  867. function_module, function_type, frontmatter = (
  868. load_function_module_by_id(filter_id)
  869. )
  870. webui_app.state.FUNCTIONS[filter_id] = function_module
  871. if hasattr(function_module, "valves") and hasattr(
  872. function_module, "Valves"
  873. ):
  874. valves = Functions.get_function_valves_by_id(filter_id)
  875. function_module.valves = function_module.Valves(
  876. **(valves if valves else {})
  877. )
  878. try:
  879. if hasattr(function_module, "outlet"):
  880. outlet = function_module.outlet
  881. # Get the signature of the function
  882. sig = inspect.signature(outlet)
  883. params = {"body": data}
  884. if "__user__" in sig.parameters:
  885. __user__ = {
  886. "id": user.id,
  887. "email": user.email,
  888. "name": user.name,
  889. "role": user.role,
  890. }
  891. try:
  892. if hasattr(function_module, "UserValves"):
  893. __user__["valves"] = function_module.UserValves(
  894. **Functions.get_user_valves_by_id_and_user_id(
  895. filter_id, user.id
  896. )
  897. )
  898. except Exception as e:
  899. print(e)
  900. params = {**params, "__user__": __user__}
  901. if "__id__" in sig.parameters:
  902. params = {
  903. **params,
  904. "__id__": filter_id,
  905. }
  906. if inspect.iscoroutinefunction(outlet):
  907. data = await outlet(**params)
  908. else:
  909. data = outlet(**params)
  910. except Exception as e:
  911. print(f"Error: {e}")
  912. return JSONResponse(
  913. status_code=status.HTTP_400_BAD_REQUEST,
  914. content={"detail": str(e)},
  915. )
  916. return data
  917. ##################################
  918. #
  919. # Task Endpoints
  920. #
  921. ##################################
  922. # TODO: Refactor task API endpoints below into a separate file
  923. @app.get("/api/task/config")
  924. async def get_task_config(user=Depends(get_verified_user)):
  925. return {
  926. "TASK_MODEL": app.state.config.TASK_MODEL,
  927. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  928. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  929. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  930. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  931. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  932. }
  933. class TaskConfigForm(BaseModel):
  934. TASK_MODEL: Optional[str]
  935. TASK_MODEL_EXTERNAL: Optional[str]
  936. TITLE_GENERATION_PROMPT_TEMPLATE: str
  937. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  938. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  939. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  940. @app.post("/api/task/config/update")
  941. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  942. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  943. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  944. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  945. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  946. )
  947. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  948. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  949. )
  950. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  951. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  952. )
  953. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  954. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  955. )
  956. return {
  957. "TASK_MODEL": app.state.config.TASK_MODEL,
  958. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  959. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  960. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  961. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  962. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  963. }
  964. @app.post("/api/task/title/completions")
  965. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  966. print("generate_title")
  967. model_id = form_data["model"]
  968. if model_id not in app.state.MODELS:
  969. raise HTTPException(
  970. status_code=status.HTTP_404_NOT_FOUND,
  971. detail="Model not found",
  972. )
  973. # Check if the user has a custom task model
  974. # If the user has a custom task model, use that model
  975. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  976. if app.state.config.TASK_MODEL:
  977. task_model_id = app.state.config.TASK_MODEL
  978. if task_model_id in app.state.MODELS:
  979. model_id = task_model_id
  980. else:
  981. if app.state.config.TASK_MODEL_EXTERNAL:
  982. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  983. if task_model_id in app.state.MODELS:
  984. model_id = task_model_id
  985. print(model_id)
  986. model = app.state.MODELS[model_id]
  987. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  988. content = title_generation_template(
  989. template,
  990. form_data["prompt"],
  991. {
  992. "name": user.name,
  993. "location": user.info.get("location") if user.info else None,
  994. },
  995. )
  996. payload = {
  997. "model": model_id,
  998. "messages": [{"role": "user", "content": content}],
  999. "stream": False,
  1000. "max_tokens": 50,
  1001. "chat_id": form_data.get("chat_id", None),
  1002. "title": True,
  1003. }
  1004. log.debug(payload)
  1005. try:
  1006. payload = filter_pipeline(payload, user)
  1007. except Exception as e:
  1008. return JSONResponse(
  1009. status_code=e.args[0],
  1010. content={"detail": e.args[1]},
  1011. )
  1012. return await generate_chat_completions(form_data=payload, user=user)
  1013. @app.post("/api/task/query/completions")
  1014. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1015. print("generate_search_query")
  1016. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1017. raise HTTPException(
  1018. status_code=status.HTTP_400_BAD_REQUEST,
  1019. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1020. )
  1021. model_id = form_data["model"]
  1022. if model_id not in app.state.MODELS:
  1023. raise HTTPException(
  1024. status_code=status.HTTP_404_NOT_FOUND,
  1025. detail="Model not found",
  1026. )
  1027. # Check if the user has a custom task model
  1028. # If the user has a custom task model, use that model
  1029. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1030. if app.state.config.TASK_MODEL:
  1031. task_model_id = app.state.config.TASK_MODEL
  1032. if task_model_id in app.state.MODELS:
  1033. model_id = task_model_id
  1034. else:
  1035. if app.state.config.TASK_MODEL_EXTERNAL:
  1036. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1037. if task_model_id in app.state.MODELS:
  1038. model_id = task_model_id
  1039. print(model_id)
  1040. model = app.state.MODELS[model_id]
  1041. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1042. content = search_query_generation_template(
  1043. template, form_data["prompt"], {"name": user.name}
  1044. )
  1045. payload = {
  1046. "model": model_id,
  1047. "messages": [{"role": "user", "content": content}],
  1048. "stream": False,
  1049. "max_tokens": 30,
  1050. "task": True,
  1051. }
  1052. print(payload)
  1053. try:
  1054. payload = filter_pipeline(payload, user)
  1055. except Exception as e:
  1056. return JSONResponse(
  1057. status_code=e.args[0],
  1058. content={"detail": e.args[1]},
  1059. )
  1060. return await generate_chat_completions(form_data=payload, user=user)
  1061. @app.post("/api/task/emoji/completions")
  1062. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1063. print("generate_emoji")
  1064. model_id = form_data["model"]
  1065. if model_id not in app.state.MODELS:
  1066. raise HTTPException(
  1067. status_code=status.HTTP_404_NOT_FOUND,
  1068. detail="Model not found",
  1069. )
  1070. # Check if the user has a custom task model
  1071. # If the user has a custom task model, use that model
  1072. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1073. if app.state.config.TASK_MODEL:
  1074. task_model_id = app.state.config.TASK_MODEL
  1075. if task_model_id in app.state.MODELS:
  1076. model_id = task_model_id
  1077. else:
  1078. if app.state.config.TASK_MODEL_EXTERNAL:
  1079. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1080. if task_model_id in app.state.MODELS:
  1081. model_id = task_model_id
  1082. print(model_id)
  1083. model = app.state.MODELS[model_id]
  1084. template = '''
  1085. 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., 😊, 😢, 😡, 😱).
  1086. Message: """{{prompt}}"""
  1087. '''
  1088. content = title_generation_template(
  1089. template,
  1090. form_data["prompt"],
  1091. {
  1092. "name": user.name,
  1093. "location": user.info.get("location") if user.info else None,
  1094. },
  1095. )
  1096. payload = {
  1097. "model": model_id,
  1098. "messages": [{"role": "user", "content": content}],
  1099. "stream": False,
  1100. "max_tokens": 4,
  1101. "chat_id": form_data.get("chat_id", None),
  1102. "task": True,
  1103. }
  1104. log.debug(payload)
  1105. try:
  1106. payload = filter_pipeline(payload, user)
  1107. except Exception as e:
  1108. return JSONResponse(
  1109. status_code=e.args[0],
  1110. content={"detail": e.args[1]},
  1111. )
  1112. return await generate_chat_completions(form_data=payload, user=user)
  1113. @app.post("/api/task/tools/completions")
  1114. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  1115. print("get_tools_function_calling")
  1116. model_id = form_data["model"]
  1117. if model_id not in app.state.MODELS:
  1118. raise HTTPException(
  1119. status_code=status.HTTP_404_NOT_FOUND,
  1120. detail="Model not found",
  1121. )
  1122. # Check if the user has a custom task model
  1123. # If the user has a custom task model, use that model
  1124. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1125. if app.state.config.TASK_MODEL:
  1126. task_model_id = app.state.config.TASK_MODEL
  1127. if task_model_id in app.state.MODELS:
  1128. model_id = task_model_id
  1129. else:
  1130. if app.state.config.TASK_MODEL_EXTERNAL:
  1131. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1132. if task_model_id in app.state.MODELS:
  1133. model_id = task_model_id
  1134. print(model_id)
  1135. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1136. try:
  1137. context, citation, file_handler = await get_function_call_response(
  1138. form_data["messages"],
  1139. form_data.get("files", []),
  1140. form_data["tool_id"],
  1141. template,
  1142. model_id,
  1143. user,
  1144. )
  1145. return context
  1146. except Exception as e:
  1147. return JSONResponse(
  1148. status_code=e.args[0],
  1149. content={"detail": e.args[1]},
  1150. )
  1151. ##################################
  1152. #
  1153. # Pipelines Endpoints
  1154. #
  1155. ##################################
  1156. # TODO: Refactor pipelines API endpoints below into a separate file
  1157. @app.get("/api/pipelines/list")
  1158. async def get_pipelines_list(user=Depends(get_admin_user)):
  1159. responses = await get_openai_models(raw=True)
  1160. print(responses)
  1161. urlIdxs = [
  1162. idx
  1163. for idx, response in enumerate(responses)
  1164. if response != None and "pipelines" in response
  1165. ]
  1166. return {
  1167. "data": [
  1168. {
  1169. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1170. "idx": urlIdx,
  1171. }
  1172. for urlIdx in urlIdxs
  1173. ]
  1174. }
  1175. @app.post("/api/pipelines/upload")
  1176. async def upload_pipeline(
  1177. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1178. ):
  1179. print("upload_pipeline", urlIdx, file.filename)
  1180. # Check if the uploaded file is a python file
  1181. if not file.filename.endswith(".py"):
  1182. raise HTTPException(
  1183. status_code=status.HTTP_400_BAD_REQUEST,
  1184. detail="Only Python (.py) files are allowed.",
  1185. )
  1186. upload_folder = f"{CACHE_DIR}/pipelines"
  1187. os.makedirs(upload_folder, exist_ok=True)
  1188. file_path = os.path.join(upload_folder, file.filename)
  1189. try:
  1190. # Save the uploaded file
  1191. with open(file_path, "wb") as buffer:
  1192. shutil.copyfileobj(file.file, buffer)
  1193. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1194. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1195. headers = {"Authorization": f"Bearer {key}"}
  1196. with open(file_path, "rb") as f:
  1197. files = {"file": f}
  1198. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1199. r.raise_for_status()
  1200. data = r.json()
  1201. return {**data}
  1202. except Exception as e:
  1203. # Handle connection error here
  1204. print(f"Connection error: {e}")
  1205. detail = "Pipeline not found"
  1206. if r is not None:
  1207. try:
  1208. res = r.json()
  1209. if "detail" in res:
  1210. detail = res["detail"]
  1211. except:
  1212. pass
  1213. raise HTTPException(
  1214. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1215. detail=detail,
  1216. )
  1217. finally:
  1218. # Ensure the file is deleted after the upload is completed or on failure
  1219. if os.path.exists(file_path):
  1220. os.remove(file_path)
  1221. class AddPipelineForm(BaseModel):
  1222. url: str
  1223. urlIdx: int
  1224. @app.post("/api/pipelines/add")
  1225. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1226. r = None
  1227. try:
  1228. urlIdx = form_data.urlIdx
  1229. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1230. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1231. headers = {"Authorization": f"Bearer {key}"}
  1232. r = requests.post(
  1233. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1234. )
  1235. r.raise_for_status()
  1236. data = r.json()
  1237. return {**data}
  1238. except Exception as e:
  1239. # Handle connection error here
  1240. print(f"Connection error: {e}")
  1241. detail = "Pipeline not found"
  1242. if r is not None:
  1243. try:
  1244. res = r.json()
  1245. if "detail" in res:
  1246. detail = res["detail"]
  1247. except:
  1248. pass
  1249. raise HTTPException(
  1250. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1251. detail=detail,
  1252. )
  1253. class DeletePipelineForm(BaseModel):
  1254. id: str
  1255. urlIdx: int
  1256. @app.delete("/api/pipelines/delete")
  1257. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1258. r = None
  1259. try:
  1260. urlIdx = form_data.urlIdx
  1261. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1262. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1263. headers = {"Authorization": f"Bearer {key}"}
  1264. r = requests.delete(
  1265. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1266. )
  1267. r.raise_for_status()
  1268. data = r.json()
  1269. return {**data}
  1270. except Exception as e:
  1271. # Handle connection error here
  1272. print(f"Connection error: {e}")
  1273. detail = "Pipeline not found"
  1274. if r is not None:
  1275. try:
  1276. res = r.json()
  1277. if "detail" in res:
  1278. detail = res["detail"]
  1279. except:
  1280. pass
  1281. raise HTTPException(
  1282. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1283. detail=detail,
  1284. )
  1285. @app.get("/api/pipelines")
  1286. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1287. r = None
  1288. try:
  1289. urlIdx
  1290. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1291. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1292. headers = {"Authorization": f"Bearer {key}"}
  1293. r = requests.get(f"{url}/pipelines", headers=headers)
  1294. r.raise_for_status()
  1295. data = r.json()
  1296. return {**data}
  1297. except Exception as e:
  1298. # Handle connection error here
  1299. print(f"Connection error: {e}")
  1300. detail = "Pipeline not found"
  1301. if r is not None:
  1302. try:
  1303. res = r.json()
  1304. if "detail" in res:
  1305. detail = res["detail"]
  1306. except:
  1307. pass
  1308. raise HTTPException(
  1309. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1310. detail=detail,
  1311. )
  1312. @app.get("/api/pipelines/{pipeline_id}/valves")
  1313. async def get_pipeline_valves(
  1314. urlIdx: Optional[int],
  1315. pipeline_id: str,
  1316. user=Depends(get_admin_user),
  1317. db=Depends(get_db),
  1318. ):
  1319. models = await get_all_models(db)
  1320. r = None
  1321. try:
  1322. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1323. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1324. headers = {"Authorization": f"Bearer {key}"}
  1325. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1326. r.raise_for_status()
  1327. data = r.json()
  1328. return {**data}
  1329. except Exception as e:
  1330. # Handle connection error here
  1331. print(f"Connection error: {e}")
  1332. detail = "Pipeline not found"
  1333. if r is not None:
  1334. try:
  1335. res = r.json()
  1336. if "detail" in res:
  1337. detail = res["detail"]
  1338. except:
  1339. pass
  1340. raise HTTPException(
  1341. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1342. detail=detail,
  1343. )
  1344. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1345. async def get_pipeline_valves_spec(
  1346. urlIdx: Optional[int],
  1347. pipeline_id: str,
  1348. user=Depends(get_admin_user),
  1349. db=Depends(get_db),
  1350. ):
  1351. models = await get_all_models(db)
  1352. r = None
  1353. try:
  1354. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1355. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1356. headers = {"Authorization": f"Bearer {key}"}
  1357. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1358. r.raise_for_status()
  1359. data = r.json()
  1360. return {**data}
  1361. except Exception as e:
  1362. # Handle connection error here
  1363. print(f"Connection error: {e}")
  1364. detail = "Pipeline not found"
  1365. if r is not None:
  1366. try:
  1367. res = r.json()
  1368. if "detail" in res:
  1369. detail = res["detail"]
  1370. except:
  1371. pass
  1372. raise HTTPException(
  1373. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1374. detail=detail,
  1375. )
  1376. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1377. async def update_pipeline_valves(
  1378. urlIdx: Optional[int],
  1379. pipeline_id: str,
  1380. form_data: dict,
  1381. user=Depends(get_admin_user),
  1382. db=Depends(get_db),
  1383. ):
  1384. models = await get_all_models(db)
  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(db: Session = Depends(get_db)):
  1672. result = db.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. )