main.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197
  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
  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 "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. async def __event_emitter__(data):
  516. await sio.emit(
  517. "chat-events",
  518. {
  519. "chat_id": chat_id,
  520. "message_id": message_id,
  521. "data": data,
  522. },
  523. to=session_id,
  524. )
  525. async def __event_call__(data):
  526. response = await sio.call(
  527. "chat-events",
  528. {"chat_id": chat_id, "message_id": message_id, "data": data},
  529. to=session_id,
  530. )
  531. return response
  532. # Initialize data_items to store additional data to be sent to the client
  533. data_items = []
  534. # Initialize context, and citations
  535. contexts = []
  536. citations = []
  537. try:
  538. body, flags = await chat_completion_functions_handler(
  539. body, model, user, __event_emitter__, __event_call__
  540. )
  541. except Exception as e:
  542. return JSONResponse(
  543. status_code=status.HTTP_400_BAD_REQUEST,
  544. content={"detail": str(e)},
  545. )
  546. try:
  547. body, flags = await chat_completion_tools_handler(
  548. body, user, __event_emitter__, __event_call__
  549. )
  550. contexts.extend(flags.get("contexts", []))
  551. citations.extend(flags.get("citations", []))
  552. except Exception as e:
  553. print(e)
  554. pass
  555. try:
  556. body, flags = await chat_completion_files_handler(body)
  557. contexts.extend(flags.get("contexts", []))
  558. citations.extend(flags.get("citations", []))
  559. except Exception as e:
  560. print(e)
  561. pass
  562. # If context is not empty, insert it into the messages
  563. if len(contexts) > 0:
  564. context_string = "/n".join(contexts).strip()
  565. prompt = get_last_user_message(body["messages"])
  566. body["messages"] = add_or_update_system_message(
  567. rag_template(
  568. rag_app.state.config.RAG_TEMPLATE, context_string, prompt
  569. ),
  570. body["messages"],
  571. )
  572. # If there are citations, add them to the data_items
  573. if len(citations) > 0:
  574. data_items.append({"citations": citations})
  575. modified_body_bytes = json.dumps(body).encode("utf-8")
  576. # Replace the request body with the modified one
  577. request._body = modified_body_bytes
  578. # Set custom header to ensure content-length matches new body length
  579. request.headers.__dict__["_list"] = [
  580. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  581. *[
  582. (k, v)
  583. for k, v in request.headers.raw
  584. if k.lower() != b"content-length"
  585. ],
  586. ]
  587. response = await call_next(request)
  588. if isinstance(response, StreamingResponse):
  589. # If it's a streaming response, inject it as SSE event or NDJSON line
  590. content_type = response.headers.get("Content-Type")
  591. if "text/event-stream" in content_type:
  592. return StreamingResponse(
  593. self.openai_stream_wrapper(response.body_iterator, data_items),
  594. )
  595. if "application/x-ndjson" in content_type:
  596. return StreamingResponse(
  597. self.ollama_stream_wrapper(response.body_iterator, data_items),
  598. )
  599. return response
  600. else:
  601. return response
  602. # If it's not a chat completion request, just pass it through
  603. response = await call_next(request)
  604. return response
  605. async def _receive(self, body: bytes):
  606. return {"type": "http.request", "body": body, "more_body": False}
  607. async def openai_stream_wrapper(self, original_generator, data_items):
  608. for item in data_items:
  609. yield f"data: {json.dumps(item)}\n\n"
  610. async for data in original_generator:
  611. yield data
  612. async def ollama_stream_wrapper(self, original_generator, data_items):
  613. for item in data_items:
  614. yield f"{json.dumps(item)}\n"
  615. async for data in original_generator:
  616. yield data
  617. app.add_middleware(ChatCompletionMiddleware)
  618. ##################################
  619. #
  620. # Pipeline Middleware
  621. #
  622. ##################################
  623. def filter_pipeline(payload, user):
  624. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  625. model_id = payload["model"]
  626. filters = [
  627. model
  628. for model in app.state.MODELS.values()
  629. if "pipeline" in model
  630. and "type" in model["pipeline"]
  631. and model["pipeline"]["type"] == "filter"
  632. and (
  633. model["pipeline"]["pipelines"] == ["*"]
  634. or any(
  635. model_id == target_model_id
  636. for target_model_id in model["pipeline"]["pipelines"]
  637. )
  638. )
  639. ]
  640. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  641. model = app.state.MODELS[model_id]
  642. if "pipeline" in model:
  643. sorted_filters.append(model)
  644. for filter in sorted_filters:
  645. r = None
  646. try:
  647. urlIdx = filter["urlIdx"]
  648. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  649. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  650. if key != "":
  651. headers = {"Authorization": f"Bearer {key}"}
  652. r = requests.post(
  653. f"{url}/{filter['id']}/filter/inlet",
  654. headers=headers,
  655. json={
  656. "user": user,
  657. "body": payload,
  658. },
  659. )
  660. r.raise_for_status()
  661. payload = r.json()
  662. except Exception as e:
  663. # Handle connection error here
  664. print(f"Connection error: {e}")
  665. if r is not None:
  666. try:
  667. res = r.json()
  668. except:
  669. pass
  670. if "detail" in res:
  671. raise Exception(r.status_code, res["detail"])
  672. else:
  673. pass
  674. if "pipeline" not in app.state.MODELS[model_id]:
  675. if "task" in payload:
  676. del payload["task"]
  677. return payload
  678. class PipelineMiddleware(BaseHTTPMiddleware):
  679. async def dispatch(self, request: Request, call_next):
  680. if request.method == "POST" and (
  681. "/ollama/api/chat" in request.url.path
  682. or "/chat/completions" in request.url.path
  683. ):
  684. log.debug(f"request.url.path: {request.url.path}")
  685. # Read the original request body
  686. body = await request.body()
  687. # Decode body to string
  688. body_str = body.decode("utf-8")
  689. # Parse string to JSON
  690. data = json.loads(body_str) if body_str else {}
  691. user = get_current_user(
  692. request,
  693. get_http_authorization_cred(request.headers.get("Authorization")),
  694. )
  695. try:
  696. data = filter_pipeline(data, user)
  697. except Exception as e:
  698. return JSONResponse(
  699. status_code=e.args[0],
  700. content={"detail": e.args[1]},
  701. )
  702. modified_body_bytes = json.dumps(data).encode("utf-8")
  703. # Replace the request body with the modified one
  704. request._body = modified_body_bytes
  705. # Set custom header to ensure content-length matches new body length
  706. request.headers.__dict__["_list"] = [
  707. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  708. *[
  709. (k, v)
  710. for k, v in request.headers.raw
  711. if k.lower() != b"content-length"
  712. ],
  713. ]
  714. response = await call_next(request)
  715. return response
  716. async def _receive(self, body: bytes):
  717. return {"type": "http.request", "body": body, "more_body": False}
  718. app.add_middleware(PipelineMiddleware)
  719. app.add_middleware(
  720. CORSMiddleware,
  721. allow_origins=origins,
  722. allow_credentials=True,
  723. allow_methods=["*"],
  724. allow_headers=["*"],
  725. )
  726. @app.middleware("http")
  727. async def commit_session_after_request(request: Request, call_next):
  728. response = await call_next(request)
  729. log.debug("Commit session after request")
  730. Session.commit()
  731. return response
  732. @app.middleware("http")
  733. async def check_url(request: Request, call_next):
  734. if len(app.state.MODELS) == 0:
  735. await get_all_models()
  736. else:
  737. pass
  738. start_time = int(time.time())
  739. response = await call_next(request)
  740. process_time = int(time.time()) - start_time
  741. response.headers["X-Process-Time"] = str(process_time)
  742. return response
  743. @app.middleware("http")
  744. async def update_embedding_function(request: Request, call_next):
  745. response = await call_next(request)
  746. if "/embedding/update" in request.url.path:
  747. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  748. return response
  749. app.mount("/ws", socket_app)
  750. app.mount("/ollama", ollama_app)
  751. app.mount("/openai", openai_app)
  752. app.mount("/images/api/v1", images_app)
  753. app.mount("/audio/api/v1", audio_app)
  754. app.mount("/rag/api/v1", rag_app)
  755. app.mount("/api/v1", webui_app)
  756. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  757. async def get_all_models():
  758. pipe_models = []
  759. openai_models = []
  760. ollama_models = []
  761. pipe_models = await get_pipe_models()
  762. if app.state.config.ENABLE_OPENAI_API:
  763. openai_models = await get_openai_models()
  764. openai_models = openai_models["data"]
  765. if app.state.config.ENABLE_OLLAMA_API:
  766. ollama_models = await get_ollama_models()
  767. ollama_models = [
  768. {
  769. "id": model["model"],
  770. "name": model["name"],
  771. "object": "model",
  772. "created": int(time.time()),
  773. "owned_by": "ollama",
  774. "ollama": model,
  775. }
  776. for model in ollama_models["models"]
  777. ]
  778. models = pipe_models + openai_models + ollama_models
  779. custom_models = Models.get_all_models()
  780. for custom_model in custom_models:
  781. if custom_model.base_model_id == None:
  782. for model in models:
  783. if (
  784. custom_model.id == model["id"]
  785. or custom_model.id == model["id"].split(":")[0]
  786. ):
  787. model["name"] = custom_model.name
  788. model["info"] = custom_model.model_dump()
  789. else:
  790. owned_by = "openai"
  791. pipe = None
  792. for model in models:
  793. if (
  794. custom_model.base_model_id == model["id"]
  795. or custom_model.base_model_id == model["id"].split(":")[0]
  796. ):
  797. owned_by = model["owned_by"]
  798. if "pipe" in model:
  799. pipe = model["pipe"]
  800. break
  801. models.append(
  802. {
  803. "id": custom_model.id,
  804. "name": custom_model.name,
  805. "object": "model",
  806. "created": custom_model.created_at,
  807. "owned_by": owned_by,
  808. "info": custom_model.model_dump(),
  809. "preset": True,
  810. **({"pipe": pipe} if pipe is not None else {}),
  811. }
  812. )
  813. app.state.MODELS = {model["id"]: model for model in models}
  814. webui_app.state.MODELS = app.state.MODELS
  815. return models
  816. @app.get("/api/models")
  817. async def get_models(user=Depends(get_verified_user)):
  818. models = await get_all_models()
  819. # Filter out filter pipelines
  820. models = [
  821. model
  822. for model in models
  823. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  824. ]
  825. if app.state.config.ENABLE_MODEL_FILTER:
  826. if user.role == "user":
  827. models = list(
  828. filter(
  829. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  830. models,
  831. )
  832. )
  833. return {"data": models}
  834. return {"data": models}
  835. @app.post("/api/chat/completions")
  836. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  837. model_id = form_data["model"]
  838. if model_id not in app.state.MODELS:
  839. raise HTTPException(
  840. status_code=status.HTTP_404_NOT_FOUND,
  841. detail="Model not found",
  842. )
  843. model = app.state.MODELS[model_id]
  844. pipe = model.get("pipe")
  845. if pipe:
  846. return await generate_function_chat_completion(form_data, user=user)
  847. if model["owned_by"] == "ollama":
  848. return await generate_ollama_chat_completion(form_data, user=user)
  849. else:
  850. return await generate_openai_chat_completion(form_data, user=user)
  851. @app.post("/api/chat/completed")
  852. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  853. data = form_data
  854. model_id = data["model"]
  855. if model_id not in app.state.MODELS:
  856. raise HTTPException(
  857. status_code=status.HTTP_404_NOT_FOUND,
  858. detail="Model not found",
  859. )
  860. model = app.state.MODELS[model_id]
  861. filters = [
  862. model
  863. for model in app.state.MODELS.values()
  864. if "pipeline" in model
  865. and "type" in model["pipeline"]
  866. and model["pipeline"]["type"] == "filter"
  867. and (
  868. model["pipeline"]["pipelines"] == ["*"]
  869. or any(
  870. model_id == target_model_id
  871. for target_model_id in model["pipeline"]["pipelines"]
  872. )
  873. )
  874. ]
  875. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  876. if "pipeline" in model:
  877. sorted_filters = [model] + sorted_filters
  878. for filter in sorted_filters:
  879. r = None
  880. try:
  881. urlIdx = filter["urlIdx"]
  882. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  883. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  884. if key != "":
  885. headers = {"Authorization": f"Bearer {key}"}
  886. r = requests.post(
  887. f"{url}/{filter['id']}/filter/outlet",
  888. headers=headers,
  889. json={
  890. "user": {
  891. "id": user.id,
  892. "name": user.name,
  893. "email": user.email,
  894. "role": user.role,
  895. },
  896. "body": data,
  897. },
  898. )
  899. r.raise_for_status()
  900. data = r.json()
  901. except Exception as e:
  902. # Handle connection error here
  903. print(f"Connection error: {e}")
  904. if r is not None:
  905. try:
  906. res = r.json()
  907. if "detail" in res:
  908. return JSONResponse(
  909. status_code=r.status_code,
  910. content=res,
  911. )
  912. except:
  913. pass
  914. else:
  915. pass
  916. async def __event_emitter__(data):
  917. await sio.emit(
  918. "chat-events",
  919. {
  920. "chat_id": data["chat_id"],
  921. "message_id": data["id"],
  922. "data": data,
  923. },
  924. to=data["session_id"],
  925. )
  926. async def __event_call__(data):
  927. response = await sio.call(
  928. "chat-events",
  929. {"chat_id": data["chat_id"], "message_id": data["id"], "data": data},
  930. to=data["session_id"],
  931. )
  932. return response
  933. def get_priority(function_id):
  934. function = Functions.get_function_by_id(function_id)
  935. if function is not None and hasattr(function, "valves"):
  936. return (function.valves if function.valves else {}).get("priority", 0)
  937. return 0
  938. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  939. if "info" in model and "meta" in model["info"]:
  940. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  941. filter_ids = list(set(filter_ids))
  942. enabled_filter_ids = [
  943. function.id
  944. for function in Functions.get_functions_by_type("filter", active_only=True)
  945. ]
  946. filter_ids = [
  947. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  948. ]
  949. # Sort filter_ids by priority, using the get_priority function
  950. filter_ids.sort(key=get_priority)
  951. for filter_id in filter_ids:
  952. filter = Functions.get_function_by_id(filter_id)
  953. if not filter:
  954. continue
  955. if filter_id in webui_app.state.FUNCTIONS:
  956. function_module = webui_app.state.FUNCTIONS[filter_id]
  957. else:
  958. function_module, _, _ = load_function_module_by_id(filter_id)
  959. webui_app.state.FUNCTIONS[filter_id] = function_module
  960. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  961. valves = Functions.get_function_valves_by_id(filter_id)
  962. function_module.valves = function_module.Valves(
  963. **(valves if valves else {})
  964. )
  965. if not hasattr(function_module, "outlet"):
  966. continue
  967. try:
  968. outlet = function_module.outlet
  969. # Get the signature of the function
  970. sig = inspect.signature(outlet)
  971. params = {"body": data}
  972. # Extra parameters to be passed to the function
  973. extra_params = {
  974. "__model__": model,
  975. "__id__": filter_id,
  976. "__event_emitter__": __event_emitter__,
  977. "__event_call__": __event_call__,
  978. }
  979. # Add extra params in contained in function signature
  980. for key, value in extra_params.items():
  981. if key in sig.parameters:
  982. params[key] = value
  983. if "__user__" in sig.parameters:
  984. __user__ = {
  985. "id": user.id,
  986. "email": user.email,
  987. "name": user.name,
  988. "role": user.role,
  989. }
  990. try:
  991. if hasattr(function_module, "UserValves"):
  992. __user__["valves"] = function_module.UserValves(
  993. **Functions.get_user_valves_by_id_and_user_id(
  994. filter_id, user.id
  995. )
  996. )
  997. except Exception as e:
  998. print(e)
  999. params = {**params, "__user__": __user__}
  1000. if inspect.iscoroutinefunction(outlet):
  1001. data = await outlet(**params)
  1002. else:
  1003. data = outlet(**params)
  1004. except Exception as e:
  1005. print(f"Error: {e}")
  1006. return JSONResponse(
  1007. status_code=status.HTTP_400_BAD_REQUEST,
  1008. content={"detail": str(e)},
  1009. )
  1010. return data
  1011. ##################################
  1012. #
  1013. # Task Endpoints
  1014. #
  1015. ##################################
  1016. # TODO: Refactor task API endpoints below into a separate file
  1017. @app.get("/api/task/config")
  1018. async def get_task_config(user=Depends(get_verified_user)):
  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. class TaskConfigForm(BaseModel):
  1028. TASK_MODEL: Optional[str]
  1029. TASK_MODEL_EXTERNAL: Optional[str]
  1030. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1031. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1032. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  1033. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1034. @app.post("/api/task/config/update")
  1035. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1036. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1037. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1038. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1039. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1040. )
  1041. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1042. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1043. )
  1044. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  1045. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  1046. )
  1047. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1048. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1049. )
  1050. return {
  1051. "TASK_MODEL": app.state.config.TASK_MODEL,
  1052. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1053. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1054. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1055. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1056. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1057. }
  1058. @app.post("/api/task/title/completions")
  1059. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1060. print("generate_title")
  1061. model_id = form_data["model"]
  1062. if model_id not in app.state.MODELS:
  1063. raise HTTPException(
  1064. status_code=status.HTTP_404_NOT_FOUND,
  1065. detail="Model not found",
  1066. )
  1067. # Check if the user has a custom task model
  1068. # If the user has a custom task model, use that model
  1069. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1070. if app.state.config.TASK_MODEL:
  1071. task_model_id = app.state.config.TASK_MODEL
  1072. if task_model_id in app.state.MODELS:
  1073. model_id = task_model_id
  1074. else:
  1075. if app.state.config.TASK_MODEL_EXTERNAL:
  1076. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1077. if task_model_id in app.state.MODELS:
  1078. model_id = task_model_id
  1079. print(model_id)
  1080. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1081. content = title_generation_template(
  1082. template,
  1083. form_data["prompt"],
  1084. {
  1085. "name": user.name,
  1086. "location": user.info.get("location") if user.info else None,
  1087. },
  1088. )
  1089. payload = {
  1090. "model": model_id,
  1091. "messages": [{"role": "user", "content": content}],
  1092. "stream": False,
  1093. "max_tokens": 50,
  1094. "chat_id": form_data.get("chat_id", None),
  1095. "task": TASKS.TITLE_GENERATION,
  1096. }
  1097. log.debug(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/query/completions")
  1109. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1110. print("generate_search_query")
  1111. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1112. raise HTTPException(
  1113. status_code=status.HTTP_400_BAD_REQUEST,
  1114. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1115. )
  1116. model_id = form_data["model"]
  1117. if model_id not in app.state.MODELS:
  1118. raise HTTPException(
  1119. status_code=status.HTTP_404_NOT_FOUND,
  1120. detail="Model not found",
  1121. )
  1122. # Check if the user has a custom task model
  1123. # If the user has a custom task model, use that model
  1124. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1125. if app.state.config.TASK_MODEL:
  1126. task_model_id = app.state.config.TASK_MODEL
  1127. if task_model_id in app.state.MODELS:
  1128. model_id = task_model_id
  1129. else:
  1130. if app.state.config.TASK_MODEL_EXTERNAL:
  1131. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1132. if task_model_id in app.state.MODELS:
  1133. model_id = task_model_id
  1134. print(model_id)
  1135. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1136. content = search_query_generation_template(
  1137. template, form_data["prompt"], {"name": user.name}
  1138. )
  1139. payload = {
  1140. "model": model_id,
  1141. "messages": [{"role": "user", "content": content}],
  1142. "stream": False,
  1143. "max_tokens": 30,
  1144. "task": TASKS.QUERY_GENERATION,
  1145. }
  1146. print(payload)
  1147. try:
  1148. payload = filter_pipeline(payload, user)
  1149. except Exception as e:
  1150. return JSONResponse(
  1151. status_code=e.args[0],
  1152. content={"detail": e.args[1]},
  1153. )
  1154. if "chat_id" in payload:
  1155. del payload["chat_id"]
  1156. return await generate_chat_completions(form_data=payload, user=user)
  1157. @app.post("/api/task/emoji/completions")
  1158. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1159. print("generate_emoji")
  1160. model_id = form_data["model"]
  1161. if model_id not in app.state.MODELS:
  1162. raise HTTPException(
  1163. status_code=status.HTTP_404_NOT_FOUND,
  1164. detail="Model not found",
  1165. )
  1166. # Check if the user has a custom task model
  1167. # If the user has a custom task model, use that model
  1168. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1169. if app.state.config.TASK_MODEL:
  1170. task_model_id = app.state.config.TASK_MODEL
  1171. if task_model_id in app.state.MODELS:
  1172. model_id = task_model_id
  1173. else:
  1174. if app.state.config.TASK_MODEL_EXTERNAL:
  1175. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1176. if task_model_id in app.state.MODELS:
  1177. model_id = task_model_id
  1178. print(model_id)
  1179. template = '''
  1180. 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., 😊, 😢, 😡, 😱).
  1181. Message: """{{prompt}}"""
  1182. '''
  1183. content = title_generation_template(
  1184. template,
  1185. form_data["prompt"],
  1186. {
  1187. "name": user.name,
  1188. "location": user.info.get("location") if user.info else None,
  1189. },
  1190. )
  1191. payload = {
  1192. "model": model_id,
  1193. "messages": [{"role": "user", "content": content}],
  1194. "stream": False,
  1195. "max_tokens": 4,
  1196. "chat_id": form_data.get("chat_id", None),
  1197. "task": TASKS.EMOJI_GENERATION,
  1198. }
  1199. log.debug(payload)
  1200. try:
  1201. payload = filter_pipeline(payload, user)
  1202. except Exception as e:
  1203. return JSONResponse(
  1204. status_code=e.args[0],
  1205. content={"detail": e.args[1]},
  1206. )
  1207. if "chat_id" in payload:
  1208. del payload["chat_id"]
  1209. return await generate_chat_completions(form_data=payload, user=user)
  1210. @app.post("/api/task/tools/completions")
  1211. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  1212. print("get_tools_function_calling")
  1213. model_id = form_data["model"]
  1214. if model_id not in app.state.MODELS:
  1215. raise HTTPException(
  1216. status_code=status.HTTP_404_NOT_FOUND,
  1217. detail="Model not found",
  1218. )
  1219. # Check if the user has a custom task model
  1220. # If the user has a custom task model, use that model
  1221. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1222. if app.state.config.TASK_MODEL:
  1223. task_model_id = app.state.config.TASK_MODEL
  1224. if task_model_id in app.state.MODELS:
  1225. model_id = task_model_id
  1226. else:
  1227. if app.state.config.TASK_MODEL_EXTERNAL:
  1228. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1229. if task_model_id in app.state.MODELS:
  1230. model_id = task_model_id
  1231. print(model_id)
  1232. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1233. try:
  1234. context, _, _ = await get_function_call_response(
  1235. form_data["messages"],
  1236. form_data.get("files", []),
  1237. form_data["tool_id"],
  1238. template,
  1239. model_id,
  1240. user,
  1241. )
  1242. return context
  1243. except Exception as e:
  1244. return JSONResponse(
  1245. status_code=e.args[0],
  1246. content={"detail": e.args[1]},
  1247. )
  1248. ##################################
  1249. #
  1250. # Pipelines Endpoints
  1251. #
  1252. ##################################
  1253. # TODO: Refactor pipelines API endpoints below into a separate file
  1254. @app.get("/api/pipelines/list")
  1255. async def get_pipelines_list(user=Depends(get_admin_user)):
  1256. responses = await get_openai_models(raw=True)
  1257. print(responses)
  1258. urlIdxs = [
  1259. idx
  1260. for idx, response in enumerate(responses)
  1261. if response != None and "pipelines" in response
  1262. ]
  1263. return {
  1264. "data": [
  1265. {
  1266. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1267. "idx": urlIdx,
  1268. }
  1269. for urlIdx in urlIdxs
  1270. ]
  1271. }
  1272. @app.post("/api/pipelines/upload")
  1273. async def upload_pipeline(
  1274. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1275. ):
  1276. print("upload_pipeline", urlIdx, file.filename)
  1277. # Check if the uploaded file is a python file
  1278. if not file.filename.endswith(".py"):
  1279. raise HTTPException(
  1280. status_code=status.HTTP_400_BAD_REQUEST,
  1281. detail="Only Python (.py) files are allowed.",
  1282. )
  1283. upload_folder = f"{CACHE_DIR}/pipelines"
  1284. os.makedirs(upload_folder, exist_ok=True)
  1285. file_path = os.path.join(upload_folder, file.filename)
  1286. r = None
  1287. try:
  1288. # Save the uploaded file
  1289. with open(file_path, "wb") as buffer:
  1290. shutil.copyfileobj(file.file, buffer)
  1291. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1292. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1293. headers = {"Authorization": f"Bearer {key}"}
  1294. with open(file_path, "rb") as f:
  1295. files = {"file": f}
  1296. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1297. r.raise_for_status()
  1298. data = r.json()
  1299. return {**data}
  1300. except Exception as e:
  1301. # Handle connection error here
  1302. print(f"Connection error: {e}")
  1303. detail = "Pipeline not found"
  1304. status_code = status.HTTP_404_NOT_FOUND
  1305. if r is not None:
  1306. status_code = r.status_code
  1307. try:
  1308. res = r.json()
  1309. if "detail" in res:
  1310. detail = res["detail"]
  1311. except:
  1312. pass
  1313. raise HTTPException(
  1314. status_code=status_code,
  1315. detail=detail,
  1316. )
  1317. finally:
  1318. # Ensure the file is deleted after the upload is completed or on failure
  1319. if os.path.exists(file_path):
  1320. os.remove(file_path)
  1321. class AddPipelineForm(BaseModel):
  1322. url: str
  1323. urlIdx: int
  1324. @app.post("/api/pipelines/add")
  1325. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1326. r = None
  1327. try:
  1328. urlIdx = form_data.urlIdx
  1329. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1330. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1331. headers = {"Authorization": f"Bearer {key}"}
  1332. r = requests.post(
  1333. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1334. )
  1335. r.raise_for_status()
  1336. data = r.json()
  1337. return {**data}
  1338. except Exception as e:
  1339. # Handle connection error here
  1340. print(f"Connection error: {e}")
  1341. detail = "Pipeline not found"
  1342. if r is not None:
  1343. try:
  1344. res = r.json()
  1345. if "detail" in res:
  1346. detail = res["detail"]
  1347. except:
  1348. pass
  1349. raise HTTPException(
  1350. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1351. detail=detail,
  1352. )
  1353. class DeletePipelineForm(BaseModel):
  1354. id: str
  1355. urlIdx: int
  1356. @app.delete("/api/pipelines/delete")
  1357. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1358. r = None
  1359. try:
  1360. urlIdx = form_data.urlIdx
  1361. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1362. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1363. headers = {"Authorization": f"Bearer {key}"}
  1364. r = requests.delete(
  1365. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1366. )
  1367. r.raise_for_status()
  1368. data = r.json()
  1369. return {**data}
  1370. except Exception as e:
  1371. # Handle connection error here
  1372. print(f"Connection error: {e}")
  1373. detail = "Pipeline not found"
  1374. if r is not None:
  1375. try:
  1376. res = r.json()
  1377. if "detail" in res:
  1378. detail = res["detail"]
  1379. except:
  1380. pass
  1381. raise HTTPException(
  1382. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1383. detail=detail,
  1384. )
  1385. @app.get("/api/pipelines")
  1386. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1387. r = None
  1388. try:
  1389. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1390. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1391. headers = {"Authorization": f"Bearer {key}"}
  1392. r = requests.get(f"{url}/pipelines", headers=headers)
  1393. r.raise_for_status()
  1394. data = r.json()
  1395. return {**data}
  1396. except Exception as e:
  1397. # Handle connection error here
  1398. print(f"Connection error: {e}")
  1399. detail = "Pipeline not found"
  1400. if r is not None:
  1401. try:
  1402. res = r.json()
  1403. if "detail" in res:
  1404. detail = res["detail"]
  1405. except:
  1406. pass
  1407. raise HTTPException(
  1408. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1409. detail=detail,
  1410. )
  1411. @app.get("/api/pipelines/{pipeline_id}/valves")
  1412. async def get_pipeline_valves(
  1413. urlIdx: Optional[int],
  1414. pipeline_id: str,
  1415. user=Depends(get_admin_user),
  1416. ):
  1417. models = await get_all_models()
  1418. r = None
  1419. try:
  1420. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1421. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1422. headers = {"Authorization": f"Bearer {key}"}
  1423. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  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. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1443. async def get_pipeline_valves_spec(
  1444. urlIdx: Optional[int],
  1445. pipeline_id: str,
  1446. user=Depends(get_admin_user),
  1447. ):
  1448. models = await get_all_models()
  1449. r = None
  1450. try:
  1451. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1452. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1453. headers = {"Authorization": f"Bearer {key}"}
  1454. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1455. r.raise_for_status()
  1456. data = r.json()
  1457. return {**data}
  1458. except Exception as e:
  1459. # Handle connection error here
  1460. print(f"Connection error: {e}")
  1461. detail = "Pipeline not found"
  1462. if r is not None:
  1463. try:
  1464. res = r.json()
  1465. if "detail" in res:
  1466. detail = res["detail"]
  1467. except:
  1468. pass
  1469. raise HTTPException(
  1470. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1471. detail=detail,
  1472. )
  1473. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1474. async def update_pipeline_valves(
  1475. urlIdx: Optional[int],
  1476. pipeline_id: str,
  1477. form_data: dict,
  1478. user=Depends(get_admin_user),
  1479. ):
  1480. models = await get_all_models()
  1481. r = None
  1482. try:
  1483. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1484. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1485. headers = {"Authorization": f"Bearer {key}"}
  1486. r = requests.post(
  1487. f"{url}/{pipeline_id}/valves/update",
  1488. headers=headers,
  1489. json={**form_data},
  1490. )
  1491. r.raise_for_status()
  1492. data = r.json()
  1493. return {**data}
  1494. except Exception as e:
  1495. # Handle connection error here
  1496. print(f"Connection error: {e}")
  1497. detail = "Pipeline not found"
  1498. if r is not None:
  1499. try:
  1500. res = r.json()
  1501. if "detail" in res:
  1502. detail = res["detail"]
  1503. except:
  1504. pass
  1505. raise HTTPException(
  1506. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1507. detail=detail,
  1508. )
  1509. ##################################
  1510. #
  1511. # Config Endpoints
  1512. #
  1513. ##################################
  1514. @app.get("/api/config")
  1515. async def get_app_config():
  1516. return {
  1517. "status": True,
  1518. "name": WEBUI_NAME,
  1519. "version": VERSION,
  1520. "default_locale": str(DEFAULT_LOCALE),
  1521. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1522. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1523. "features": {
  1524. "auth": WEBUI_AUTH,
  1525. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1526. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1527. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1528. "enable_image_generation": images_app.state.config.ENABLED,
  1529. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1530. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1531. },
  1532. "audio": {
  1533. "tts": {
  1534. "engine": audio_app.state.config.TTS_ENGINE,
  1535. "voice": audio_app.state.config.TTS_VOICE,
  1536. },
  1537. "stt": {
  1538. "engine": audio_app.state.config.STT_ENGINE,
  1539. },
  1540. },
  1541. "oauth": {
  1542. "providers": {
  1543. name: config.get("name", name)
  1544. for name, config in OAUTH_PROVIDERS.items()
  1545. }
  1546. },
  1547. }
  1548. @app.get("/api/config/model/filter")
  1549. async def get_model_filter_config(user=Depends(get_admin_user)):
  1550. return {
  1551. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1552. "models": app.state.config.MODEL_FILTER_LIST,
  1553. }
  1554. class ModelFilterConfigForm(BaseModel):
  1555. enabled: bool
  1556. models: List[str]
  1557. @app.post("/api/config/model/filter")
  1558. async def update_model_filter_config(
  1559. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1560. ):
  1561. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1562. app.state.config.MODEL_FILTER_LIST = form_data.models
  1563. return {
  1564. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1565. "models": app.state.config.MODEL_FILTER_LIST,
  1566. }
  1567. # TODO: webhook endpoint should be under config endpoints
  1568. @app.get("/api/webhook")
  1569. async def get_webhook_url(user=Depends(get_admin_user)):
  1570. return {
  1571. "url": app.state.config.WEBHOOK_URL,
  1572. }
  1573. class UrlForm(BaseModel):
  1574. url: str
  1575. @app.post("/api/webhook")
  1576. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1577. app.state.config.WEBHOOK_URL = form_data.url
  1578. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1579. return {"url": app.state.config.WEBHOOK_URL}
  1580. @app.get("/api/version")
  1581. async def get_app_config():
  1582. return {
  1583. "version": VERSION,
  1584. }
  1585. @app.get("/api/changelog")
  1586. async def get_app_changelog():
  1587. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1588. @app.get("/api/version/updates")
  1589. async def get_app_latest_release_version():
  1590. try:
  1591. async with aiohttp.ClientSession(trust_env=True) as session:
  1592. async with session.get(
  1593. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1594. ) as response:
  1595. response.raise_for_status()
  1596. data = await response.json()
  1597. latest_version = data["tag_name"]
  1598. return {"current": VERSION, "latest": latest_version[1:]}
  1599. except aiohttp.ClientError as e:
  1600. raise HTTPException(
  1601. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1602. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1603. )
  1604. ############################
  1605. # OAuth Login & Callback
  1606. ############################
  1607. oauth = OAuth()
  1608. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1609. oauth.register(
  1610. name=provider_name,
  1611. client_id=provider_config["client_id"],
  1612. client_secret=provider_config["client_secret"],
  1613. server_metadata_url=provider_config["server_metadata_url"],
  1614. client_kwargs={
  1615. "scope": provider_config["scope"],
  1616. },
  1617. )
  1618. # SessionMiddleware is used by authlib for oauth
  1619. if len(OAUTH_PROVIDERS) > 0:
  1620. app.add_middleware(
  1621. SessionMiddleware,
  1622. secret_key=WEBUI_SECRET_KEY,
  1623. session_cookie="oui-session",
  1624. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1625. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1626. )
  1627. @app.get("/oauth/{provider}/login")
  1628. async def oauth_login(provider: str, request: Request):
  1629. if provider not in OAUTH_PROVIDERS:
  1630. raise HTTPException(404)
  1631. redirect_uri = request.url_for("oauth_callback", provider=provider)
  1632. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1633. # OAuth login logic is as follows:
  1634. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1635. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1636. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1637. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1638. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1639. @app.get("/oauth/{provider}/callback")
  1640. async def oauth_callback(provider: str, request: Request, response: Response):
  1641. if provider not in OAUTH_PROVIDERS:
  1642. raise HTTPException(404)
  1643. client = oauth.create_client(provider)
  1644. try:
  1645. token = await client.authorize_access_token(request)
  1646. except Exception as e:
  1647. log.warning(f"OAuth callback error: {e}")
  1648. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1649. user_data: UserInfo = token["userinfo"]
  1650. sub = user_data.get("sub")
  1651. if not sub:
  1652. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1653. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1654. provider_sub = f"{provider}@{sub}"
  1655. email = user_data.get("email", "").lower()
  1656. # We currently mandate that email addresses are provided
  1657. if not email:
  1658. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1659. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1660. # Check if the user exists
  1661. user = Users.get_user_by_oauth_sub(provider_sub)
  1662. if not user:
  1663. # If the user does not exist, check if merging is enabled
  1664. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1665. # Check if the user exists by email
  1666. user = Users.get_user_by_email(email)
  1667. if user:
  1668. # Update the user with the new oauth sub
  1669. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1670. if not user:
  1671. # If the user does not exist, check if signups are enabled
  1672. if ENABLE_OAUTH_SIGNUP.value:
  1673. # Check if an existing user with the same email already exists
  1674. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1675. if existing_user:
  1676. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1677. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1678. picture_url = user_data.get(picture_claim, "")
  1679. if picture_url:
  1680. # Download the profile image into a base64 string
  1681. try:
  1682. async with aiohttp.ClientSession() as session:
  1683. async with session.get(picture_url) as resp:
  1684. picture = await resp.read()
  1685. base64_encoded_picture = base64.b64encode(picture).decode(
  1686. "utf-8"
  1687. )
  1688. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1689. if guessed_mime_type is None:
  1690. # assume JPG, browsers are tolerant enough of image formats
  1691. guessed_mime_type = "image/jpeg"
  1692. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1693. except Exception as e:
  1694. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1695. picture_url = ""
  1696. if not picture_url:
  1697. picture_url = "/user.png"
  1698. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1699. role = (
  1700. "admin"
  1701. if Users.get_num_users() == 0
  1702. else webui_app.state.config.DEFAULT_USER_ROLE
  1703. )
  1704. user = Auths.insert_new_auth(
  1705. email=email,
  1706. password=get_password_hash(
  1707. str(uuid.uuid4())
  1708. ), # Random password, not used
  1709. name=user_data.get(username_claim, "User"),
  1710. profile_image_url=picture_url,
  1711. role=role,
  1712. oauth_sub=provider_sub,
  1713. )
  1714. if webui_app.state.config.WEBHOOK_URL:
  1715. post_webhook(
  1716. webui_app.state.config.WEBHOOK_URL,
  1717. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1718. {
  1719. "action": "signup",
  1720. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1721. "user": user.model_dump_json(exclude_none=True),
  1722. },
  1723. )
  1724. else:
  1725. raise HTTPException(
  1726. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1727. )
  1728. jwt_token = create_token(
  1729. data={"id": user.id},
  1730. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1731. )
  1732. # Set the cookie token
  1733. response.set_cookie(
  1734. key="token",
  1735. value=jwt_token,
  1736. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1737. )
  1738. # Redirect back to the frontend with the JWT token
  1739. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1740. return RedirectResponse(url=redirect_url)
  1741. @app.get("/manifest.json")
  1742. async def get_manifest_json():
  1743. return {
  1744. "name": WEBUI_NAME,
  1745. "short_name": WEBUI_NAME,
  1746. "start_url": "/",
  1747. "display": "standalone",
  1748. "background_color": "#343541",
  1749. "orientation": "portrait-primary",
  1750. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1751. }
  1752. @app.get("/opensearch.xml")
  1753. async def get_opensearch_xml():
  1754. xml_content = rf"""
  1755. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1756. <ShortName>{WEBUI_NAME}</ShortName>
  1757. <Description>Search {WEBUI_NAME}</Description>
  1758. <InputEncoding>UTF-8</InputEncoding>
  1759. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1760. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1761. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1762. </OpenSearchDescription>
  1763. """
  1764. return Response(content=xml_content, media_type="application/xml")
  1765. @app.get("/health")
  1766. async def healthcheck():
  1767. return {"status": True}
  1768. @app.get("/health/db")
  1769. async def healthcheck_with_db():
  1770. Session.execute(text("SELECT 1;")).all()
  1771. return {"status": True}
  1772. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1773. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1774. if os.path.exists(FRONTEND_BUILD_DIR):
  1775. mimetypes.add_type("text/javascript", ".js")
  1776. app.mount(
  1777. "/",
  1778. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1779. name="spa-static-files",
  1780. )
  1781. else:
  1782. log.warning(
  1783. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1784. )