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 fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  17. from fastapi.staticfiles import StaticFiles
  18. from fastapi.responses import JSONResponse
  19. from fastapi import HTTPException
  20. from fastapi.middleware.cors import CORSMiddleware
  21. from sqlalchemy import text
  22. from starlette.exceptions import HTTPException as StarletteHTTPException
  23. from starlette.middleware.base import BaseHTTPMiddleware
  24. from starlette.middleware.sessions import SessionMiddleware
  25. from starlette.responses import StreamingResponse, Response, RedirectResponse
  26. from apps.socket.main import app as socket_app, get_event_emitter, get_event_call
  27. from apps.ollama.main import (
  28. app as ollama_app,
  29. get_all_models as get_ollama_models,
  30. generate_openai_chat_completion as generate_ollama_chat_completion,
  31. )
  32. from apps.openai.main import (
  33. app as openai_app,
  34. get_all_models as get_openai_models,
  35. generate_chat_completion as generate_openai_chat_completion,
  36. )
  37. from apps.audio.main import app as audio_app
  38. from apps.images.main import app as images_app
  39. from apps.rag.main import app as rag_app
  40. from apps.webui.main import (
  41. app as webui_app,
  42. get_pipe_models,
  43. generate_function_chat_completion,
  44. )
  45. from apps.webui.internal.db import Session
  46. from pydantic import BaseModel
  47. from apps.webui.models.auths import Auths
  48. from apps.webui.models.models import Models
  49. from apps.webui.models.functions import Functions
  50. from apps.webui.models.users import Users, UserModel
  51. from apps.webui.utils import load_function_module_by_id
  52. from utils.utils import (
  53. get_admin_user,
  54. get_verified_user,
  55. get_current_user,
  56. get_http_authorization_cred,
  57. get_password_hash,
  58. create_token,
  59. )
  60. from utils.task import (
  61. title_generation_template,
  62. search_query_generation_template,
  63. tools_function_calling_generation_template,
  64. moa_response_generation_template,
  65. )
  66. from utils.tools import get_tools
  67. from utils.misc import (
  68. get_last_user_message,
  69. add_or_update_system_message,
  70. prepend_to_first_user_message_content,
  71. parse_duration,
  72. )
  73. from apps.rag.utils import get_rag_context, rag_template
  74. from config import (
  75. WEBUI_NAME,
  76. WEBUI_URL,
  77. WEBUI_AUTH,
  78. ENV,
  79. VERSION,
  80. CHANGELOG,
  81. FRONTEND_BUILD_DIR,
  82. CACHE_DIR,
  83. STATIC_DIR,
  84. DEFAULT_LOCALE,
  85. ENABLE_OPENAI_API,
  86. ENABLE_OLLAMA_API,
  87. ENABLE_MODEL_FILTER,
  88. MODEL_FILTER_LIST,
  89. GLOBAL_LOG_LEVEL,
  90. SRC_LOG_LEVELS,
  91. WEBHOOK_URL,
  92. ENABLE_ADMIN_EXPORT,
  93. WEBUI_BUILD_HASH,
  94. TASK_MODEL,
  95. TASK_MODEL_EXTERNAL,
  96. TITLE_GENERATION_PROMPT_TEMPLATE,
  97. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  98. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  99. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  100. SAFE_MODE,
  101. OAUTH_PROVIDERS,
  102. ENABLE_OAUTH_SIGNUP,
  103. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  104. WEBUI_SECRET_KEY,
  105. WEBUI_SESSION_COOKIE_SAME_SITE,
  106. WEBUI_SESSION_COOKIE_SECURE,
  107. ENABLE_ADMIN_CHAT_ACCESS,
  108. ENABLE_TOOLS_FILTER,
  109. ENABLE_FILES_FILTER,
  110. AppConfig,
  111. )
  112. from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES, TASKS
  113. from utils.webhook import post_webhook
  114. if SAFE_MODE:
  115. print("SAFE MODE ENABLED")
  116. Functions.deactivate_all_functions()
  117. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  118. log = logging.getLogger(__name__)
  119. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  120. class SPAStaticFiles(StaticFiles):
  121. async def get_response(self, path: str, scope):
  122. try:
  123. return await super().get_response(path, scope)
  124. except (HTTPException, StarletteHTTPException) as ex:
  125. if ex.status_code == 404:
  126. return await super().get_response("index.html", scope)
  127. else:
  128. raise ex
  129. print(
  130. rf"""
  131. ___ __ __ _ _ _ ___
  132. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  133. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  134. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  135. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  136. |_|
  137. v{VERSION} - building the best open-source AI user interface.
  138. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  139. https://github.com/open-webui/open-webui
  140. """
  141. )
  142. def run_migrations():
  143. try:
  144. from alembic.config import Config
  145. from alembic import command
  146. alembic_cfg = Config("alembic.ini")
  147. command.upgrade(alembic_cfg, "head")
  148. except Exception as e:
  149. print(f"Error: {e}")
  150. @asynccontextmanager
  151. async def lifespan(app: FastAPI):
  152. run_migrations()
  153. yield
  154. app = FastAPI(
  155. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  156. )
  157. app.state.config = AppConfig()
  158. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  159. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  160. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  161. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  162. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  163. app.state.config.TASK_MODEL = TASK_MODEL
  164. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  165. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  166. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  167. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  168. )
  169. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  170. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  171. )
  172. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  173. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  174. )
  175. app.state.MODELS = {}
  176. origins = ["*"]
  177. ##################################
  178. #
  179. # ChatCompletion Middleware
  180. #
  181. ##################################
  182. def get_task_model_id(default_model_id):
  183. # Set the task model
  184. task_model_id = default_model_id
  185. # Check if the user has a custom task model and use that model
  186. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  187. if (
  188. app.state.config.TASK_MODEL
  189. and app.state.config.TASK_MODEL in app.state.MODELS
  190. ):
  191. task_model_id = app.state.config.TASK_MODEL
  192. else:
  193. if (
  194. app.state.config.TASK_MODEL_EXTERNAL
  195. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  196. ):
  197. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  198. return task_model_id
  199. def get_filter_function_ids(model):
  200. def get_priority(function_id):
  201. function = Functions.get_function_by_id(function_id)
  202. if function is not None and hasattr(function, "valves"):
  203. # TODO: Fix FunctionModel
  204. return (function.valves if function.valves else {}).get("priority", 0)
  205. return 0
  206. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  207. if "info" in model and "meta" in model["info"]:
  208. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  209. filter_ids = list(set(filter_ids))
  210. enabled_filter_ids = [
  211. function.id
  212. for function in Functions.get_functions_by_type("filter", active_only=True)
  213. ]
  214. filter_ids = [
  215. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  216. ]
  217. filter_ids.sort(key=get_priority)
  218. return filter_ids
  219. async def chat_completion_filter_functions_handler(body, model, extra_params):
  220. skip_files = None
  221. filter_ids = get_filter_function_ids(model)
  222. for filter_id in filter_ids:
  223. filter = Functions.get_function_by_id(filter_id)
  224. if not filter:
  225. continue
  226. if filter_id in webui_app.state.FUNCTIONS:
  227. function_module = webui_app.state.FUNCTIONS[filter_id]
  228. else:
  229. function_module, _, _ = load_function_module_by_id(filter_id)
  230. webui_app.state.FUNCTIONS[filter_id] = function_module
  231. # Check if the function has a file_handler variable
  232. if hasattr(function_module, "file_handler"):
  233. skip_files = function_module.file_handler
  234. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  235. valves = Functions.get_function_valves_by_id(filter_id)
  236. function_module.valves = function_module.Valves(
  237. **(valves if valves else {})
  238. )
  239. if not hasattr(function_module, "inlet"):
  240. continue
  241. try:
  242. inlet = function_module.inlet
  243. # Get the signature of the function
  244. sig = inspect.signature(inlet)
  245. params = {"body": body}
  246. # Extra parameters to be passed to the function
  247. custom_params = {**extra_params, "__model__": model, "__id__": filter_id}
  248. if hasattr(function_module, "UserValves") and "__user__" in sig.parameters:
  249. try:
  250. uid = custom_params["__user__"]["id"]
  251. custom_params["__user__"]["valves"] = function_module.UserValves(
  252. **Functions.get_user_valves_by_id_and_user_id(filter_id, uid)
  253. )
  254. except Exception as e:
  255. print(e)
  256. # Add extra params in contained in function signature
  257. for key, value in custom_params.items():
  258. if key in sig.parameters:
  259. params[key] = value
  260. if inspect.iscoroutinefunction(inlet):
  261. body = await inlet(**params)
  262. else:
  263. body = inlet(**params)
  264. except Exception as e:
  265. print(f"Error: {e}")
  266. raise e
  267. if skip_files and "files" in body:
  268. del body["files"]
  269. return body, {}
  270. def get_tools_function_calling_payload(messages, task_model_id, content):
  271. user_message = get_last_user_message(messages)
  272. history = "\n".join(
  273. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  274. for message in messages[::-1][:4]
  275. )
  276. prompt = f"History:\n{history}\nQuery: {user_message}"
  277. return {
  278. "model": task_model_id,
  279. "messages": [
  280. {"role": "system", "content": content},
  281. {"role": "user", "content": f"Query: {prompt}"},
  282. ],
  283. "stream": False,
  284. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  285. }
  286. async def get_content_from_response(response) -> Optional[str]:
  287. content = None
  288. if hasattr(response, "body_iterator"):
  289. async for chunk in response.body_iterator:
  290. data = json.loads(chunk.decode("utf-8"))
  291. content = data["choices"][0]["message"]["content"]
  292. # Cleanup any remaining background tasks if necessary
  293. if response.background is not None:
  294. await response.background()
  295. else:
  296. content = response["choices"][0]["message"]["content"]
  297. return content
  298. async def chat_completion_tools_handler(
  299. body: dict, user: UserModel, extra_params: dict
  300. ) -> tuple[dict, dict]:
  301. log.debug(f"{ENABLE_TOOLS_FILTER=}")
  302. if not ENABLE_TOOLS_FILTER:
  303. return body, {}
  304. skip_files = False
  305. contexts = []
  306. citations = []
  307. task_model_id = get_task_model_id(body["model"])
  308. # If tool_ids field is present, call the functions
  309. tool_ids = body.pop("tool_ids", None)
  310. if not tool_ids:
  311. return body, {}
  312. log.debug(f"{tool_ids=}")
  313. custom_params = {
  314. **extra_params,
  315. "__model__": app.state.MODELS[task_model_id],
  316. "__messages__": body["messages"],
  317. "__files__": body.get("files", []),
  318. }
  319. tools = get_tools(webui_app, tool_ids, user, custom_params)
  320. log.info(f"{tools=}")
  321. specs = [tool["spec"] for tool in tools.values()]
  322. tools_specs = json.dumps(specs)
  323. tools_function_calling_prompt = tools_function_calling_generation_template(
  324. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE, tools_specs
  325. )
  326. log.info(f"{tools_function_calling_prompt=}")
  327. payload = get_tools_function_calling_payload(
  328. body["messages"], task_model_id, tools_function_calling_prompt
  329. )
  330. try:
  331. payload = filter_pipeline(payload, user)
  332. except Exception as e:
  333. raise e
  334. try:
  335. response = await generate_chat_completions(form_data=payload, user=user)
  336. log.debug(f"{response=}")
  337. content = await get_content_from_response(response)
  338. log.debug(f"{content=}")
  339. if content is None:
  340. return body, {}
  341. result = json.loads(content)
  342. tool_function_name = result.get("name", None)
  343. if tool_function_name not in tools:
  344. return body, {}
  345. tool_function_params = result.get("parameters", {})
  346. try:
  347. tool_output = await tools[tool_function_name]["callable"](
  348. **tool_function_params
  349. )
  350. except Exception as e:
  351. tool_output = str(e)
  352. if tools[tool_function_name]["citation"]:
  353. citations.append(
  354. {
  355. "source": {
  356. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  357. },
  358. "document": [tool_output],
  359. "metadata": [{"source": tool_function_name}],
  360. }
  361. )
  362. if tools[tool_function_name]["file_handler"]:
  363. skip_files = True
  364. if isinstance(tool_output, str):
  365. contexts.append(tool_output)
  366. except Exception as e:
  367. log.exception(f"Error: {e}")
  368. content = None
  369. log.debug(f"tool_contexts: {contexts}")
  370. if skip_files and "files" in body:
  371. del body["files"]
  372. return body, {"contexts": contexts, "citations": citations}
  373. async def chat_completion_files_handler(body) -> tuple[dict, dict[str, list]]:
  374. log.debug(f"{ENABLE_FILES_FILTER=}")
  375. if not ENABLE_FILES_FILTER:
  376. return body, {}
  377. contexts = []
  378. citations = []
  379. if files := body.pop("files", None):
  380. contexts, citations = get_rag_context(
  381. files=files,
  382. messages=body["messages"],
  383. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  384. k=rag_app.state.config.TOP_K,
  385. reranking_function=rag_app.state.sentence_transformer_rf,
  386. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  387. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  388. )
  389. log.debug(f"rag_contexts: {contexts}, citations: {citations}")
  390. return body, {"contexts": contexts, "citations": citations}
  391. def is_chat_completion_request(request):
  392. return request.method == "POST" and any(
  393. endpoint in request.url.path
  394. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  395. )
  396. async def get_body_and_model_and_user(request):
  397. # Read the original request body
  398. body = await request.body()
  399. body_str = body.decode("utf-8")
  400. body = json.loads(body_str) if body_str else {}
  401. model_id = body["model"]
  402. if model_id not in app.state.MODELS:
  403. raise Exception("Model not found")
  404. model = app.state.MODELS[model_id]
  405. user = get_current_user(
  406. request,
  407. get_http_authorization_cred(request.headers.get("Authorization")),
  408. )
  409. return body, model, user
  410. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  411. async def dispatch(self, request: Request, call_next):
  412. if not is_chat_completion_request(request):
  413. return await call_next(request)
  414. log.debug(f"request.url.path: {request.url.path}")
  415. try:
  416. body, model, user = await get_body_and_model_and_user(request)
  417. except Exception as e:
  418. return JSONResponse(
  419. status_code=status.HTTP_400_BAD_REQUEST,
  420. content={"detail": str(e)},
  421. )
  422. metadata = {
  423. "chat_id": body.pop("chat_id", None),
  424. "message_id": body.pop("id", None),
  425. "session_id": body.pop("session_id", None),
  426. "valves": body.pop("valves", None),
  427. }
  428. __user__ = {
  429. "id": user.id,
  430. "email": user.email,
  431. "name": user.name,
  432. "role": user.role,
  433. }
  434. extra_params = {
  435. "__user__": __user__,
  436. "__event_emitter__": get_event_emitter(metadata),
  437. "__event_call__": get_event_call(metadata),
  438. }
  439. # Initialize data_items to store additional data to be sent to the client
  440. # Initalize contexts and citation
  441. data_items = []
  442. contexts = []
  443. citations = []
  444. try:
  445. body, flags = await chat_completion_filter_functions_handler(
  446. body, model, extra_params
  447. )
  448. except Exception as e:
  449. return JSONResponse(
  450. status_code=status.HTTP_400_BAD_REQUEST,
  451. content={"detail": str(e)},
  452. )
  453. try:
  454. body, flags = await chat_completion_tools_handler(body, user, extra_params)
  455. contexts.extend(flags.get("contexts", []))
  456. citations.extend(flags.get("citations", []))
  457. except Exception as e:
  458. log.exception(e)
  459. try:
  460. body, flags = await chat_completion_files_handler(body)
  461. contexts.extend(flags.get("contexts", []))
  462. citations.extend(flags.get("citations", []))
  463. except Exception as e:
  464. log.exception(e)
  465. # If context is not empty, insert it into the messages
  466. if len(contexts) > 0:
  467. context_string = "/n".join(contexts).strip()
  468. prompt = get_last_user_message(body["messages"])
  469. if prompt is None:
  470. raise Exception("No user message found")
  471. # Workaround for Ollama 2.0+ system prompt issue
  472. # TODO: replace with add_or_update_system_message
  473. if model["owned_by"] == "ollama":
  474. body["messages"] = prepend_to_first_user_message_content(
  475. rag_template(
  476. rag_app.state.config.RAG_TEMPLATE, context_string, prompt
  477. ),
  478. body["messages"],
  479. )
  480. else:
  481. body["messages"] = add_or_update_system_message(
  482. rag_template(
  483. rag_app.state.config.RAG_TEMPLATE, context_string, prompt
  484. ),
  485. body["messages"],
  486. )
  487. # If there are citations, add them to the data_items
  488. if len(citations) > 0:
  489. data_items.append({"citations": citations})
  490. body["metadata"] = metadata
  491. modified_body_bytes = json.dumps(body).encode("utf-8")
  492. # Replace the request body with the modified one
  493. request._body = modified_body_bytes
  494. # Set custom header to ensure content-length matches new body length
  495. request.headers.__dict__["_list"] = [
  496. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  497. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  498. ]
  499. response = await call_next(request)
  500. if not isinstance(response, StreamingResponse):
  501. return response
  502. content_type = response.headers["Content-Type"]
  503. is_openai = "text/event-stream" in content_type
  504. is_ollama = "application/x-ndjson" in content_type
  505. if not is_openai and not is_ollama:
  506. return response
  507. def wrap_item(item):
  508. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  509. async def stream_wrapper(original_generator, data_items):
  510. for item in data_items:
  511. yield wrap_item(json.dumps(item))
  512. async for data in original_generator:
  513. yield data
  514. return StreamingResponse(stream_wrapper(response.body_iterator, data_items))
  515. async def _receive(self, body: bytes):
  516. return {"type": "http.request", "body": body, "more_body": False}
  517. app.add_middleware(ChatCompletionMiddleware)
  518. ##################################
  519. #
  520. # Pipeline Middleware
  521. #
  522. ##################################
  523. def get_sorted_filters(model_id):
  524. filters = [
  525. model
  526. for model in app.state.MODELS.values()
  527. if "pipeline" in model
  528. and "type" in model["pipeline"]
  529. and model["pipeline"]["type"] == "filter"
  530. and (
  531. model["pipeline"]["pipelines"] == ["*"]
  532. or any(
  533. model_id == target_model_id
  534. for target_model_id in model["pipeline"]["pipelines"]
  535. )
  536. )
  537. ]
  538. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  539. return sorted_filters
  540. def filter_pipeline(payload, user):
  541. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  542. model_id = payload["model"]
  543. sorted_filters = get_sorted_filters(model_id)
  544. model = app.state.MODELS[model_id]
  545. if "pipeline" in model:
  546. sorted_filters.append(model)
  547. for filter in sorted_filters:
  548. r = None
  549. try:
  550. urlIdx = filter["urlIdx"]
  551. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  552. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  553. if key == "":
  554. continue
  555. headers = {"Authorization": f"Bearer {key}"}
  556. r = requests.post(
  557. f"{url}/{filter['id']}/filter/inlet",
  558. headers=headers,
  559. json={
  560. "user": user,
  561. "body": payload,
  562. },
  563. )
  564. r.raise_for_status()
  565. payload = r.json()
  566. except Exception as e:
  567. # Handle connection error here
  568. print(f"Connection error: {e}")
  569. if r is not None:
  570. res = r.json()
  571. if "detail" in res:
  572. raise Exception(r.status_code, res["detail"])
  573. return payload
  574. class PipelineMiddleware(BaseHTTPMiddleware):
  575. async def dispatch(self, request: Request, call_next):
  576. if not is_chat_completion_request(request):
  577. return await call_next(request)
  578. log.debug(f"request.url.path: {request.url.path}")
  579. # Read the original request body
  580. body = await request.body()
  581. # Decode body to string
  582. body_str = body.decode("utf-8")
  583. # Parse string to JSON
  584. data = json.loads(body_str) if body_str else {}
  585. user = get_current_user(
  586. request,
  587. get_http_authorization_cred(request.headers["Authorization"]),
  588. )
  589. try:
  590. data = filter_pipeline(data, user)
  591. except Exception as e:
  592. return JSONResponse(
  593. status_code=e.args[0],
  594. content={"detail": e.args[1]},
  595. )
  596. modified_body_bytes = json.dumps(data).encode("utf-8")
  597. # Replace the request body with the modified one
  598. request._body = modified_body_bytes
  599. # Set custom header to ensure content-length matches new body length
  600. request.headers.__dict__["_list"] = [
  601. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  602. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  603. ]
  604. response = await call_next(request)
  605. return response
  606. async def _receive(self, body: bytes):
  607. return {"type": "http.request", "body": body, "more_body": False}
  608. app.add_middleware(PipelineMiddleware)
  609. app.add_middleware(
  610. CORSMiddleware,
  611. allow_origins=origins,
  612. allow_credentials=True,
  613. allow_methods=["*"],
  614. allow_headers=["*"],
  615. )
  616. @app.middleware("http")
  617. async def commit_session_after_request(request: Request, call_next):
  618. response = await call_next(request)
  619. log.debug("Commit session after request")
  620. Session.commit()
  621. return response
  622. @app.middleware("http")
  623. async def check_url(request: Request, call_next):
  624. if len(app.state.MODELS) == 0:
  625. await get_all_models()
  626. else:
  627. pass
  628. start_time = int(time.time())
  629. response = await call_next(request)
  630. process_time = int(time.time()) - start_time
  631. response.headers["X-Process-Time"] = str(process_time)
  632. return response
  633. @app.middleware("http")
  634. async def update_embedding_function(request: Request, call_next):
  635. response = await call_next(request)
  636. if "/embedding/update" in request.url.path:
  637. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  638. return response
  639. app.mount("/ws", socket_app)
  640. app.mount("/ollama", ollama_app)
  641. app.mount("/openai", openai_app)
  642. app.mount("/images/api/v1", images_app)
  643. app.mount("/audio/api/v1", audio_app)
  644. app.mount("/rag/api/v1", rag_app)
  645. app.mount("/api/v1", webui_app)
  646. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  647. async def get_all_models():
  648. # TODO: Optimize this function
  649. pipe_models = []
  650. openai_models = []
  651. ollama_models = []
  652. pipe_models = await get_pipe_models()
  653. if app.state.config.ENABLE_OPENAI_API:
  654. openai_models = await get_openai_models()
  655. openai_models = openai_models["data"]
  656. if app.state.config.ENABLE_OLLAMA_API:
  657. ollama_models = await get_ollama_models()
  658. ollama_models = [
  659. {
  660. "id": model["model"],
  661. "name": model["name"],
  662. "object": "model",
  663. "created": int(time.time()),
  664. "owned_by": "ollama",
  665. "ollama": model,
  666. }
  667. for model in ollama_models["models"]
  668. ]
  669. models = pipe_models + openai_models + ollama_models
  670. global_action_ids = [
  671. function.id for function in Functions.get_global_action_functions()
  672. ]
  673. enabled_action_ids = [
  674. function.id
  675. for function in Functions.get_functions_by_type("action", active_only=True)
  676. ]
  677. custom_models = Models.get_all_models()
  678. for custom_model in custom_models:
  679. if custom_model.base_model_id is None:
  680. for model in models:
  681. if (
  682. custom_model.id == model["id"]
  683. or custom_model.id == model["id"].split(":")[0]
  684. ):
  685. model["name"] = custom_model.name
  686. model["info"] = custom_model.model_dump()
  687. action_ids = []
  688. if "info" in model and "meta" in model["info"]:
  689. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  690. model["action_ids"] = action_ids
  691. else:
  692. owned_by = "openai"
  693. pipe = None
  694. action_ids = []
  695. for model in models:
  696. if (
  697. custom_model.base_model_id == model["id"]
  698. or custom_model.base_model_id == model["id"].split(":")[0]
  699. ):
  700. owned_by = model["owned_by"]
  701. if "pipe" in model:
  702. pipe = model["pipe"]
  703. if "info" in model and "meta" in model["info"]:
  704. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  705. break
  706. models.append(
  707. {
  708. "id": custom_model.id,
  709. "name": custom_model.name,
  710. "object": "model",
  711. "created": custom_model.created_at,
  712. "owned_by": owned_by,
  713. "info": custom_model.model_dump(),
  714. "preset": True,
  715. **({"pipe": pipe} if pipe is not None else {}),
  716. "action_ids": action_ids,
  717. }
  718. )
  719. for model in models:
  720. action_ids = []
  721. if "action_ids" in model:
  722. action_ids = model["action_ids"]
  723. del model["action_ids"]
  724. action_ids = action_ids + global_action_ids
  725. action_ids = list(set(action_ids))
  726. action_ids = [
  727. action_id for action_id in action_ids if action_id in enabled_action_ids
  728. ]
  729. model["actions"] = []
  730. for action_id in action_ids:
  731. action = Functions.get_function_by_id(action_id)
  732. if action is None:
  733. raise Exception(f"Action not found: {action_id}")
  734. if action_id in webui_app.state.FUNCTIONS:
  735. function_module = webui_app.state.FUNCTIONS[action_id]
  736. else:
  737. function_module, _, _ = load_function_module_by_id(action_id)
  738. webui_app.state.FUNCTIONS[action_id] = function_module
  739. __webui__ = False
  740. if hasattr(function_module, "__webui__"):
  741. __webui__ = function_module.__webui__
  742. if hasattr(function_module, "actions"):
  743. actions = function_module.actions
  744. model["actions"].extend(
  745. [
  746. {
  747. "id": f"{action_id}.{_action['id']}",
  748. "name": _action.get(
  749. "name", f"{action.name} ({_action['id']})"
  750. ),
  751. "description": action.meta.description,
  752. "icon_url": _action.get(
  753. "icon_url", action.meta.manifest.get("icon_url", None)
  754. ),
  755. **({"__webui__": __webui__} if __webui__ else {}),
  756. }
  757. for _action in actions
  758. ]
  759. )
  760. else:
  761. model["actions"].append(
  762. {
  763. "id": action_id,
  764. "name": action.name,
  765. "description": action.meta.description,
  766. "icon_url": action.meta.manifest.get("icon_url", None),
  767. **({"__webui__": __webui__} if __webui__ else {}),
  768. }
  769. )
  770. app.state.MODELS = {model["id"]: model for model in models}
  771. webui_app.state.MODELS = app.state.MODELS
  772. return models
  773. @app.get("/api/models")
  774. async def get_models(user=Depends(get_verified_user)):
  775. models = await get_all_models()
  776. # Filter out filter pipelines
  777. models = [
  778. model
  779. for model in models
  780. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  781. ]
  782. if app.state.config.ENABLE_MODEL_FILTER:
  783. if user.role == "user":
  784. models = list(
  785. filter(
  786. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  787. models,
  788. )
  789. )
  790. return {"data": models}
  791. return {"data": models}
  792. @app.post("/api/chat/completions")
  793. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  794. model_id = form_data["model"]
  795. if model_id not in app.state.MODELS:
  796. raise HTTPException(
  797. status_code=status.HTTP_404_NOT_FOUND,
  798. detail="Model not found",
  799. )
  800. model = app.state.MODELS[model_id]
  801. if model.get("pipe"):
  802. return await generate_function_chat_completion(form_data, user=user)
  803. for key in ["tool_ids", "files"]:
  804. if key in form_data:
  805. del form_data[key]
  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. )