main.py 79 KB

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