main.py 75 KB

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