main.py 67 KB

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