main.py 79 KB

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