main.py 70 KB

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