main.py 69 KB

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