main.py 72 KB

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