main.py 68 KB

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