main.py 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803
  1. import asyncio
  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 random
  11. from contextlib import asynccontextmanager
  12. from typing import Optional
  13. from aiocache import cached
  14. import aiohttp
  15. import requests
  16. from fastapi import (
  17. Depends,
  18. FastAPI,
  19. File,
  20. Form,
  21. HTTPException,
  22. Request,
  23. UploadFile,
  24. status,
  25. )
  26. from fastapi.middleware.cors import CORSMiddleware
  27. from fastapi.responses import JSONResponse, RedirectResponse
  28. from fastapi.staticfiles import StaticFiles
  29. from pydantic import BaseModel
  30. from sqlalchemy import text
  31. from starlette.exceptions import HTTPException as StarletteHTTPException
  32. from starlette.middleware.base import BaseHTTPMiddleware
  33. from starlette.middleware.sessions import SessionMiddleware
  34. from starlette.responses import Response, StreamingResponse
  35. from open_webui.apps.audio.main import app as audio_app
  36. from open_webui.apps.images.main import app as images_app
  37. from open_webui.apps.ollama.main import (
  38. app as ollama_app,
  39. get_all_models as get_ollama_models,
  40. generate_chat_completion as generate_ollama_chat_completion,
  41. GenerateChatCompletionForm,
  42. )
  43. from open_webui.apps.openai.main import (
  44. app as openai_app,
  45. generate_chat_completion as generate_openai_chat_completion,
  46. get_all_models as get_openai_models,
  47. get_all_models_responses as get_openai_models_responses,
  48. )
  49. from open_webui.apps.retrieval.main import app as retrieval_app
  50. from open_webui.apps.retrieval.utils import get_sources_from_files
  51. from open_webui.apps.socket.main import (
  52. app as socket_app,
  53. periodic_usage_pool_cleanup,
  54. get_event_call,
  55. get_event_emitter,
  56. )
  57. from open_webui.apps.webui.internal.db import Session
  58. from open_webui.apps.webui.main import (
  59. app as webui_app,
  60. generate_function_chat_completion,
  61. get_all_models as get_open_webui_models,
  62. )
  63. from open_webui.apps.webui.models.functions import Functions
  64. from open_webui.apps.webui.models.models import Models
  65. from open_webui.apps.webui.models.users import UserModel, Users
  66. from open_webui.apps.webui.utils import load_function_module_by_id
  67. from open_webui.config import (
  68. CACHE_DIR,
  69. CORS_ALLOW_ORIGIN,
  70. DEFAULT_LOCALE,
  71. ENABLE_ADMIN_CHAT_ACCESS,
  72. ENABLE_ADMIN_EXPORT,
  73. ENABLE_OLLAMA_API,
  74. ENABLE_OPENAI_API,
  75. ENABLE_TAGS_GENERATION,
  76. ENV,
  77. FRONTEND_BUILD_DIR,
  78. OAUTH_PROVIDERS,
  79. STATIC_DIR,
  80. TASK_MODEL,
  81. TASK_MODEL_EXTERNAL,
  82. ENABLE_SEARCH_QUERY_GENERATION,
  83. ENABLE_RETRIEVAL_QUERY_GENERATION,
  84. QUERY_GENERATION_PROMPT_TEMPLATE,
  85. DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE,
  86. TITLE_GENERATION_PROMPT_TEMPLATE,
  87. TAGS_GENERATION_PROMPT_TEMPLATE,
  88. ENABLE_AUTOCOMPLETE_GENERATION,
  89. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH,
  90. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE,
  91. DEFAULT_AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE,
  92. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  93. WEBHOOK_URL,
  94. WEBUI_AUTH,
  95. WEBUI_NAME,
  96. AppConfig,
  97. reset_config,
  98. )
  99. from open_webui.constants import TASKS
  100. from open_webui.env import (
  101. CHANGELOG,
  102. GLOBAL_LOG_LEVEL,
  103. SAFE_MODE,
  104. SRC_LOG_LEVELS,
  105. VERSION,
  106. WEBUI_BUILD_HASH,
  107. WEBUI_SECRET_KEY,
  108. WEBUI_SESSION_COOKIE_SAME_SITE,
  109. WEBUI_SESSION_COOKIE_SECURE,
  110. WEBUI_URL,
  111. RESET_CONFIG_ON_START,
  112. OFFLINE_MODE,
  113. )
  114. from open_webui.utils.misc import (
  115. add_or_update_system_message,
  116. get_last_user_message,
  117. prepend_to_first_user_message_content,
  118. )
  119. from open_webui.utils.oauth import oauth_manager
  120. from open_webui.utils.payload import convert_payload_openai_to_ollama
  121. from open_webui.utils.response import (
  122. convert_response_ollama_to_openai,
  123. convert_streaming_response_ollama_to_openai,
  124. )
  125. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  126. from open_webui.utils.task import (
  127. rag_template,
  128. title_generation_template,
  129. query_generation_template,
  130. autocomplete_generation_template,
  131. tags_generation_template,
  132. emoji_generation_template,
  133. moa_response_generation_template,
  134. tools_function_calling_generation_template,
  135. )
  136. from open_webui.utils.tools import get_tools
  137. from open_webui.utils.utils import (
  138. decode_token,
  139. get_admin_user,
  140. get_current_user,
  141. get_http_authorization_cred,
  142. get_verified_user,
  143. )
  144. from open_webui.utils.access_control import has_access
  145. if SAFE_MODE:
  146. print("SAFE MODE ENABLED")
  147. Functions.deactivate_all_functions()
  148. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  149. log = logging.getLogger(__name__)
  150. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  151. class SPAStaticFiles(StaticFiles):
  152. async def get_response(self, path: str, scope):
  153. try:
  154. return await super().get_response(path, scope)
  155. except (HTTPException, StarletteHTTPException) as ex:
  156. if ex.status_code == 404:
  157. return await super().get_response("index.html", scope)
  158. else:
  159. raise ex
  160. print(
  161. rf"""
  162. ___ __ __ _ _ _ ___
  163. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  164. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  165. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  166. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  167. |_|
  168. v{VERSION} - building the best open-source AI user interface.
  169. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  170. https://github.com/open-webui/open-webui
  171. """
  172. )
  173. @asynccontextmanager
  174. async def lifespan(app: FastAPI):
  175. if RESET_CONFIG_ON_START:
  176. reset_config()
  177. asyncio.create_task(periodic_usage_pool_cleanup())
  178. yield
  179. app = FastAPI(
  180. docs_url="/docs" if ENV == "dev" else None,
  181. openapi_url="/openapi.json" if ENV == "dev" else None,
  182. redoc_url=None,
  183. lifespan=lifespan,
  184. )
  185. app.state.config = AppConfig()
  186. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  187. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  188. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  189. app.state.config.TASK_MODEL = TASK_MODEL
  190. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  191. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  192. app.state.config.ENABLE_AUTOCOMPLETE_GENERATION = ENABLE_AUTOCOMPLETE_GENERATION
  193. app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = (
  194. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH
  195. )
  196. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  197. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  198. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  199. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  200. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  201. app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = (
  202. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  203. )
  204. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  205. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  206. )
  207. ##################################
  208. #
  209. # ChatCompletion Middleware
  210. #
  211. ##################################
  212. def get_filter_function_ids(model):
  213. def get_priority(function_id):
  214. function = Functions.get_function_by_id(function_id)
  215. if function is not None and hasattr(function, "valves"):
  216. # TODO: Fix FunctionModel
  217. return (function.valves if function.valves else {}).get("priority", 0)
  218. return 0
  219. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  220. if "info" in model and "meta" in model["info"]:
  221. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  222. filter_ids = list(set(filter_ids))
  223. enabled_filter_ids = [
  224. function.id
  225. for function in Functions.get_functions_by_type("filter", active_only=True)
  226. ]
  227. filter_ids = [
  228. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  229. ]
  230. filter_ids.sort(key=get_priority)
  231. return filter_ids
  232. async def chat_completion_filter_functions_handler(body, model, extra_params):
  233. skip_files = None
  234. filter_ids = get_filter_function_ids(model)
  235. for filter_id in filter_ids:
  236. filter = Functions.get_function_by_id(filter_id)
  237. if not filter:
  238. continue
  239. if filter_id in webui_app.state.FUNCTIONS:
  240. function_module = webui_app.state.FUNCTIONS[filter_id]
  241. else:
  242. function_module, _, _ = load_function_module_by_id(filter_id)
  243. webui_app.state.FUNCTIONS[filter_id] = function_module
  244. # Check if the function has a file_handler variable
  245. if hasattr(function_module, "file_handler"):
  246. skip_files = function_module.file_handler
  247. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  248. valves = Functions.get_function_valves_by_id(filter_id)
  249. function_module.valves = function_module.Valves(
  250. **(valves if valves else {})
  251. )
  252. if not hasattr(function_module, "inlet"):
  253. continue
  254. try:
  255. inlet = function_module.inlet
  256. # Get the signature of the function
  257. sig = inspect.signature(inlet)
  258. params = {"body": body} | {
  259. k: v
  260. for k, v in {
  261. **extra_params,
  262. "__model__": model,
  263. "__id__": filter_id,
  264. }.items()
  265. if k in sig.parameters
  266. }
  267. if "__user__" in params and hasattr(function_module, "UserValves"):
  268. try:
  269. params["__user__"]["valves"] = function_module.UserValves(
  270. **Functions.get_user_valves_by_id_and_user_id(
  271. filter_id, params["__user__"]["id"]
  272. )
  273. )
  274. except Exception as e:
  275. print(e)
  276. if inspect.iscoroutinefunction(inlet):
  277. body = await inlet(**params)
  278. else:
  279. body = inlet(**params)
  280. except Exception as e:
  281. print(f"Error: {e}")
  282. raise e
  283. if skip_files and "files" in body.get("metadata", {}):
  284. del body["metadata"]["files"]
  285. return body, {}
  286. def get_tools_function_calling_payload(messages, task_model_id, content):
  287. user_message = get_last_user_message(messages)
  288. history = "\n".join(
  289. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  290. for message in messages[::-1][:4]
  291. )
  292. prompt = f"History:\n{history}\nQuery: {user_message}"
  293. return {
  294. "model": task_model_id,
  295. "messages": [
  296. {"role": "system", "content": content},
  297. {"role": "user", "content": f"Query: {prompt}"},
  298. ],
  299. "stream": False,
  300. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  301. }
  302. async def get_content_from_response(response) -> Optional[str]:
  303. content = None
  304. if hasattr(response, "body_iterator"):
  305. async for chunk in response.body_iterator:
  306. data = json.loads(chunk.decode("utf-8"))
  307. content = data["choices"][0]["message"]["content"]
  308. # Cleanup any remaining background tasks if necessary
  309. if response.background is not None:
  310. await response.background()
  311. else:
  312. content = response["choices"][0]["message"]["content"]
  313. return content
  314. def get_task_model_id(
  315. default_model_id: str, task_model: str, task_model_external: str, models
  316. ) -> str:
  317. # Set the task model
  318. task_model_id = default_model_id
  319. # Check if the user has a custom task model and use that model
  320. if models[task_model_id]["owned_by"] == "ollama":
  321. if task_model and task_model in models:
  322. task_model_id = task_model
  323. else:
  324. if task_model_external and task_model_external in models:
  325. task_model_id = task_model_external
  326. return task_model_id
  327. async def chat_completion_tools_handler(
  328. body: dict, user: UserModel, models, extra_params: dict
  329. ) -> tuple[dict, dict]:
  330. # If tool_ids field is present, call the functions
  331. metadata = body.get("metadata", {})
  332. tool_ids = metadata.get("tool_ids", None)
  333. log.debug(f"{tool_ids=}")
  334. if not tool_ids:
  335. return body, {}
  336. skip_files = False
  337. sources = []
  338. task_model_id = get_task_model_id(
  339. body["model"],
  340. app.state.config.TASK_MODEL,
  341. app.state.config.TASK_MODEL_EXTERNAL,
  342. models,
  343. )
  344. tools = get_tools(
  345. webui_app,
  346. tool_ids,
  347. user,
  348. {
  349. **extra_params,
  350. "__model__": models[task_model_id],
  351. "__messages__": body["messages"],
  352. "__files__": metadata.get("files", []),
  353. },
  354. )
  355. log.info(f"{tools=}")
  356. specs = [tool["spec"] for tool in tools.values()]
  357. tools_specs = json.dumps(specs)
  358. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  359. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  360. else:
  361. 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."""
  362. tools_function_calling_prompt = tools_function_calling_generation_template(
  363. template, tools_specs
  364. )
  365. log.info(f"{tools_function_calling_prompt=}")
  366. payload = get_tools_function_calling_payload(
  367. body["messages"], task_model_id, tools_function_calling_prompt
  368. )
  369. try:
  370. payload = filter_pipeline(payload, user, models)
  371. except Exception as e:
  372. raise e
  373. try:
  374. response = await generate_chat_completions(form_data=payload, user=user)
  375. log.debug(f"{response=}")
  376. content = await get_content_from_response(response)
  377. log.debug(f"{content=}")
  378. if not content:
  379. return body, {}
  380. try:
  381. content = content[content.find("{") : content.rfind("}") + 1]
  382. if not content:
  383. raise Exception("No JSON object found in the response")
  384. result = json.loads(content)
  385. tool_function_name = result.get("name", None)
  386. if tool_function_name not in tools:
  387. return body, {}
  388. tool_function_params = result.get("parameters", {})
  389. try:
  390. required_params = (
  391. tools[tool_function_name]
  392. .get("spec", {})
  393. .get("parameters", {})
  394. .get("required", [])
  395. )
  396. tool_function = tools[tool_function_name]["callable"]
  397. tool_function_params = {
  398. k: v
  399. for k, v in tool_function_params.items()
  400. if k in required_params
  401. }
  402. tool_output = await tool_function(**tool_function_params)
  403. except Exception as e:
  404. tool_output = str(e)
  405. print(tools[tool_function_name]["citation"])
  406. if isinstance(tool_output, str):
  407. if tools[tool_function_name]["citation"]:
  408. sources.append(
  409. {
  410. "source": {
  411. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  412. },
  413. "document": [tool_output],
  414. "metadata": [
  415. {
  416. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  417. }
  418. ],
  419. }
  420. )
  421. else:
  422. sources.append(
  423. {
  424. "source": {},
  425. "document": [tool_output],
  426. "metadata": [
  427. {
  428. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  429. }
  430. ],
  431. }
  432. )
  433. if tools[tool_function_name]["file_handler"]:
  434. skip_files = True
  435. except Exception as e:
  436. log.exception(f"Error: {e}")
  437. content = None
  438. except Exception as e:
  439. log.exception(f"Error: {e}")
  440. content = None
  441. log.debug(f"tool_contexts: {sources}")
  442. if skip_files and "files" in body.get("metadata", {}):
  443. del body["metadata"]["files"]
  444. return body, {"sources": sources}
  445. async def chat_completion_files_handler(
  446. body: dict, user: UserModel
  447. ) -> tuple[dict, dict[str, list]]:
  448. sources = []
  449. if files := body.get("metadata", {}).get("files", None):
  450. try:
  451. queries_response = await generate_queries(
  452. {
  453. "model": body["model"],
  454. "messages": body["messages"],
  455. "type": "retrieval",
  456. },
  457. user,
  458. )
  459. queries_response = queries_response["choices"][0]["message"]["content"]
  460. try:
  461. bracket_start = queries_response.find("{")
  462. bracket_end = queries_response.rfind("}") + 1
  463. if bracket_start == -1 or bracket_end == -1:
  464. raise Exception("No JSON object found in the response")
  465. queries_response = queries_response[bracket_start:bracket_end]
  466. queries_response = json.loads(queries_response)
  467. except Exception as e:
  468. queries_response = {"queries": [queries_response]}
  469. queries = queries_response.get("queries", [])
  470. except Exception as e:
  471. queries = []
  472. if len(queries) == 0:
  473. queries = [get_last_user_message(body["messages"])]
  474. sources = get_sources_from_files(
  475. files=files,
  476. queries=queries,
  477. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  478. k=retrieval_app.state.config.TOP_K,
  479. reranking_function=retrieval_app.state.sentence_transformer_rf,
  480. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  481. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  482. )
  483. log.debug(f"rag_contexts:sources: {sources}")
  484. return body, {"sources": sources}
  485. def is_chat_completion_request(request):
  486. return request.method == "POST" and any(
  487. endpoint in request.url.path
  488. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  489. )
  490. async def get_body_and_model_and_user(request, models):
  491. # Read the original request body
  492. body = await request.body()
  493. body_str = body.decode("utf-8")
  494. body = json.loads(body_str) if body_str else {}
  495. model_id = body["model"]
  496. if model_id not in models:
  497. raise Exception("Model not found")
  498. model = models[model_id]
  499. user = get_current_user(
  500. request,
  501. get_http_authorization_cred(request.headers.get("Authorization")),
  502. )
  503. return body, model, user
  504. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  505. async def dispatch(self, request: Request, call_next):
  506. if not is_chat_completion_request(request):
  507. return await call_next(request)
  508. log.debug(f"request.url.path: {request.url.path}")
  509. model_list = await get_all_models()
  510. models = {model["id"]: model for model in model_list}
  511. try:
  512. body, model, user = await get_body_and_model_and_user(request, models)
  513. except Exception as e:
  514. return JSONResponse(
  515. status_code=status.HTTP_400_BAD_REQUEST,
  516. content={"detail": str(e)},
  517. )
  518. model_info = Models.get_model_by_id(model["id"])
  519. if user.role == "user":
  520. if model.get("arena"):
  521. if not has_access(
  522. user.id,
  523. type="read",
  524. access_control=model.get("info", {})
  525. .get("meta", {})
  526. .get("access_control", {}),
  527. ):
  528. raise HTTPException(
  529. status_code=403,
  530. detail="Model not found",
  531. )
  532. else:
  533. if not model_info:
  534. return JSONResponse(
  535. status_code=status.HTTP_404_NOT_FOUND,
  536. content={"detail": "Model not found"},
  537. )
  538. elif not (
  539. user.id == model_info.user_id
  540. or has_access(
  541. user.id, type="read", access_control=model_info.access_control
  542. )
  543. ):
  544. return JSONResponse(
  545. status_code=status.HTTP_403_FORBIDDEN,
  546. content={"detail": "User does not have access to the model"},
  547. )
  548. metadata = {
  549. "chat_id": body.pop("chat_id", None),
  550. "message_id": body.pop("id", None),
  551. "session_id": body.pop("session_id", None),
  552. "tool_ids": body.get("tool_ids", None),
  553. "files": body.get("files", None),
  554. }
  555. body["metadata"] = metadata
  556. extra_params = {
  557. "__event_emitter__": get_event_emitter(metadata),
  558. "__event_call__": get_event_call(metadata),
  559. "__user__": {
  560. "id": user.id,
  561. "email": user.email,
  562. "name": user.name,
  563. "role": user.role,
  564. },
  565. "__metadata__": metadata,
  566. }
  567. # Initialize data_items to store additional data to be sent to the client
  568. # Initialize contexts and citation
  569. data_items = []
  570. sources = []
  571. try:
  572. body, flags = await chat_completion_filter_functions_handler(
  573. body, model, extra_params
  574. )
  575. except Exception as e:
  576. return JSONResponse(
  577. status_code=status.HTTP_400_BAD_REQUEST,
  578. content={"detail": str(e)},
  579. )
  580. tool_ids = body.pop("tool_ids", None)
  581. files = body.pop("files", None)
  582. metadata = {
  583. **metadata,
  584. "tool_ids": tool_ids,
  585. "files": files,
  586. }
  587. body["metadata"] = metadata
  588. try:
  589. body, flags = await chat_completion_tools_handler(
  590. body, user, models, extra_params
  591. )
  592. sources.extend(flags.get("sources", []))
  593. except Exception as e:
  594. log.exception(e)
  595. try:
  596. body, flags = await chat_completion_files_handler(body, user)
  597. sources.extend(flags.get("sources", []))
  598. except Exception as e:
  599. log.exception(e)
  600. # If context is not empty, insert it into the messages
  601. if len(sources) > 0:
  602. context_string = ""
  603. for source_idx, source in enumerate(sources):
  604. source_id = source.get("source", {}).get("name", "")
  605. if "document" in source:
  606. for doc_idx, doc_context in enumerate(source["document"]):
  607. metadata = source.get("metadata")
  608. doc_source_id = None
  609. if metadata:
  610. doc_source_id = metadata[doc_idx].get("source", source_id)
  611. if source_id:
  612. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  613. else:
  614. # If there is no source_id, then do not include the source_id tag
  615. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  616. context_string = context_string.strip()
  617. prompt = get_last_user_message(body["messages"])
  618. if prompt is None:
  619. raise Exception("No user message found")
  620. if (
  621. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  622. and context_string.strip() == ""
  623. ):
  624. log.debug(
  625. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  626. )
  627. # Workaround for Ollama 2.0+ system prompt issue
  628. # TODO: replace with add_or_update_system_message
  629. if model["owned_by"] == "ollama":
  630. body["messages"] = prepend_to_first_user_message_content(
  631. rag_template(
  632. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  633. ),
  634. body["messages"],
  635. )
  636. else:
  637. body["messages"] = add_or_update_system_message(
  638. rag_template(
  639. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  640. ),
  641. body["messages"],
  642. )
  643. # If there are citations, add them to the data_items
  644. sources = [
  645. source for source in sources if source.get("source", {}).get("name", "")
  646. ]
  647. if len(sources) > 0:
  648. data_items.append({"sources": sources})
  649. modified_body_bytes = json.dumps(body).encode("utf-8")
  650. # Replace the request body with the modified one
  651. request._body = modified_body_bytes
  652. # Set custom header to ensure content-length matches new body length
  653. request.headers.__dict__["_list"] = [
  654. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  655. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  656. ]
  657. response = await call_next(request)
  658. if not isinstance(response, StreamingResponse):
  659. return response
  660. content_type = response.headers["Content-Type"]
  661. is_openai = "text/event-stream" in content_type
  662. is_ollama = "application/x-ndjson" in content_type
  663. if not is_openai and not is_ollama:
  664. return response
  665. def wrap_item(item):
  666. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  667. async def stream_wrapper(original_generator, data_items):
  668. for item in data_items:
  669. yield wrap_item(json.dumps(item))
  670. async for data in original_generator:
  671. yield data
  672. return StreamingResponse(
  673. stream_wrapper(response.body_iterator, data_items),
  674. headers=dict(response.headers),
  675. )
  676. async def _receive(self, body: bytes):
  677. return {"type": "http.request", "body": body, "more_body": False}
  678. app.add_middleware(ChatCompletionMiddleware)
  679. ##################################
  680. #
  681. # Pipeline Middleware
  682. #
  683. ##################################
  684. def get_sorted_filters(model_id, models):
  685. filters = [
  686. model
  687. for model in models.values()
  688. if "pipeline" in model
  689. and "type" in model["pipeline"]
  690. and model["pipeline"]["type"] == "filter"
  691. and (
  692. model["pipeline"]["pipelines"] == ["*"]
  693. or any(
  694. model_id == target_model_id
  695. for target_model_id in model["pipeline"]["pipelines"]
  696. )
  697. )
  698. ]
  699. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  700. return sorted_filters
  701. def filter_pipeline(payload, user, models):
  702. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  703. model_id = payload["model"]
  704. sorted_filters = get_sorted_filters(model_id, models)
  705. model = models[model_id]
  706. if "pipeline" in model:
  707. sorted_filters.append(model)
  708. for filter in sorted_filters:
  709. r = None
  710. try:
  711. urlIdx = filter["urlIdx"]
  712. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  713. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  714. if key == "":
  715. continue
  716. headers = {"Authorization": f"Bearer {key}"}
  717. r = requests.post(
  718. f"{url}/{filter['id']}/filter/inlet",
  719. headers=headers,
  720. json={
  721. "user": user,
  722. "body": payload,
  723. },
  724. )
  725. r.raise_for_status()
  726. payload = r.json()
  727. except Exception as e:
  728. # Handle connection error here
  729. print(f"Connection error: {e}")
  730. if r is not None:
  731. res = r.json()
  732. if "detail" in res:
  733. raise Exception(r.status_code, res["detail"])
  734. return payload
  735. class PipelineMiddleware(BaseHTTPMiddleware):
  736. async def dispatch(self, request: Request, call_next):
  737. if not is_chat_completion_request(request):
  738. return await call_next(request)
  739. log.debug(f"request.url.path: {request.url.path}")
  740. # Read the original request body
  741. body = await request.body()
  742. # Decode body to string
  743. body_str = body.decode("utf-8")
  744. # Parse string to JSON
  745. data = json.loads(body_str) if body_str else {}
  746. try:
  747. user = get_current_user(
  748. request,
  749. get_http_authorization_cred(request.headers["Authorization"]),
  750. )
  751. except KeyError as e:
  752. if len(e.args) > 1:
  753. return JSONResponse(
  754. status_code=e.args[0],
  755. content={"detail": e.args[1]},
  756. )
  757. else:
  758. return JSONResponse(
  759. status_code=status.HTTP_401_UNAUTHORIZED,
  760. content={"detail": "Not authenticated"},
  761. )
  762. except HTTPException as e:
  763. return JSONResponse(
  764. status_code=e.status_code,
  765. content={"detail": e.detail},
  766. )
  767. model_list = await get_all_models()
  768. models = {model["id"]: model for model in model_list}
  769. try:
  770. data = filter_pipeline(data, user, models)
  771. except Exception as e:
  772. if len(e.args) > 1:
  773. return JSONResponse(
  774. status_code=e.args[0],
  775. content={"detail": e.args[1]},
  776. )
  777. else:
  778. return JSONResponse(
  779. status_code=status.HTTP_400_BAD_REQUEST,
  780. content={"detail": str(e)},
  781. )
  782. modified_body_bytes = json.dumps(data).encode("utf-8")
  783. # Replace the request body with the modified one
  784. request._body = modified_body_bytes
  785. # Set custom header to ensure content-length matches new body length
  786. request.headers.__dict__["_list"] = [
  787. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  788. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  789. ]
  790. response = await call_next(request)
  791. return response
  792. async def _receive(self, body: bytes):
  793. return {"type": "http.request", "body": body, "more_body": False}
  794. app.add_middleware(PipelineMiddleware)
  795. from urllib.parse import urlencode, parse_qs, urlparse
  796. class RedirectMiddleware(BaseHTTPMiddleware):
  797. async def dispatch(self, request: Request, call_next):
  798. # Check if the request is a GET request
  799. if request.method == "GET":
  800. path = request.url.path
  801. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  802. # Check for the specific watch path and the presence of 'v' parameter
  803. if path.endswith("/watch") and "v" in query_params:
  804. video_id = query_params["v"][0] # Extract the first 'v' parameter
  805. encoded_video_id = urlencode({"youtube": video_id})
  806. redirect_url = f"/?{encoded_video_id}"
  807. return RedirectResponse(url=redirect_url)
  808. # Proceed with the normal flow of other requests
  809. response = await call_next(request)
  810. return response
  811. # Add the middleware to the app
  812. app.add_middleware(RedirectMiddleware)
  813. app.add_middleware(
  814. CORSMiddleware,
  815. allow_origins=CORS_ALLOW_ORIGIN,
  816. allow_credentials=True,
  817. allow_methods=["*"],
  818. allow_headers=["*"],
  819. )
  820. app.add_middleware(SecurityHeadersMiddleware)
  821. @app.middleware("http")
  822. async def commit_session_after_request(request: Request, call_next):
  823. response = await call_next(request)
  824. # log.debug("Commit session after request")
  825. Session.commit()
  826. return response
  827. @app.middleware("http")
  828. async def check_url(request: Request, call_next):
  829. start_time = int(time.time())
  830. request.state.enable_api_key = webui_app.state.config.ENABLE_API_KEY
  831. response = await call_next(request)
  832. process_time = int(time.time()) - start_time
  833. response.headers["X-Process-Time"] = str(process_time)
  834. return response
  835. @app.middleware("http")
  836. async def update_embedding_function(request: Request, call_next):
  837. response = await call_next(request)
  838. if "/embedding/update" in request.url.path:
  839. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  840. return response
  841. @app.middleware("http")
  842. async def inspect_websocket(request: Request, call_next):
  843. if (
  844. "/ws/socket.io" in request.url.path
  845. and request.query_params.get("transport") == "websocket"
  846. ):
  847. upgrade = (request.headers.get("Upgrade") or "").lower()
  848. connection = (request.headers.get("Connection") or "").lower().split(",")
  849. # Check that there's the correct headers for an upgrade, else reject the connection
  850. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  851. if upgrade != "websocket" or "upgrade" not in connection:
  852. return JSONResponse(
  853. status_code=status.HTTP_400_BAD_REQUEST,
  854. content={"detail": "Invalid WebSocket upgrade request"},
  855. )
  856. return await call_next(request)
  857. app.mount("/ws", socket_app)
  858. app.mount("/ollama", ollama_app)
  859. app.mount("/openai", openai_app)
  860. app.mount("/images/api/v1", images_app)
  861. app.mount("/audio/api/v1", audio_app)
  862. app.mount("/retrieval/api/v1", retrieval_app)
  863. app.mount("/api/v1", webui_app)
  864. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  865. async def get_all_base_models():
  866. open_webui_models = []
  867. openai_models = []
  868. ollama_models = []
  869. if app.state.config.ENABLE_OPENAI_API:
  870. openai_models = await get_openai_models()
  871. openai_models = openai_models["data"]
  872. if app.state.config.ENABLE_OLLAMA_API:
  873. ollama_models = await get_ollama_models()
  874. ollama_models = [
  875. {
  876. "id": model["model"],
  877. "name": model["name"],
  878. "object": "model",
  879. "created": int(time.time()),
  880. "owned_by": "ollama",
  881. "ollama": model,
  882. }
  883. for model in ollama_models["models"]
  884. ]
  885. open_webui_models = await get_open_webui_models()
  886. models = open_webui_models + openai_models + ollama_models
  887. return models
  888. @cached(ttl=3)
  889. async def get_all_models():
  890. models = await get_all_base_models()
  891. # If there are no models, return an empty list
  892. if len([model for model in models if not model.get("arena", False)]) == 0:
  893. return []
  894. global_action_ids = [
  895. function.id for function in Functions.get_global_action_functions()
  896. ]
  897. enabled_action_ids = [
  898. function.id
  899. for function in Functions.get_functions_by_type("action", active_only=True)
  900. ]
  901. custom_models = Models.get_all_models()
  902. for custom_model in custom_models:
  903. if custom_model.base_model_id is None:
  904. for model in models:
  905. if (
  906. custom_model.id == model["id"]
  907. or custom_model.id == model["id"].split(":")[0]
  908. ):
  909. if custom_model.is_active:
  910. model["name"] = custom_model.name
  911. model["info"] = custom_model.model_dump()
  912. action_ids = []
  913. if "info" in model and "meta" in model["info"]:
  914. action_ids.extend(
  915. model["info"]["meta"].get("actionIds", [])
  916. )
  917. model["action_ids"] = action_ids
  918. else:
  919. models.remove(model)
  920. elif custom_model.is_active and (
  921. custom_model.id not in [model["id"] for model in models]
  922. ):
  923. owned_by = "openai"
  924. pipe = None
  925. action_ids = []
  926. for model in models:
  927. if (
  928. custom_model.base_model_id == model["id"]
  929. or custom_model.base_model_id == model["id"].split(":")[0]
  930. ):
  931. owned_by = model["owned_by"]
  932. if "pipe" in model:
  933. pipe = model["pipe"]
  934. break
  935. if custom_model.meta:
  936. meta = custom_model.meta.model_dump()
  937. if "actionIds" in meta:
  938. action_ids.extend(meta["actionIds"])
  939. models.append(
  940. {
  941. "id": f"{custom_model.id}",
  942. "name": custom_model.name,
  943. "object": "model",
  944. "created": custom_model.created_at,
  945. "owned_by": owned_by,
  946. "info": custom_model.model_dump(),
  947. "preset": True,
  948. **({"pipe": pipe} if pipe is not None else {}),
  949. "action_ids": action_ids,
  950. }
  951. )
  952. # Process action_ids to get the actions
  953. def get_action_items_from_module(function, module):
  954. actions = []
  955. if hasattr(module, "actions"):
  956. actions = module.actions
  957. return [
  958. {
  959. "id": f"{function.id}.{action['id']}",
  960. "name": action.get("name", f"{function.name} ({action['id']})"),
  961. "description": function.meta.description,
  962. "icon_url": action.get(
  963. "icon_url", function.meta.manifest.get("icon_url", None)
  964. ),
  965. }
  966. for action in actions
  967. ]
  968. else:
  969. return [
  970. {
  971. "id": function.id,
  972. "name": function.name,
  973. "description": function.meta.description,
  974. "icon_url": function.meta.manifest.get("icon_url", None),
  975. }
  976. ]
  977. def get_function_module_by_id(function_id):
  978. if function_id in webui_app.state.FUNCTIONS:
  979. function_module = webui_app.state.FUNCTIONS[function_id]
  980. else:
  981. function_module, _, _ = load_function_module_by_id(function_id)
  982. webui_app.state.FUNCTIONS[function_id] = function_module
  983. for model in models:
  984. action_ids = [
  985. action_id
  986. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  987. if action_id in enabled_action_ids
  988. ]
  989. model["actions"] = []
  990. for action_id in action_ids:
  991. action_function = Functions.get_function_by_id(action_id)
  992. if action_function is None:
  993. raise Exception(f"Action not found: {action_id}")
  994. function_module = get_function_module_by_id(action_id)
  995. model["actions"].extend(
  996. get_action_items_from_module(action_function, function_module)
  997. )
  998. log.debug(f"get_all_models() returned {len(models)} models")
  999. return models
  1000. @app.get("/api/models")
  1001. async def get_models(user=Depends(get_verified_user)):
  1002. models = await get_all_models()
  1003. # Filter out filter pipelines
  1004. models = [
  1005. model
  1006. for model in models
  1007. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  1008. ]
  1009. model_order_list = webui_app.state.config.MODEL_ORDER_LIST
  1010. if model_order_list:
  1011. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  1012. # Sort models by order list priority, with fallback for those not in the list
  1013. models.sort(
  1014. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  1015. )
  1016. # Filter out models that the user does not have access to
  1017. if user.role == "user":
  1018. filtered_models = []
  1019. for model in models:
  1020. if model.get("arena"):
  1021. if has_access(
  1022. user.id,
  1023. type="read",
  1024. access_control=model.get("info", {})
  1025. .get("meta", {})
  1026. .get("access_control", {}),
  1027. ):
  1028. filtered_models.append(model)
  1029. continue
  1030. model_info = Models.get_model_by_id(model["id"])
  1031. if model_info:
  1032. if user.id == model_info.user_id or has_access(
  1033. user.id, type="read", access_control=model_info.access_control
  1034. ):
  1035. filtered_models.append(model)
  1036. models = filtered_models
  1037. log.debug(
  1038. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  1039. )
  1040. return {"data": models}
  1041. @app.get("/api/models/base")
  1042. async def get_base_models(user=Depends(get_admin_user)):
  1043. models = await get_all_base_models()
  1044. # Filter out arena models
  1045. models = [model for model in models if not model.get("arena", False)]
  1046. return {"data": models}
  1047. @app.post("/api/chat/completions")
  1048. async def generate_chat_completions(
  1049. form_data: dict, user=Depends(get_verified_user), bypass_filter: bool = False
  1050. ):
  1051. model_list = await get_all_models()
  1052. models = {model["id"]: model for model in model_list}
  1053. model_id = form_data["model"]
  1054. if model_id not in models:
  1055. raise HTTPException(
  1056. status_code=status.HTTP_404_NOT_FOUND,
  1057. detail="Model not found",
  1058. )
  1059. model = models[model_id]
  1060. # Check if user has access to the model
  1061. if not bypass_filter and user.role == "user":
  1062. if model.get("arena"):
  1063. if not has_access(
  1064. user.id,
  1065. type="read",
  1066. access_control=model.get("info", {})
  1067. .get("meta", {})
  1068. .get("access_control", {}),
  1069. ):
  1070. raise HTTPException(
  1071. status_code=403,
  1072. detail="Model not found",
  1073. )
  1074. else:
  1075. model_info = Models.get_model_by_id(model_id)
  1076. if not model_info:
  1077. raise HTTPException(
  1078. status_code=404,
  1079. detail="Model not found",
  1080. )
  1081. elif not (
  1082. user.id == model_info.user_id
  1083. or has_access(
  1084. user.id, type="read", access_control=model_info.access_control
  1085. )
  1086. ):
  1087. raise HTTPException(
  1088. status_code=403,
  1089. detail="Model not found",
  1090. )
  1091. if model["owned_by"] == "arena":
  1092. model_ids = model.get("info", {}).get("meta", {}).get("model_ids")
  1093. filter_mode = model.get("info", {}).get("meta", {}).get("filter_mode")
  1094. if model_ids and filter_mode == "exclude":
  1095. model_ids = [
  1096. model["id"]
  1097. for model in await get_all_models()
  1098. if model.get("owned_by") != "arena" and model["id"] not in model_ids
  1099. ]
  1100. selected_model_id = None
  1101. if isinstance(model_ids, list) and model_ids:
  1102. selected_model_id = random.choice(model_ids)
  1103. else:
  1104. model_ids = [
  1105. model["id"]
  1106. for model in await get_all_models()
  1107. if model.get("owned_by") != "arena"
  1108. ]
  1109. selected_model_id = random.choice(model_ids)
  1110. form_data["model"] = selected_model_id
  1111. if form_data.get("stream") == True:
  1112. async def stream_wrapper(stream):
  1113. yield f"data: {json.dumps({'selected_model_id': selected_model_id})}\n\n"
  1114. async for chunk in stream:
  1115. yield chunk
  1116. response = await generate_chat_completions(
  1117. form_data, user, bypass_filter=True
  1118. )
  1119. return StreamingResponse(
  1120. stream_wrapper(response.body_iterator), media_type="text/event-stream"
  1121. )
  1122. else:
  1123. return {
  1124. **(
  1125. await generate_chat_completions(form_data, user, bypass_filter=True)
  1126. ),
  1127. "selected_model_id": selected_model_id,
  1128. }
  1129. if model.get("pipe"):
  1130. # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
  1131. return await generate_function_chat_completion(
  1132. form_data, user=user, models=models
  1133. )
  1134. if model["owned_by"] == "ollama":
  1135. # Using /ollama/api/chat endpoint
  1136. form_data = convert_payload_openai_to_ollama(form_data)
  1137. form_data = GenerateChatCompletionForm(**form_data)
  1138. response = await generate_ollama_chat_completion(
  1139. form_data=form_data, user=user, bypass_filter=bypass_filter
  1140. )
  1141. if form_data.stream:
  1142. response.headers["content-type"] = "text/event-stream"
  1143. return StreamingResponse(
  1144. convert_streaming_response_ollama_to_openai(response),
  1145. headers=dict(response.headers),
  1146. )
  1147. else:
  1148. return convert_response_ollama_to_openai(response)
  1149. else:
  1150. return await generate_openai_chat_completion(
  1151. form_data, user=user, bypass_filter=bypass_filter
  1152. )
  1153. @app.post("/api/chat/completed")
  1154. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  1155. model_list = await get_all_models()
  1156. models = {model["id"]: model for model in model_list}
  1157. data = form_data
  1158. model_id = data["model"]
  1159. if model_id not in models:
  1160. raise HTTPException(
  1161. status_code=status.HTTP_404_NOT_FOUND,
  1162. detail="Model not found",
  1163. )
  1164. model = models[model_id]
  1165. sorted_filters = get_sorted_filters(model_id, models)
  1166. if "pipeline" in model:
  1167. sorted_filters = [model] + sorted_filters
  1168. for filter in sorted_filters:
  1169. r = None
  1170. try:
  1171. urlIdx = filter["urlIdx"]
  1172. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1173. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1174. if key != "":
  1175. headers = {"Authorization": f"Bearer {key}"}
  1176. r = requests.post(
  1177. f"{url}/{filter['id']}/filter/outlet",
  1178. headers=headers,
  1179. json={
  1180. "user": {
  1181. "id": user.id,
  1182. "name": user.name,
  1183. "email": user.email,
  1184. "role": user.role,
  1185. },
  1186. "body": data,
  1187. },
  1188. )
  1189. r.raise_for_status()
  1190. data = r.json()
  1191. except Exception as e:
  1192. # Handle connection error here
  1193. print(f"Connection error: {e}")
  1194. if r is not None:
  1195. try:
  1196. res = r.json()
  1197. if "detail" in res:
  1198. return JSONResponse(
  1199. status_code=r.status_code,
  1200. content=res,
  1201. )
  1202. except Exception:
  1203. pass
  1204. else:
  1205. pass
  1206. __event_emitter__ = get_event_emitter(
  1207. {
  1208. "chat_id": data["chat_id"],
  1209. "message_id": data["id"],
  1210. "session_id": data["session_id"],
  1211. }
  1212. )
  1213. __event_call__ = get_event_call(
  1214. {
  1215. "chat_id": data["chat_id"],
  1216. "message_id": data["id"],
  1217. "session_id": data["session_id"],
  1218. }
  1219. )
  1220. def get_priority(function_id):
  1221. function = Functions.get_function_by_id(function_id)
  1222. if function is not None and hasattr(function, "valves"):
  1223. # TODO: Fix FunctionModel to include vavles
  1224. return (function.valves if function.valves else {}).get("priority", 0)
  1225. return 0
  1226. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  1227. if "info" in model and "meta" in model["info"]:
  1228. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  1229. filter_ids = list(set(filter_ids))
  1230. enabled_filter_ids = [
  1231. function.id
  1232. for function in Functions.get_functions_by_type("filter", active_only=True)
  1233. ]
  1234. filter_ids = [
  1235. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  1236. ]
  1237. # Sort filter_ids by priority, using the get_priority function
  1238. filter_ids.sort(key=get_priority)
  1239. for filter_id in filter_ids:
  1240. filter = Functions.get_function_by_id(filter_id)
  1241. if not filter:
  1242. continue
  1243. if filter_id in webui_app.state.FUNCTIONS:
  1244. function_module = webui_app.state.FUNCTIONS[filter_id]
  1245. else:
  1246. function_module, _, _ = load_function_module_by_id(filter_id)
  1247. webui_app.state.FUNCTIONS[filter_id] = function_module
  1248. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1249. valves = Functions.get_function_valves_by_id(filter_id)
  1250. function_module.valves = function_module.Valves(
  1251. **(valves if valves else {})
  1252. )
  1253. if not hasattr(function_module, "outlet"):
  1254. continue
  1255. try:
  1256. outlet = function_module.outlet
  1257. # Get the signature of the function
  1258. sig = inspect.signature(outlet)
  1259. params = {"body": data}
  1260. # Extra parameters to be passed to the function
  1261. extra_params = {
  1262. "__model__": model,
  1263. "__id__": filter_id,
  1264. "__event_emitter__": __event_emitter__,
  1265. "__event_call__": __event_call__,
  1266. }
  1267. # Add extra params in contained in function signature
  1268. for key, value in extra_params.items():
  1269. if key in sig.parameters:
  1270. params[key] = value
  1271. if "__user__" in sig.parameters:
  1272. __user__ = {
  1273. "id": user.id,
  1274. "email": user.email,
  1275. "name": user.name,
  1276. "role": user.role,
  1277. }
  1278. try:
  1279. if hasattr(function_module, "UserValves"):
  1280. __user__["valves"] = function_module.UserValves(
  1281. **Functions.get_user_valves_by_id_and_user_id(
  1282. filter_id, user.id
  1283. )
  1284. )
  1285. except Exception as e:
  1286. print(e)
  1287. params = {**params, "__user__": __user__}
  1288. if inspect.iscoroutinefunction(outlet):
  1289. data = await outlet(**params)
  1290. else:
  1291. data = outlet(**params)
  1292. except Exception as e:
  1293. print(f"Error: {e}")
  1294. return JSONResponse(
  1295. status_code=status.HTTP_400_BAD_REQUEST,
  1296. content={"detail": str(e)},
  1297. )
  1298. return data
  1299. @app.post("/api/chat/actions/{action_id}")
  1300. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1301. if "." in action_id:
  1302. action_id, sub_action_id = action_id.split(".")
  1303. else:
  1304. sub_action_id = None
  1305. action = Functions.get_function_by_id(action_id)
  1306. if not action:
  1307. raise HTTPException(
  1308. status_code=status.HTTP_404_NOT_FOUND,
  1309. detail="Action not found",
  1310. )
  1311. model_list = await get_all_models()
  1312. models = {model["id"]: model for model in model_list}
  1313. data = form_data
  1314. model_id = data["model"]
  1315. if model_id not in models:
  1316. raise HTTPException(
  1317. status_code=status.HTTP_404_NOT_FOUND,
  1318. detail="Model not found",
  1319. )
  1320. model = models[model_id]
  1321. __event_emitter__ = get_event_emitter(
  1322. {
  1323. "chat_id": data["chat_id"],
  1324. "message_id": data["id"],
  1325. "session_id": data["session_id"],
  1326. }
  1327. )
  1328. __event_call__ = get_event_call(
  1329. {
  1330. "chat_id": data["chat_id"],
  1331. "message_id": data["id"],
  1332. "session_id": data["session_id"],
  1333. }
  1334. )
  1335. if action_id in webui_app.state.FUNCTIONS:
  1336. function_module = webui_app.state.FUNCTIONS[action_id]
  1337. else:
  1338. function_module, _, _ = load_function_module_by_id(action_id)
  1339. webui_app.state.FUNCTIONS[action_id] = function_module
  1340. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1341. valves = Functions.get_function_valves_by_id(action_id)
  1342. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1343. if hasattr(function_module, "action"):
  1344. try:
  1345. action = function_module.action
  1346. # Get the signature of the function
  1347. sig = inspect.signature(action)
  1348. params = {"body": data}
  1349. # Extra parameters to be passed to the function
  1350. extra_params = {
  1351. "__model__": model,
  1352. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1353. "__event_emitter__": __event_emitter__,
  1354. "__event_call__": __event_call__,
  1355. }
  1356. # Add extra params in contained in function signature
  1357. for key, value in extra_params.items():
  1358. if key in sig.parameters:
  1359. params[key] = value
  1360. if "__user__" in sig.parameters:
  1361. __user__ = {
  1362. "id": user.id,
  1363. "email": user.email,
  1364. "name": user.name,
  1365. "role": user.role,
  1366. }
  1367. try:
  1368. if hasattr(function_module, "UserValves"):
  1369. __user__["valves"] = function_module.UserValves(
  1370. **Functions.get_user_valves_by_id_and_user_id(
  1371. action_id, user.id
  1372. )
  1373. )
  1374. except Exception as e:
  1375. print(e)
  1376. params = {**params, "__user__": __user__}
  1377. if inspect.iscoroutinefunction(action):
  1378. data = await action(**params)
  1379. else:
  1380. data = action(**params)
  1381. except Exception as e:
  1382. print(f"Error: {e}")
  1383. return JSONResponse(
  1384. status_code=status.HTTP_400_BAD_REQUEST,
  1385. content={"detail": str(e)},
  1386. )
  1387. return data
  1388. ##################################
  1389. #
  1390. # Task Endpoints
  1391. #
  1392. ##################################
  1393. # TODO: Refactor task API endpoints below into a separate file
  1394. @app.get("/api/task/config")
  1395. async def get_task_config(user=Depends(get_verified_user)):
  1396. return {
  1397. "TASK_MODEL": app.state.config.TASK_MODEL,
  1398. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1399. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1400. "ENABLE_AUTOCOMPLETE_GENERATION": app.state.config.ENABLE_AUTOCOMPLETE_GENERATION,
  1401. "AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH": app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH,
  1402. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1403. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1404. "ENABLE_SEARCH_QUERY_GENERATION": app.state.config.ENABLE_SEARCH_QUERY_GENERATION,
  1405. "ENABLE_RETRIEVAL_QUERY_GENERATION": app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION,
  1406. "QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE,
  1407. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1408. }
  1409. class TaskConfigForm(BaseModel):
  1410. TASK_MODEL: Optional[str]
  1411. TASK_MODEL_EXTERNAL: Optional[str]
  1412. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1413. ENABLE_AUTOCOMPLETE_GENERATION: bool
  1414. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH: int
  1415. TAGS_GENERATION_PROMPT_TEMPLATE: str
  1416. ENABLE_TAGS_GENERATION: bool
  1417. ENABLE_SEARCH_QUERY_GENERATION: bool
  1418. ENABLE_RETRIEVAL_QUERY_GENERATION: bool
  1419. QUERY_GENERATION_PROMPT_TEMPLATE: str
  1420. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1421. @app.post("/api/task/config/update")
  1422. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1423. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1424. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1425. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1426. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1427. )
  1428. app.state.config.ENABLE_AUTOCOMPLETE_GENERATION = (
  1429. form_data.ENABLE_AUTOCOMPLETE_GENERATION
  1430. )
  1431. app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = (
  1432. form_data.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH
  1433. )
  1434. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = (
  1435. form_data.TAGS_GENERATION_PROMPT_TEMPLATE
  1436. )
  1437. app.state.config.ENABLE_TAGS_GENERATION = form_data.ENABLE_TAGS_GENERATION
  1438. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = (
  1439. form_data.ENABLE_SEARCH_QUERY_GENERATION
  1440. )
  1441. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = (
  1442. form_data.ENABLE_RETRIEVAL_QUERY_GENERATION
  1443. )
  1444. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = (
  1445. form_data.QUERY_GENERATION_PROMPT_TEMPLATE
  1446. )
  1447. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1448. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1449. )
  1450. return {
  1451. "TASK_MODEL": app.state.config.TASK_MODEL,
  1452. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1453. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1454. "ENABLE_AUTOCOMPLETE_GENERATION": app.state.config.ENABLE_AUTOCOMPLETE_GENERATION,
  1455. "AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH": app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH,
  1456. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1457. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1458. "ENABLE_SEARCH_QUERY_GENERATION": app.state.config.ENABLE_SEARCH_QUERY_GENERATION,
  1459. "ENABLE_RETRIEVAL_QUERY_GENERATION": app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION,
  1460. "QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE,
  1461. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1462. }
  1463. @app.post("/api/task/title/completions")
  1464. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1465. model_list = await get_all_models()
  1466. models = {model["id"]: model for model in model_list}
  1467. model_id = form_data["model"]
  1468. if model_id not in models:
  1469. raise HTTPException(
  1470. status_code=status.HTTP_404_NOT_FOUND,
  1471. detail="Model not found",
  1472. )
  1473. # Check if the user has a custom task model
  1474. # If the user has a custom task model, use that model
  1475. task_model_id = get_task_model_id(
  1476. model_id,
  1477. app.state.config.TASK_MODEL,
  1478. app.state.config.TASK_MODEL_EXTERNAL,
  1479. models,
  1480. )
  1481. log.debug(
  1482. f"generating chat title using model {task_model_id} for user {user.email} "
  1483. )
  1484. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1485. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1486. else:
  1487. template = """Create a concise, 3-5 word title with an emoji as a title for the chat history, 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.
  1488. Examples of titles:
  1489. 📉 Stock Market Trends
  1490. 🍪 Perfect Chocolate Chip Recipe
  1491. Evolution of Music Streaming
  1492. Remote Work Productivity Tips
  1493. Artificial Intelligence in Healthcare
  1494. 🎮 Video Game Development Insights
  1495. <chat_history>
  1496. {{MESSAGES:END:2}}
  1497. </chat_history>"""
  1498. content = title_generation_template(
  1499. template,
  1500. form_data["messages"],
  1501. {
  1502. "name": user.name,
  1503. "location": user.info.get("location") if user.info else None,
  1504. },
  1505. )
  1506. payload = {
  1507. "model": task_model_id,
  1508. "messages": [{"role": "user", "content": content}],
  1509. "stream": False,
  1510. **(
  1511. {"max_tokens": 50}
  1512. if models[task_model_id]["owned_by"] == "ollama"
  1513. else {
  1514. "max_completion_tokens": 50,
  1515. }
  1516. ),
  1517. "metadata": {
  1518. "task": str(TASKS.TITLE_GENERATION),
  1519. "task_body": form_data,
  1520. "chat_id": form_data.get("chat_id", None),
  1521. },
  1522. }
  1523. # Handle pipeline filters
  1524. try:
  1525. payload = filter_pipeline(payload, user, models)
  1526. except Exception as e:
  1527. if len(e.args) > 1:
  1528. return JSONResponse(
  1529. status_code=e.args[0],
  1530. content={"detail": e.args[1]},
  1531. )
  1532. else:
  1533. return JSONResponse(
  1534. status_code=status.HTTP_400_BAD_REQUEST,
  1535. content={"detail": str(e)},
  1536. )
  1537. if "chat_id" in payload:
  1538. del payload["chat_id"]
  1539. return await generate_chat_completions(form_data=payload, user=user)
  1540. @app.post("/api/task/tags/completions")
  1541. async def generate_chat_tags(form_data: dict, user=Depends(get_verified_user)):
  1542. if not app.state.config.ENABLE_TAGS_GENERATION:
  1543. return JSONResponse(
  1544. status_code=status.HTTP_200_OK,
  1545. content={"detail": "Tags generation is disabled"},
  1546. )
  1547. model_list = await get_all_models()
  1548. models = {model["id"]: model for model in model_list}
  1549. model_id = form_data["model"]
  1550. if model_id not in models:
  1551. raise HTTPException(
  1552. status_code=status.HTTP_404_NOT_FOUND,
  1553. detail="Model not found",
  1554. )
  1555. # Check if the user has a custom task model
  1556. # If the user has a custom task model, use that model
  1557. task_model_id = get_task_model_id(
  1558. model_id,
  1559. app.state.config.TASK_MODEL,
  1560. app.state.config.TASK_MODEL_EXTERNAL,
  1561. models,
  1562. )
  1563. log.debug(
  1564. f"generating chat tags using model {task_model_id} for user {user.email} "
  1565. )
  1566. if app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE != "":
  1567. template = app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE
  1568. else:
  1569. template = """### Task:
  1570. Generate 1-3 broad tags categorizing the main themes of the chat history, along with 1-3 more specific subtopic tags.
  1571. ### Guidelines:
  1572. - Start with high-level domains (e.g. Science, Technology, Philosophy, Arts, Politics, Business, Health, Sports, Entertainment, Education)
  1573. - Consider including relevant subfields/subdomains if they are strongly represented throughout the conversation
  1574. - If content is too short (less than 3 messages) or too diverse, use only ["General"]
  1575. - Use the chat's primary language; default to English if multilingual
  1576. - Prioritize accuracy over specificity
  1577. ### Output:
  1578. JSON format: { "tags": ["tag1", "tag2", "tag3"] }
  1579. ### Chat History:
  1580. <chat_history>
  1581. {{MESSAGES:END:6}}
  1582. </chat_history>"""
  1583. content = tags_generation_template(
  1584. template, form_data["messages"], {"name": user.name}
  1585. )
  1586. payload = {
  1587. "model": task_model_id,
  1588. "messages": [{"role": "user", "content": content}],
  1589. "stream": False,
  1590. "metadata": {
  1591. "task": str(TASKS.TAGS_GENERATION),
  1592. "task_body": form_data,
  1593. "chat_id": form_data.get("chat_id", None),
  1594. },
  1595. }
  1596. # Handle pipeline filters
  1597. try:
  1598. payload = filter_pipeline(payload, user, models)
  1599. except Exception as e:
  1600. if len(e.args) > 1:
  1601. return JSONResponse(
  1602. status_code=e.args[0],
  1603. content={"detail": e.args[1]},
  1604. )
  1605. else:
  1606. return JSONResponse(
  1607. status_code=status.HTTP_400_BAD_REQUEST,
  1608. content={"detail": str(e)},
  1609. )
  1610. if "chat_id" in payload:
  1611. del payload["chat_id"]
  1612. return await generate_chat_completions(form_data=payload, user=user)
  1613. @app.post("/api/task/queries/completions")
  1614. async def generate_queries(form_data: dict, user=Depends(get_verified_user)):
  1615. type = form_data.get("type")
  1616. if type == "web_search":
  1617. if not app.state.config.ENABLE_SEARCH_QUERY_GENERATION:
  1618. raise HTTPException(
  1619. status_code=status.HTTP_400_BAD_REQUEST,
  1620. detail=f"Search query generation is disabled",
  1621. )
  1622. elif type == "retrieval":
  1623. if not app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION:
  1624. raise HTTPException(
  1625. status_code=status.HTTP_400_BAD_REQUEST,
  1626. detail=f"Query generation is disabled",
  1627. )
  1628. model_list = await get_all_models()
  1629. models = {model["id"]: model for model in model_list}
  1630. model_id = form_data["model"]
  1631. if model_id not in models:
  1632. raise HTTPException(
  1633. status_code=status.HTTP_404_NOT_FOUND,
  1634. detail="Model not found",
  1635. )
  1636. # Check if the user has a custom task model
  1637. # If the user has a custom task model, use that model
  1638. task_model_id = get_task_model_id(
  1639. model_id,
  1640. app.state.config.TASK_MODEL,
  1641. app.state.config.TASK_MODEL_EXTERNAL,
  1642. models,
  1643. )
  1644. log.debug(
  1645. f"generating {type} queries using model {task_model_id} for user {user.email}"
  1646. )
  1647. if (app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE).strip() != "":
  1648. template = app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE
  1649. else:
  1650. template = DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE
  1651. content = query_generation_template(
  1652. template, form_data["messages"], {"name": user.name}
  1653. )
  1654. payload = {
  1655. "model": task_model_id,
  1656. "messages": [{"role": "user", "content": content}],
  1657. "stream": False,
  1658. "metadata": {
  1659. "task": str(TASKS.QUERY_GENERATION),
  1660. "task_body": form_data,
  1661. "chat_id": form_data.get("chat_id", None),
  1662. },
  1663. }
  1664. # Handle pipeline filters
  1665. try:
  1666. payload = filter_pipeline(payload, user, models)
  1667. except Exception as e:
  1668. if len(e.args) > 1:
  1669. return JSONResponse(
  1670. status_code=e.args[0],
  1671. content={"detail": e.args[1]},
  1672. )
  1673. else:
  1674. return JSONResponse(
  1675. status_code=status.HTTP_400_BAD_REQUEST,
  1676. content={"detail": str(e)},
  1677. )
  1678. if "chat_id" in payload:
  1679. del payload["chat_id"]
  1680. return await generate_chat_completions(form_data=payload, user=user)
  1681. @app.post("/api/task/auto/completions")
  1682. async def generate_autocompletion(form_data: dict, user=Depends(get_verified_user)):
  1683. if not app.state.config.ENABLE_AUTOCOMPLETE_GENERATION:
  1684. raise HTTPException(
  1685. status_code=status.HTTP_400_BAD_REQUEST,
  1686. detail=f"Autocompletion generation is disabled",
  1687. )
  1688. type = form_data.get("type")
  1689. prompt = form_data.get("prompt")
  1690. messages = form_data.get("messages")
  1691. if app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH > 0:
  1692. if len(prompt) > app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH:
  1693. raise HTTPException(
  1694. status_code=status.HTTP_400_BAD_REQUEST,
  1695. detail=f"Input prompt exceeds maximum length of {app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH}",
  1696. )
  1697. model_list = await get_all_models()
  1698. models = {model["id"]: model for model in model_list}
  1699. model_id = form_data["model"]
  1700. if model_id not in models:
  1701. raise HTTPException(
  1702. status_code=status.HTTP_404_NOT_FOUND,
  1703. detail="Model not found",
  1704. )
  1705. # Check if the user has a custom task model
  1706. # If the user has a custom task model, use that model
  1707. task_model_id = get_task_model_id(
  1708. model_id,
  1709. app.state.config.TASK_MODEL,
  1710. app.state.config.TASK_MODEL_EXTERNAL,
  1711. models,
  1712. )
  1713. log.debug(
  1714. f"generating autocompletion using model {task_model_id} for user {user.email}"
  1715. )
  1716. if (app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE).strip() != "":
  1717. template = app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  1718. else:
  1719. template = DEFAULT_AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  1720. content = autocomplete_generation_template(
  1721. template, prompt, messages, type, {"name": user.name}
  1722. )
  1723. payload = {
  1724. "model": task_model_id,
  1725. "messages": [{"role": "user", "content": content}],
  1726. "stream": False,
  1727. "metadata": {
  1728. "task": str(TASKS.AUTOCOMPLETE_GENERATION),
  1729. "task_body": form_data,
  1730. "chat_id": form_data.get("chat_id", None),
  1731. },
  1732. }
  1733. print(payload)
  1734. # Handle pipeline filters
  1735. try:
  1736. payload = filter_pipeline(payload, user, models)
  1737. except Exception as e:
  1738. if len(e.args) > 1:
  1739. return JSONResponse(
  1740. status_code=e.args[0],
  1741. content={"detail": e.args[1]},
  1742. )
  1743. else:
  1744. return JSONResponse(
  1745. status_code=status.HTTP_400_BAD_REQUEST,
  1746. content={"detail": str(e)},
  1747. )
  1748. if "chat_id" in payload:
  1749. del payload["chat_id"]
  1750. return await generate_chat_completions(form_data=payload, user=user)
  1751. @app.post("/api/task/emoji/completions")
  1752. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1753. model_list = await get_all_models()
  1754. models = {model["id"]: model for model in model_list}
  1755. model_id = form_data["model"]
  1756. if model_id not in models:
  1757. raise HTTPException(
  1758. status_code=status.HTTP_404_NOT_FOUND,
  1759. detail="Model not found",
  1760. )
  1761. # Check if the user has a custom task model
  1762. # If the user has a custom task model, use that model
  1763. task_model_id = get_task_model_id(
  1764. model_id,
  1765. app.state.config.TASK_MODEL,
  1766. app.state.config.TASK_MODEL_EXTERNAL,
  1767. models,
  1768. )
  1769. log.debug(f"generating emoji using model {task_model_id} for user {user.email} ")
  1770. template = '''
  1771. 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., 😊, 😢, 😡, 😱).
  1772. Message: """{{prompt}}"""
  1773. '''
  1774. content = emoji_generation_template(
  1775. template,
  1776. form_data["prompt"],
  1777. {
  1778. "name": user.name,
  1779. "location": user.info.get("location") if user.info else None,
  1780. },
  1781. )
  1782. payload = {
  1783. "model": task_model_id,
  1784. "messages": [{"role": "user", "content": content}],
  1785. "stream": False,
  1786. **(
  1787. {"max_tokens": 4}
  1788. if models[task_model_id]["owned_by"] == "ollama"
  1789. else {
  1790. "max_completion_tokens": 4,
  1791. }
  1792. ),
  1793. "chat_id": form_data.get("chat_id", None),
  1794. "metadata": {"task": str(TASKS.EMOJI_GENERATION), "task_body": form_data},
  1795. }
  1796. # Handle pipeline filters
  1797. try:
  1798. payload = filter_pipeline(payload, user, models)
  1799. except Exception as e:
  1800. if len(e.args) > 1:
  1801. return JSONResponse(
  1802. status_code=e.args[0],
  1803. content={"detail": e.args[1]},
  1804. )
  1805. else:
  1806. return JSONResponse(
  1807. status_code=status.HTTP_400_BAD_REQUEST,
  1808. content={"detail": str(e)},
  1809. )
  1810. if "chat_id" in payload:
  1811. del payload["chat_id"]
  1812. return await generate_chat_completions(form_data=payload, user=user)
  1813. @app.post("/api/task/moa/completions")
  1814. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1815. model_list = await get_all_models()
  1816. models = {model["id"]: model for model in model_list}
  1817. model_id = form_data["model"]
  1818. if model_id not in models:
  1819. raise HTTPException(
  1820. status_code=status.HTTP_404_NOT_FOUND,
  1821. detail="Model not found",
  1822. )
  1823. # Check if the user has a custom task model
  1824. # If the user has a custom task model, use that model
  1825. task_model_id = get_task_model_id(
  1826. model_id,
  1827. app.state.config.TASK_MODEL,
  1828. app.state.config.TASK_MODEL_EXTERNAL,
  1829. models,
  1830. )
  1831. log.debug(f"generating MOA model {task_model_id} for user {user.email} ")
  1832. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1833. 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.
  1834. Responses from models: {{responses}}"""
  1835. content = moa_response_generation_template(
  1836. template,
  1837. form_data["prompt"],
  1838. form_data["responses"],
  1839. )
  1840. payload = {
  1841. "model": task_model_id,
  1842. "messages": [{"role": "user", "content": content}],
  1843. "stream": form_data.get("stream", False),
  1844. "chat_id": form_data.get("chat_id", None),
  1845. "metadata": {
  1846. "task": str(TASKS.MOA_RESPONSE_GENERATION),
  1847. "task_body": form_data,
  1848. },
  1849. }
  1850. try:
  1851. payload = filter_pipeline(payload, user, models)
  1852. except Exception as e:
  1853. if len(e.args) > 1:
  1854. return JSONResponse(
  1855. status_code=e.args[0],
  1856. content={"detail": e.args[1]},
  1857. )
  1858. else:
  1859. return JSONResponse(
  1860. status_code=status.HTTP_400_BAD_REQUEST,
  1861. content={"detail": str(e)},
  1862. )
  1863. if "chat_id" in payload:
  1864. del payload["chat_id"]
  1865. return await generate_chat_completions(form_data=payload, user=user)
  1866. ##################################
  1867. #
  1868. # Pipelines Endpoints
  1869. #
  1870. ##################################
  1871. # TODO: Refactor pipelines API endpoints below into a separate file
  1872. @app.get("/api/pipelines/list")
  1873. async def get_pipelines_list(user=Depends(get_admin_user)):
  1874. responses = await get_openai_models_responses()
  1875. log.debug(f"get_pipelines_list: get_openai_models_responses returned {responses}")
  1876. urlIdxs = [
  1877. idx
  1878. for idx, response in enumerate(responses)
  1879. if response is not None and "pipelines" in response
  1880. ]
  1881. return {
  1882. "data": [
  1883. {
  1884. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1885. "idx": urlIdx,
  1886. }
  1887. for urlIdx in urlIdxs
  1888. ]
  1889. }
  1890. @app.post("/api/pipelines/upload")
  1891. async def upload_pipeline(
  1892. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1893. ):
  1894. print("upload_pipeline", urlIdx, file.filename)
  1895. # Check if the uploaded file is a python file
  1896. if not (file.filename and file.filename.endswith(".py")):
  1897. raise HTTPException(
  1898. status_code=status.HTTP_400_BAD_REQUEST,
  1899. detail="Only Python (.py) files are allowed.",
  1900. )
  1901. upload_folder = f"{CACHE_DIR}/pipelines"
  1902. os.makedirs(upload_folder, exist_ok=True)
  1903. file_path = os.path.join(upload_folder, file.filename)
  1904. r = None
  1905. try:
  1906. # Save the uploaded file
  1907. with open(file_path, "wb") as buffer:
  1908. shutil.copyfileobj(file.file, buffer)
  1909. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1910. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1911. headers = {"Authorization": f"Bearer {key}"}
  1912. with open(file_path, "rb") as f:
  1913. files = {"file": f}
  1914. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1915. r.raise_for_status()
  1916. data = r.json()
  1917. return {**data}
  1918. except Exception as e:
  1919. # Handle connection error here
  1920. print(f"Connection error: {e}")
  1921. detail = "Pipeline not found"
  1922. status_code = status.HTTP_404_NOT_FOUND
  1923. if r is not None:
  1924. status_code = r.status_code
  1925. try:
  1926. res = r.json()
  1927. if "detail" in res:
  1928. detail = res["detail"]
  1929. except Exception:
  1930. pass
  1931. raise HTTPException(
  1932. status_code=status_code,
  1933. detail=detail,
  1934. )
  1935. finally:
  1936. # Ensure the file is deleted after the upload is completed or on failure
  1937. if os.path.exists(file_path):
  1938. os.remove(file_path)
  1939. class AddPipelineForm(BaseModel):
  1940. url: str
  1941. urlIdx: int
  1942. @app.post("/api/pipelines/add")
  1943. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1944. r = None
  1945. try:
  1946. urlIdx = form_data.urlIdx
  1947. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1948. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1949. headers = {"Authorization": f"Bearer {key}"}
  1950. r = requests.post(
  1951. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1952. )
  1953. r.raise_for_status()
  1954. data = r.json()
  1955. return {**data}
  1956. except Exception as e:
  1957. # Handle connection error here
  1958. print(f"Connection error: {e}")
  1959. detail = "Pipeline not found"
  1960. if r is not None:
  1961. try:
  1962. res = r.json()
  1963. if "detail" in res:
  1964. detail = res["detail"]
  1965. except Exception:
  1966. pass
  1967. raise HTTPException(
  1968. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1969. detail=detail,
  1970. )
  1971. class DeletePipelineForm(BaseModel):
  1972. id: str
  1973. urlIdx: int
  1974. @app.delete("/api/pipelines/delete")
  1975. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1976. r = None
  1977. try:
  1978. urlIdx = form_data.urlIdx
  1979. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1980. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1981. headers = {"Authorization": f"Bearer {key}"}
  1982. r = requests.delete(
  1983. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1984. )
  1985. r.raise_for_status()
  1986. data = r.json()
  1987. return {**data}
  1988. except Exception as e:
  1989. # Handle connection error here
  1990. print(f"Connection error: {e}")
  1991. detail = "Pipeline not found"
  1992. if r is not None:
  1993. try:
  1994. res = r.json()
  1995. if "detail" in res:
  1996. detail = res["detail"]
  1997. except Exception:
  1998. pass
  1999. raise HTTPException(
  2000. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2001. detail=detail,
  2002. )
  2003. @app.get("/api/pipelines")
  2004. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  2005. r = None
  2006. try:
  2007. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  2008. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  2009. headers = {"Authorization": f"Bearer {key}"}
  2010. r = requests.get(f"{url}/pipelines", headers=headers)
  2011. r.raise_for_status()
  2012. data = r.json()
  2013. return {**data}
  2014. except Exception as e:
  2015. # Handle connection error here
  2016. print(f"Connection error: {e}")
  2017. detail = "Pipeline not found"
  2018. if r is not None:
  2019. try:
  2020. res = r.json()
  2021. if "detail" in res:
  2022. detail = res["detail"]
  2023. except Exception:
  2024. pass
  2025. raise HTTPException(
  2026. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2027. detail=detail,
  2028. )
  2029. @app.get("/api/pipelines/{pipeline_id}/valves")
  2030. async def get_pipeline_valves(
  2031. urlIdx: Optional[int],
  2032. pipeline_id: str,
  2033. user=Depends(get_admin_user),
  2034. ):
  2035. r = None
  2036. try:
  2037. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  2038. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  2039. headers = {"Authorization": f"Bearer {key}"}
  2040. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  2041. r.raise_for_status()
  2042. data = r.json()
  2043. return {**data}
  2044. except Exception as e:
  2045. # Handle connection error here
  2046. print(f"Connection error: {e}")
  2047. detail = "Pipeline not found"
  2048. if r is not None:
  2049. try:
  2050. res = r.json()
  2051. if "detail" in res:
  2052. detail = res["detail"]
  2053. except Exception:
  2054. pass
  2055. raise HTTPException(
  2056. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2057. detail=detail,
  2058. )
  2059. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  2060. async def get_pipeline_valves_spec(
  2061. urlIdx: Optional[int],
  2062. pipeline_id: str,
  2063. user=Depends(get_admin_user),
  2064. ):
  2065. r = None
  2066. try:
  2067. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  2068. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  2069. headers = {"Authorization": f"Bearer {key}"}
  2070. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  2071. r.raise_for_status()
  2072. data = r.json()
  2073. return {**data}
  2074. except Exception as e:
  2075. # Handle connection error here
  2076. print(f"Connection error: {e}")
  2077. detail = "Pipeline not found"
  2078. if r is not None:
  2079. try:
  2080. res = r.json()
  2081. if "detail" in res:
  2082. detail = res["detail"]
  2083. except Exception:
  2084. pass
  2085. raise HTTPException(
  2086. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2087. detail=detail,
  2088. )
  2089. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  2090. async def update_pipeline_valves(
  2091. urlIdx: Optional[int],
  2092. pipeline_id: str,
  2093. form_data: dict,
  2094. user=Depends(get_admin_user),
  2095. ):
  2096. r = None
  2097. try:
  2098. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  2099. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  2100. headers = {"Authorization": f"Bearer {key}"}
  2101. r = requests.post(
  2102. f"{url}/{pipeline_id}/valves/update",
  2103. headers=headers,
  2104. json={**form_data},
  2105. )
  2106. r.raise_for_status()
  2107. data = r.json()
  2108. return {**data}
  2109. except Exception as e:
  2110. # Handle connection error here
  2111. print(f"Connection error: {e}")
  2112. detail = "Pipeline not found"
  2113. if r is not None:
  2114. try:
  2115. res = r.json()
  2116. if "detail" in res:
  2117. detail = res["detail"]
  2118. except Exception:
  2119. pass
  2120. raise HTTPException(
  2121. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2122. detail=detail,
  2123. )
  2124. ##################################
  2125. #
  2126. # Config Endpoints
  2127. #
  2128. ##################################
  2129. @app.get("/api/config")
  2130. async def get_app_config(request: Request):
  2131. user = None
  2132. if "token" in request.cookies:
  2133. token = request.cookies.get("token")
  2134. try:
  2135. data = decode_token(token)
  2136. except Exception as e:
  2137. log.debug(e)
  2138. raise HTTPException(
  2139. status_code=status.HTTP_401_UNAUTHORIZED,
  2140. detail="Invalid token",
  2141. )
  2142. if data is not None and "id" in data:
  2143. user = Users.get_user_by_id(data["id"])
  2144. onboarding = False
  2145. if user is None:
  2146. user_count = Users.get_num_users()
  2147. onboarding = user_count == 0
  2148. return {
  2149. **({"onboarding": True} if onboarding else {}),
  2150. "status": True,
  2151. "name": WEBUI_NAME,
  2152. "version": VERSION,
  2153. "default_locale": str(DEFAULT_LOCALE),
  2154. "oauth": {
  2155. "providers": {
  2156. name: config.get("name", name)
  2157. for name, config in OAUTH_PROVIDERS.items()
  2158. }
  2159. },
  2160. "features": {
  2161. "auth": WEBUI_AUTH,
  2162. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  2163. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  2164. "enable_api_key": webui_app.state.config.ENABLE_API_KEY,
  2165. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  2166. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  2167. **(
  2168. {
  2169. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  2170. "enable_image_generation": images_app.state.config.ENABLED,
  2171. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  2172. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  2173. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  2174. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  2175. }
  2176. if user is not None
  2177. else {}
  2178. ),
  2179. },
  2180. **(
  2181. {
  2182. "default_models": webui_app.state.config.DEFAULT_MODELS,
  2183. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  2184. "audio": {
  2185. "tts": {
  2186. "engine": audio_app.state.config.TTS_ENGINE,
  2187. "voice": audio_app.state.config.TTS_VOICE,
  2188. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  2189. },
  2190. "stt": {
  2191. "engine": audio_app.state.config.STT_ENGINE,
  2192. },
  2193. },
  2194. "file": {
  2195. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  2196. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  2197. },
  2198. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  2199. }
  2200. if user is not None
  2201. else {}
  2202. ),
  2203. }
  2204. # TODO: webhook endpoint should be under config endpoints
  2205. @app.get("/api/webhook")
  2206. async def get_webhook_url(user=Depends(get_admin_user)):
  2207. return {
  2208. "url": app.state.config.WEBHOOK_URL,
  2209. }
  2210. class UrlForm(BaseModel):
  2211. url: str
  2212. @app.post("/api/webhook")
  2213. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  2214. app.state.config.WEBHOOK_URL = form_data.url
  2215. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  2216. return {"url": app.state.config.WEBHOOK_URL}
  2217. @app.get("/api/version")
  2218. async def get_app_version():
  2219. return {
  2220. "version": VERSION,
  2221. }
  2222. @app.get("/api/changelog")
  2223. async def get_app_changelog():
  2224. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  2225. @app.get("/api/version/updates")
  2226. async def get_app_latest_release_version():
  2227. if OFFLINE_MODE:
  2228. log.debug(
  2229. f"Offline mode is enabled, returning current version as latest version"
  2230. )
  2231. return {"current": VERSION, "latest": VERSION}
  2232. try:
  2233. timeout = aiohttp.ClientTimeout(total=1)
  2234. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  2235. async with session.get(
  2236. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  2237. ) as response:
  2238. response.raise_for_status()
  2239. data = await response.json()
  2240. latest_version = data["tag_name"]
  2241. return {"current": VERSION, "latest": latest_version[1:]}
  2242. except Exception as e:
  2243. log.debug(e)
  2244. return {"current": VERSION, "latest": VERSION}
  2245. ############################
  2246. # OAuth Login & Callback
  2247. ############################
  2248. # SessionMiddleware is used by authlib for oauth
  2249. if len(OAUTH_PROVIDERS) > 0:
  2250. app.add_middleware(
  2251. SessionMiddleware,
  2252. secret_key=WEBUI_SECRET_KEY,
  2253. session_cookie="oui-session",
  2254. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  2255. https_only=WEBUI_SESSION_COOKIE_SECURE,
  2256. )
  2257. @app.get("/oauth/{provider}/login")
  2258. async def oauth_login(provider: str, request: Request):
  2259. return await oauth_manager.handle_login(provider, request)
  2260. # OAuth login logic is as follows:
  2261. # 1. Attempt to find a user with matching subject ID, tied to the provider
  2262. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  2263. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  2264. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  2265. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  2266. @app.get("/oauth/{provider}/callback")
  2267. async def oauth_callback(provider: str, request: Request, response: Response):
  2268. return await oauth_manager.handle_callback(provider, request, response)
  2269. @app.get("/manifest.json")
  2270. async def get_manifest_json():
  2271. return {
  2272. "name": WEBUI_NAME,
  2273. "short_name": WEBUI_NAME,
  2274. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  2275. "start_url": "/",
  2276. "display": "standalone",
  2277. "background_color": "#343541",
  2278. "orientation": "natural",
  2279. "icons": [
  2280. {
  2281. "src": "/static/logo.png",
  2282. "type": "image/png",
  2283. "sizes": "500x500",
  2284. "purpose": "any",
  2285. },
  2286. {
  2287. "src": "/static/logo.png",
  2288. "type": "image/png",
  2289. "sizes": "500x500",
  2290. "purpose": "maskable",
  2291. },
  2292. ],
  2293. }
  2294. @app.get("/opensearch.xml")
  2295. async def get_opensearch_xml():
  2296. xml_content = rf"""
  2297. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  2298. <ShortName>{WEBUI_NAME}</ShortName>
  2299. <Description>Search {WEBUI_NAME}</Description>
  2300. <InputEncoding>UTF-8</InputEncoding>
  2301. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  2302. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  2303. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  2304. </OpenSearchDescription>
  2305. """
  2306. return Response(content=xml_content, media_type="application/xml")
  2307. @app.get("/health")
  2308. async def healthcheck():
  2309. return {"status": True}
  2310. @app.get("/health/db")
  2311. async def healthcheck_with_db():
  2312. Session.execute(text("SELECT 1;")).all()
  2313. return {"status": True}
  2314. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  2315. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  2316. if os.path.exists(FRONTEND_BUILD_DIR):
  2317. mimetypes.add_type("text/javascript", ".js")
  2318. app.mount(
  2319. "/",
  2320. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  2321. name="spa-static-files",
  2322. )
  2323. else:
  2324. log.warning(
  2325. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  2326. )