main.py 70 KB

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