main.py 70 KB

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