main.py 71 KB

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