main.py 66 KB

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