main.py 70 KB

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