main.py 68 KB

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