main.py 67 KB

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