main.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428
  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. )
  94. from fastapi import (
  95. Depends,
  96. FastAPI,
  97. File,
  98. Form,
  99. HTTPException,
  100. Request,
  101. UploadFile,
  102. status,
  103. )
  104. from fastapi.middleware.cors import CORSMiddleware
  105. from fastapi.responses import JSONResponse
  106. from fastapi.staticfiles import StaticFiles
  107. from pydantic import BaseModel
  108. from sqlalchemy import text
  109. from starlette.exceptions import HTTPException as StarletteHTTPException
  110. from starlette.middleware.base import BaseHTTPMiddleware
  111. from starlette.middleware.sessions import SessionMiddleware
  112. from starlette.responses import RedirectResponse, Response, StreamingResponse
  113. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  114. from open_webui.utils.misc import (
  115. add_or_update_system_message,
  116. get_last_user_message,
  117. parse_duration,
  118. prepend_to_first_user_message_content,
  119. )
  120. from open_webui.utils.task import (
  121. moa_response_generation_template,
  122. search_query_generation_template,
  123. title_generation_template,
  124. tools_function_calling_generation_template,
  125. )
  126. from open_webui.utils.tools import get_tools
  127. from open_webui.utils.utils import (
  128. create_token,
  129. decode_token,
  130. get_admin_user,
  131. get_current_user,
  132. get_http_authorization_cred,
  133. get_password_hash,
  134. get_verified_user,
  135. )
  136. from open_webui.utils.webhook import post_webhook
  137. from open_webui.utils.payload import convert_payload_openai_to_ollama
  138. from open_webui.utils.response import (
  139. convert_response_ollama_to_openai,
  140. convert_streaming_response_ollama_to_openai,
  141. )
  142. if SAFE_MODE:
  143. print("SAFE MODE ENABLED")
  144. Functions.deactivate_all_functions()
  145. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  146. log = logging.getLogger(__name__)
  147. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  148. class SPAStaticFiles(StaticFiles):
  149. async def get_response(self, path: str, scope):
  150. try:
  151. return await super().get_response(path, scope)
  152. except (HTTPException, StarletteHTTPException) as ex:
  153. if ex.status_code == 404:
  154. return await super().get_response("index.html", scope)
  155. else:
  156. raise ex
  157. print(
  158. rf"""
  159. ___ __ __ _ _ _ ___
  160. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  161. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  162. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  163. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  164. |_|
  165. v{VERSION} - building the best open-source AI user interface.
  166. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  167. https://github.com/open-webui/open-webui
  168. """
  169. )
  170. @asynccontextmanager
  171. async def lifespan(app: FastAPI):
  172. run_migrations()
  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. # Initalize 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. app.add_middleware(
  677. CORSMiddleware,
  678. allow_origins=CORS_ALLOW_ORIGIN,
  679. allow_credentials=True,
  680. allow_methods=["*"],
  681. allow_headers=["*"],
  682. )
  683. app.add_middleware(SecurityHeadersMiddleware)
  684. @app.middleware("http")
  685. async def commit_session_after_request(request: Request, call_next):
  686. response = await call_next(request)
  687. log.debug("Commit session after request")
  688. Session.commit()
  689. return response
  690. @app.middleware("http")
  691. async def check_url(request: Request, call_next):
  692. if len(app.state.MODELS) == 0:
  693. await get_all_models()
  694. else:
  695. pass
  696. start_time = int(time.time())
  697. response = await call_next(request)
  698. process_time = int(time.time()) - start_time
  699. response.headers["X-Process-Time"] = str(process_time)
  700. return response
  701. @app.middleware("http")
  702. async def update_embedding_function(request: Request, call_next):
  703. response = await call_next(request)
  704. if "/embedding/update" in request.url.path:
  705. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  706. return response
  707. @app.middleware("http")
  708. async def inspect_websocket(request: Request, call_next):
  709. if (
  710. "/ws/socket.io" in request.url.path
  711. and request.query_params.get("transport") == "websocket"
  712. ):
  713. upgrade = (request.headers.get("Upgrade") or "").lower()
  714. connection = (request.headers.get("Connection") or "").lower().split(",")
  715. # Check that there's the correct headers for an upgrade, else reject the connection
  716. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  717. if upgrade != "websocket" or "upgrade" not in connection:
  718. return JSONResponse(
  719. status_code=status.HTTP_400_BAD_REQUEST,
  720. content={"detail": "Invalid WebSocket upgrade request"},
  721. )
  722. return await call_next(request)
  723. app.mount("/ws", socket_app)
  724. app.mount("/ollama", ollama_app)
  725. app.mount("/openai", openai_app)
  726. app.mount("/images/api/v1", images_app)
  727. app.mount("/audio/api/v1", audio_app)
  728. app.mount("/retrieval/api/v1", retrieval_app)
  729. app.mount("/api/v1", webui_app)
  730. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  731. async def get_all_models():
  732. # TODO: Optimize this function
  733. pipe_models = []
  734. openai_models = []
  735. ollama_models = []
  736. pipe_models = await get_pipe_models()
  737. if app.state.config.ENABLE_OPENAI_API:
  738. openai_models = await get_openai_models()
  739. openai_models = openai_models["data"]
  740. if app.state.config.ENABLE_OLLAMA_API:
  741. ollama_models = await get_ollama_models()
  742. ollama_models = [
  743. {
  744. "id": model["model"],
  745. "name": model["name"],
  746. "object": "model",
  747. "created": int(time.time()),
  748. "owned_by": "ollama",
  749. "ollama": model,
  750. }
  751. for model in ollama_models["models"]
  752. ]
  753. models = pipe_models + openai_models + ollama_models
  754. global_action_ids = [
  755. function.id for function in Functions.get_global_action_functions()
  756. ]
  757. enabled_action_ids = [
  758. function.id
  759. for function in Functions.get_functions_by_type("action", active_only=True)
  760. ]
  761. custom_models = Models.get_all_models()
  762. for custom_model in custom_models:
  763. if custom_model.base_model_id is None:
  764. for model in models:
  765. if (
  766. custom_model.id == model["id"]
  767. or custom_model.id == model["id"].split(":")[0]
  768. ):
  769. model["name"] = custom_model.name
  770. model["info"] = custom_model.model_dump()
  771. action_ids = []
  772. if "info" in model and "meta" in model["info"]:
  773. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  774. model["action_ids"] = action_ids
  775. else:
  776. owned_by = "openai"
  777. pipe = None
  778. action_ids = []
  779. for model in models:
  780. if (
  781. custom_model.base_model_id == model["id"]
  782. or custom_model.base_model_id == model["id"].split(":")[0]
  783. ):
  784. owned_by = model["owned_by"]
  785. if "pipe" in model:
  786. pipe = model["pipe"]
  787. if "info" in model and "meta" in model["info"]:
  788. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  789. break
  790. models.append(
  791. {
  792. "id": custom_model.id,
  793. "name": custom_model.name,
  794. "object": "model",
  795. "created": custom_model.created_at,
  796. "owned_by": owned_by,
  797. "info": custom_model.model_dump(),
  798. "preset": True,
  799. **({"pipe": pipe} if pipe is not None else {}),
  800. "action_ids": action_ids,
  801. }
  802. )
  803. for model in models:
  804. action_ids = []
  805. if "action_ids" in model:
  806. action_ids = model["action_ids"]
  807. del model["action_ids"]
  808. action_ids = action_ids + global_action_ids
  809. action_ids = list(set(action_ids))
  810. action_ids = [
  811. action_id for action_id in action_ids if action_id in enabled_action_ids
  812. ]
  813. model["actions"] = []
  814. for action_id in action_ids:
  815. action = Functions.get_function_by_id(action_id)
  816. if action is None:
  817. raise Exception(f"Action not found: {action_id}")
  818. if action_id in webui_app.state.FUNCTIONS:
  819. function_module = webui_app.state.FUNCTIONS[action_id]
  820. else:
  821. function_module, _, _ = load_function_module_by_id(action_id)
  822. webui_app.state.FUNCTIONS[action_id] = function_module
  823. __webui__ = False
  824. if hasattr(function_module, "__webui__"):
  825. __webui__ = function_module.__webui__
  826. if hasattr(function_module, "actions"):
  827. actions = function_module.actions
  828. model["actions"].extend(
  829. [
  830. {
  831. "id": f"{action_id}.{_action['id']}",
  832. "name": _action.get(
  833. "name", f"{action.name} ({_action['id']})"
  834. ),
  835. "description": action.meta.description,
  836. "icon_url": _action.get(
  837. "icon_url", action.meta.manifest.get("icon_url", None)
  838. ),
  839. **({"__webui__": __webui__} if __webui__ else {}),
  840. }
  841. for _action in actions
  842. ]
  843. )
  844. else:
  845. model["actions"].append(
  846. {
  847. "id": action_id,
  848. "name": action.name,
  849. "description": action.meta.description,
  850. "icon_url": action.meta.manifest.get("icon_url", None),
  851. **({"__webui__": __webui__} if __webui__ else {}),
  852. }
  853. )
  854. app.state.MODELS = {model["id"]: model for model in models}
  855. webui_app.state.MODELS = app.state.MODELS
  856. return models
  857. @app.get("/api/models")
  858. async def get_models(user=Depends(get_verified_user)):
  859. models = await get_all_models()
  860. # Filter out filter pipelines
  861. models = [
  862. model
  863. for model in models
  864. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  865. ]
  866. if app.state.config.ENABLE_MODEL_FILTER:
  867. if user.role == "user":
  868. models = list(
  869. filter(
  870. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  871. models,
  872. )
  873. )
  874. return {"data": models}
  875. return {"data": models}
  876. @app.post("/api/chat/completions")
  877. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  878. model_id = form_data["model"]
  879. if model_id not in app.state.MODELS:
  880. raise HTTPException(
  881. status_code=status.HTTP_404_NOT_FOUND,
  882. detail="Model not found",
  883. )
  884. if app.state.config.ENABLE_MODEL_FILTER:
  885. if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
  886. raise HTTPException(
  887. status_code=status.HTTP_403_FORBIDDEN,
  888. detail="Model not found",
  889. )
  890. model = app.state.MODELS[model_id]
  891. if model.get("pipe"):
  892. return await generate_function_chat_completion(form_data, user=user)
  893. if model["owned_by"] == "ollama":
  894. # Using /ollama/api/chat endpoint
  895. form_data = convert_payload_openai_to_ollama(form_data)
  896. form_data = GenerateChatCompletionForm(**form_data)
  897. response = await generate_ollama_chat_completion(form_data=form_data, user=user)
  898. if form_data.stream:
  899. response.headers["content-type"] = "text/event-stream"
  900. return StreamingResponse(
  901. convert_streaming_response_ollama_to_openai(response),
  902. headers=dict(response.headers),
  903. )
  904. else:
  905. return convert_response_ollama_to_openai(response)
  906. else:
  907. return await generate_openai_chat_completion(form_data, user=user)
  908. @app.post("/api/chat/completed")
  909. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  910. data = form_data
  911. model_id = data["model"]
  912. if model_id not in app.state.MODELS:
  913. raise HTTPException(
  914. status_code=status.HTTP_404_NOT_FOUND,
  915. detail="Model not found",
  916. )
  917. model = app.state.MODELS[model_id]
  918. sorted_filters = get_sorted_filters(model_id)
  919. if "pipeline" in model:
  920. sorted_filters = [model] + sorted_filters
  921. for filter in sorted_filters:
  922. r = None
  923. try:
  924. urlIdx = filter["urlIdx"]
  925. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  926. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  927. if key != "":
  928. headers = {"Authorization": f"Bearer {key}"}
  929. r = requests.post(
  930. f"{url}/{filter['id']}/filter/outlet",
  931. headers=headers,
  932. json={
  933. "user": {
  934. "id": user.id,
  935. "name": user.name,
  936. "email": user.email,
  937. "role": user.role,
  938. },
  939. "body": data,
  940. },
  941. )
  942. r.raise_for_status()
  943. data = r.json()
  944. except Exception as e:
  945. # Handle connection error here
  946. print(f"Connection error: {e}")
  947. if r is not None:
  948. try:
  949. res = r.json()
  950. if "detail" in res:
  951. return JSONResponse(
  952. status_code=r.status_code,
  953. content=res,
  954. )
  955. except Exception:
  956. pass
  957. else:
  958. pass
  959. __event_emitter__ = get_event_emitter(
  960. {
  961. "chat_id": data["chat_id"],
  962. "message_id": data["id"],
  963. "session_id": data["session_id"],
  964. }
  965. )
  966. __event_call__ = get_event_call(
  967. {
  968. "chat_id": data["chat_id"],
  969. "message_id": data["id"],
  970. "session_id": data["session_id"],
  971. }
  972. )
  973. def get_priority(function_id):
  974. function = Functions.get_function_by_id(function_id)
  975. if function is not None and hasattr(function, "valves"):
  976. # TODO: Fix FunctionModel to include vavles
  977. return (function.valves if function.valves else {}).get("priority", 0)
  978. return 0
  979. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  980. if "info" in model and "meta" in model["info"]:
  981. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  982. filter_ids = list(set(filter_ids))
  983. enabled_filter_ids = [
  984. function.id
  985. for function in Functions.get_functions_by_type("filter", active_only=True)
  986. ]
  987. filter_ids = [
  988. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  989. ]
  990. # Sort filter_ids by priority, using the get_priority function
  991. filter_ids.sort(key=get_priority)
  992. for filter_id in filter_ids:
  993. filter = Functions.get_function_by_id(filter_id)
  994. if not filter:
  995. continue
  996. if filter_id in webui_app.state.FUNCTIONS:
  997. function_module = webui_app.state.FUNCTIONS[filter_id]
  998. else:
  999. function_module, _, _ = load_function_module_by_id(filter_id)
  1000. webui_app.state.FUNCTIONS[filter_id] = function_module
  1001. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1002. valves = Functions.get_function_valves_by_id(filter_id)
  1003. function_module.valves = function_module.Valves(
  1004. **(valves if valves else {})
  1005. )
  1006. if not hasattr(function_module, "outlet"):
  1007. continue
  1008. try:
  1009. outlet = function_module.outlet
  1010. # Get the signature of the function
  1011. sig = inspect.signature(outlet)
  1012. params = {"body": data}
  1013. # Extra parameters to be passed to the function
  1014. extra_params = {
  1015. "__model__": model,
  1016. "__id__": filter_id,
  1017. "__event_emitter__": __event_emitter__,
  1018. "__event_call__": __event_call__,
  1019. }
  1020. # Add extra params in contained in function signature
  1021. for key, value in extra_params.items():
  1022. if key in sig.parameters:
  1023. params[key] = value
  1024. if "__user__" in sig.parameters:
  1025. __user__ = {
  1026. "id": user.id,
  1027. "email": user.email,
  1028. "name": user.name,
  1029. "role": user.role,
  1030. }
  1031. try:
  1032. if hasattr(function_module, "UserValves"):
  1033. __user__["valves"] = function_module.UserValves(
  1034. **Functions.get_user_valves_by_id_and_user_id(
  1035. filter_id, user.id
  1036. )
  1037. )
  1038. except Exception as e:
  1039. print(e)
  1040. params = {**params, "__user__": __user__}
  1041. if inspect.iscoroutinefunction(outlet):
  1042. data = await outlet(**params)
  1043. else:
  1044. data = outlet(**params)
  1045. except Exception as e:
  1046. print(f"Error: {e}")
  1047. return JSONResponse(
  1048. status_code=status.HTTP_400_BAD_REQUEST,
  1049. content={"detail": str(e)},
  1050. )
  1051. return data
  1052. @app.post("/api/chat/actions/{action_id}")
  1053. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1054. if "." in action_id:
  1055. action_id, sub_action_id = action_id.split(".")
  1056. else:
  1057. sub_action_id = None
  1058. action = Functions.get_function_by_id(action_id)
  1059. if not action:
  1060. raise HTTPException(
  1061. status_code=status.HTTP_404_NOT_FOUND,
  1062. detail="Action not found",
  1063. )
  1064. data = form_data
  1065. model_id = data["model"]
  1066. if model_id not in app.state.MODELS:
  1067. raise HTTPException(
  1068. status_code=status.HTTP_404_NOT_FOUND,
  1069. detail="Model not found",
  1070. )
  1071. model = app.state.MODELS[model_id]
  1072. __event_emitter__ = get_event_emitter(
  1073. {
  1074. "chat_id": data["chat_id"],
  1075. "message_id": data["id"],
  1076. "session_id": data["session_id"],
  1077. }
  1078. )
  1079. __event_call__ = get_event_call(
  1080. {
  1081. "chat_id": data["chat_id"],
  1082. "message_id": data["id"],
  1083. "session_id": data["session_id"],
  1084. }
  1085. )
  1086. if action_id in webui_app.state.FUNCTIONS:
  1087. function_module = webui_app.state.FUNCTIONS[action_id]
  1088. else:
  1089. function_module, _, _ = load_function_module_by_id(action_id)
  1090. webui_app.state.FUNCTIONS[action_id] = function_module
  1091. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1092. valves = Functions.get_function_valves_by_id(action_id)
  1093. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1094. if hasattr(function_module, "action"):
  1095. try:
  1096. action = function_module.action
  1097. # Get the signature of the function
  1098. sig = inspect.signature(action)
  1099. params = {"body": data}
  1100. # Extra parameters to be passed to the function
  1101. extra_params = {
  1102. "__model__": model,
  1103. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1104. "__event_emitter__": __event_emitter__,
  1105. "__event_call__": __event_call__,
  1106. }
  1107. # Add extra params in contained in function signature
  1108. for key, value in extra_params.items():
  1109. if key in sig.parameters:
  1110. params[key] = value
  1111. if "__user__" in sig.parameters:
  1112. __user__ = {
  1113. "id": user.id,
  1114. "email": user.email,
  1115. "name": user.name,
  1116. "role": user.role,
  1117. }
  1118. try:
  1119. if hasattr(function_module, "UserValves"):
  1120. __user__["valves"] = function_module.UserValves(
  1121. **Functions.get_user_valves_by_id_and_user_id(
  1122. action_id, user.id
  1123. )
  1124. )
  1125. except Exception as e:
  1126. print(e)
  1127. params = {**params, "__user__": __user__}
  1128. if inspect.iscoroutinefunction(action):
  1129. data = await action(**params)
  1130. else:
  1131. data = action(**params)
  1132. except Exception as e:
  1133. print(f"Error: {e}")
  1134. return JSONResponse(
  1135. status_code=status.HTTP_400_BAD_REQUEST,
  1136. content={"detail": str(e)},
  1137. )
  1138. return data
  1139. ##################################
  1140. #
  1141. # Task Endpoints
  1142. #
  1143. ##################################
  1144. # TODO: Refactor task API endpoints below into a separate file
  1145. @app.get("/api/task/config")
  1146. async def get_task_config(user=Depends(get_verified_user)):
  1147. return {
  1148. "TASK_MODEL": app.state.config.TASK_MODEL,
  1149. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1150. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1151. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1152. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1153. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1154. }
  1155. class TaskConfigForm(BaseModel):
  1156. TASK_MODEL: Optional[str]
  1157. TASK_MODEL_EXTERNAL: Optional[str]
  1158. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1159. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1160. ENABLE_SEARCH_QUERY: bool
  1161. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1162. @app.post("/api/task/config/update")
  1163. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1164. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1165. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1166. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1167. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1168. )
  1169. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1170. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1171. )
  1172. app.state.config.ENABLE_SEARCH_QUERY = form_data.ENABLE_SEARCH_QUERY
  1173. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1174. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1175. )
  1176. return {
  1177. "TASK_MODEL": app.state.config.TASK_MODEL,
  1178. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1179. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1180. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1181. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1182. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1183. }
  1184. @app.post("/api/task/title/completions")
  1185. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1186. print("generate_title")
  1187. model_id = form_data["model"]
  1188. if model_id not in app.state.MODELS:
  1189. raise HTTPException(
  1190. status_code=status.HTTP_404_NOT_FOUND,
  1191. detail="Model not found",
  1192. )
  1193. # Check if the user has a custom task model
  1194. # If the user has a custom task model, use that model
  1195. task_model_id = get_task_model_id(model_id)
  1196. print(task_model_id)
  1197. model = app.state.MODELS[task_model_id]
  1198. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1199. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1200. else:
  1201. 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.
  1202. Examples of titles:
  1203. 📉 Stock Market Trends
  1204. 🍪 Perfect Chocolate Chip Recipe
  1205. Evolution of Music Streaming
  1206. Remote Work Productivity Tips
  1207. Artificial Intelligence in Healthcare
  1208. 🎮 Video Game Development Insights
  1209. Prompt: {{prompt:middletruncate:8000}}"""
  1210. content = title_generation_template(
  1211. template,
  1212. form_data["prompt"],
  1213. {
  1214. "name": user.name,
  1215. "location": user.info.get("location") if user.info else None,
  1216. },
  1217. )
  1218. payload = {
  1219. "model": task_model_id,
  1220. "messages": [{"role": "user", "content": content}],
  1221. "stream": False,
  1222. **(
  1223. {"max_tokens": 50}
  1224. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1225. else {
  1226. "max_completion_tokens": 50,
  1227. }
  1228. ),
  1229. "chat_id": form_data.get("chat_id", None),
  1230. "metadata": {"task": str(TASKS.TITLE_GENERATION)},
  1231. }
  1232. log.debug(payload)
  1233. # Handle pipeline filters
  1234. try:
  1235. payload = filter_pipeline(payload, user)
  1236. except Exception as e:
  1237. if len(e.args) > 1:
  1238. return JSONResponse(
  1239. status_code=e.args[0],
  1240. content={"detail": e.args[1]},
  1241. )
  1242. else:
  1243. return JSONResponse(
  1244. status_code=status.HTTP_400_BAD_REQUEST,
  1245. content={"detail": str(e)},
  1246. )
  1247. if "chat_id" in payload:
  1248. del payload["chat_id"]
  1249. return await generate_chat_completions(form_data=payload, user=user)
  1250. @app.post("/api/task/query/completions")
  1251. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1252. print("generate_search_query")
  1253. if not app.state.config.ENABLE_SEARCH_QUERY:
  1254. raise HTTPException(
  1255. status_code=status.HTTP_400_BAD_REQUEST,
  1256. detail=f"Search query generation is disabled",
  1257. )
  1258. model_id = form_data["model"]
  1259. if model_id not in app.state.MODELS:
  1260. raise HTTPException(
  1261. status_code=status.HTTP_404_NOT_FOUND,
  1262. detail="Model not found",
  1263. )
  1264. # Check if the user has a custom task model
  1265. # If the user has a custom task model, use that model
  1266. task_model_id = get_task_model_id(model_id)
  1267. print(task_model_id)
  1268. model = app.state.MODELS[task_model_id]
  1269. if app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE != "":
  1270. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1271. else:
  1272. 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}}.
  1273. User Message:
  1274. {{prompt:end:4000}}
  1275. Interaction History:
  1276. {{MESSAGES:END:6}}
  1277. Search Query:"""
  1278. content = search_query_generation_template(
  1279. template, form_data["messages"], {"name": user.name}
  1280. )
  1281. print("content", content)
  1282. payload = {
  1283. "model": task_model_id,
  1284. "messages": [{"role": "user", "content": content}],
  1285. "stream": False,
  1286. **(
  1287. {"max_tokens": 30}
  1288. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1289. else {
  1290. "max_completion_tokens": 30,
  1291. }
  1292. ),
  1293. "metadata": {"task": str(TASKS.QUERY_GENERATION)},
  1294. }
  1295. log.debug(payload)
  1296. # Handle pipeline filters
  1297. try:
  1298. payload = filter_pipeline(payload, user)
  1299. except Exception as e:
  1300. if len(e.args) > 1:
  1301. return JSONResponse(
  1302. status_code=e.args[0],
  1303. content={"detail": e.args[1]},
  1304. )
  1305. else:
  1306. return JSONResponse(
  1307. status_code=status.HTTP_400_BAD_REQUEST,
  1308. content={"detail": str(e)},
  1309. )
  1310. if "chat_id" in payload:
  1311. del payload["chat_id"]
  1312. return await generate_chat_completions(form_data=payload, user=user)
  1313. @app.post("/api/task/emoji/completions")
  1314. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1315. print("generate_emoji")
  1316. model_id = form_data["model"]
  1317. if model_id not in app.state.MODELS:
  1318. raise HTTPException(
  1319. status_code=status.HTTP_404_NOT_FOUND,
  1320. detail="Model not found",
  1321. )
  1322. # Check if the user has a custom task model
  1323. # If the user has a custom task model, use that model
  1324. task_model_id = get_task_model_id(model_id)
  1325. print(task_model_id)
  1326. model = app.state.MODELS[task_model_id]
  1327. template = '''
  1328. 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., 😊, 😢, 😡, 😱).
  1329. Message: """{{prompt}}"""
  1330. '''
  1331. content = title_generation_template(
  1332. template,
  1333. form_data["prompt"],
  1334. {
  1335. "name": user.name,
  1336. "location": user.info.get("location") if user.info else None,
  1337. },
  1338. )
  1339. payload = {
  1340. "model": task_model_id,
  1341. "messages": [{"role": "user", "content": content}],
  1342. "stream": False,
  1343. **(
  1344. {"max_tokens": 4}
  1345. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1346. else {
  1347. "max_completion_tokens": 4,
  1348. }
  1349. ),
  1350. "chat_id": form_data.get("chat_id", None),
  1351. "metadata": {"task": str(TASKS.EMOJI_GENERATION)},
  1352. }
  1353. log.debug(payload)
  1354. # Handle pipeline filters
  1355. try:
  1356. payload = filter_pipeline(payload, user)
  1357. except Exception as e:
  1358. if len(e.args) > 1:
  1359. return JSONResponse(
  1360. status_code=e.args[0],
  1361. content={"detail": e.args[1]},
  1362. )
  1363. else:
  1364. return JSONResponse(
  1365. status_code=status.HTTP_400_BAD_REQUEST,
  1366. content={"detail": str(e)},
  1367. )
  1368. if "chat_id" in payload:
  1369. del payload["chat_id"]
  1370. return await generate_chat_completions(form_data=payload, user=user)
  1371. @app.post("/api/task/moa/completions")
  1372. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1373. print("generate_moa_response")
  1374. model_id = form_data["model"]
  1375. if model_id not in app.state.MODELS:
  1376. raise HTTPException(
  1377. status_code=status.HTTP_404_NOT_FOUND,
  1378. detail="Model not found",
  1379. )
  1380. # Check if the user has a custom task model
  1381. # If the user has a custom task model, use that model
  1382. task_model_id = get_task_model_id(model_id)
  1383. print(task_model_id)
  1384. model = app.state.MODELS[task_model_id]
  1385. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1386. 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.
  1387. Responses from models: {{responses}}"""
  1388. content = moa_response_generation_template(
  1389. template,
  1390. form_data["prompt"],
  1391. form_data["responses"],
  1392. )
  1393. payload = {
  1394. "model": task_model_id,
  1395. "messages": [{"role": "user", "content": content}],
  1396. "stream": form_data.get("stream", False),
  1397. "chat_id": form_data.get("chat_id", None),
  1398. "metadata": {"task": str(TASKS.MOA_RESPONSE_GENERATION)},
  1399. }
  1400. log.debug(payload)
  1401. try:
  1402. payload = filter_pipeline(payload, user)
  1403. except Exception as e:
  1404. if len(e.args) > 1:
  1405. return JSONResponse(
  1406. status_code=e.args[0],
  1407. content={"detail": e.args[1]},
  1408. )
  1409. else:
  1410. return JSONResponse(
  1411. status_code=status.HTTP_400_BAD_REQUEST,
  1412. content={"detail": str(e)},
  1413. )
  1414. if "chat_id" in payload:
  1415. del payload["chat_id"]
  1416. return await generate_chat_completions(form_data=payload, user=user)
  1417. ##################################
  1418. #
  1419. # Pipelines Endpoints
  1420. #
  1421. ##################################
  1422. # TODO: Refactor pipelines API endpoints below into a separate file
  1423. @app.get("/api/pipelines/list")
  1424. async def get_pipelines_list(user=Depends(get_admin_user)):
  1425. responses = await get_openai_models(raw=True)
  1426. print(responses)
  1427. urlIdxs = [
  1428. idx
  1429. for idx, response in enumerate(responses)
  1430. if response is not None and "pipelines" in response
  1431. ]
  1432. return {
  1433. "data": [
  1434. {
  1435. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1436. "idx": urlIdx,
  1437. }
  1438. for urlIdx in urlIdxs
  1439. ]
  1440. }
  1441. @app.post("/api/pipelines/upload")
  1442. async def upload_pipeline(
  1443. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1444. ):
  1445. print("upload_pipeline", urlIdx, file.filename)
  1446. # Check if the uploaded file is a python file
  1447. if not (file.filename and file.filename.endswith(".py")):
  1448. raise HTTPException(
  1449. status_code=status.HTTP_400_BAD_REQUEST,
  1450. detail="Only Python (.py) files are allowed.",
  1451. )
  1452. upload_folder = f"{CACHE_DIR}/pipelines"
  1453. os.makedirs(upload_folder, exist_ok=True)
  1454. file_path = os.path.join(upload_folder, file.filename)
  1455. r = None
  1456. try:
  1457. # Save the uploaded file
  1458. with open(file_path, "wb") as buffer:
  1459. shutil.copyfileobj(file.file, buffer)
  1460. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1461. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1462. headers = {"Authorization": f"Bearer {key}"}
  1463. with open(file_path, "rb") as f:
  1464. files = {"file": f}
  1465. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1466. r.raise_for_status()
  1467. data = r.json()
  1468. return {**data}
  1469. except Exception as e:
  1470. # Handle connection error here
  1471. print(f"Connection error: {e}")
  1472. detail = "Pipeline not found"
  1473. status_code = status.HTTP_404_NOT_FOUND
  1474. if r is not None:
  1475. status_code = r.status_code
  1476. try:
  1477. res = r.json()
  1478. if "detail" in res:
  1479. detail = res["detail"]
  1480. except Exception:
  1481. pass
  1482. raise HTTPException(
  1483. status_code=status_code,
  1484. detail=detail,
  1485. )
  1486. finally:
  1487. # Ensure the file is deleted after the upload is completed or on failure
  1488. if os.path.exists(file_path):
  1489. os.remove(file_path)
  1490. class AddPipelineForm(BaseModel):
  1491. url: str
  1492. urlIdx: int
  1493. @app.post("/api/pipelines/add")
  1494. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1495. r = None
  1496. try:
  1497. urlIdx = form_data.urlIdx
  1498. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1499. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1500. headers = {"Authorization": f"Bearer {key}"}
  1501. r = requests.post(
  1502. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1503. )
  1504. r.raise_for_status()
  1505. data = r.json()
  1506. return {**data}
  1507. except Exception as e:
  1508. # Handle connection error here
  1509. print(f"Connection error: {e}")
  1510. detail = "Pipeline not found"
  1511. if r is not None:
  1512. try:
  1513. res = r.json()
  1514. if "detail" in res:
  1515. detail = res["detail"]
  1516. except Exception:
  1517. pass
  1518. raise HTTPException(
  1519. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1520. detail=detail,
  1521. )
  1522. class DeletePipelineForm(BaseModel):
  1523. id: str
  1524. urlIdx: int
  1525. @app.delete("/api/pipelines/delete")
  1526. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1527. r = None
  1528. try:
  1529. urlIdx = form_data.urlIdx
  1530. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1531. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1532. headers = {"Authorization": f"Bearer {key}"}
  1533. r = requests.delete(
  1534. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1535. )
  1536. r.raise_for_status()
  1537. data = r.json()
  1538. return {**data}
  1539. except Exception as e:
  1540. # Handle connection error here
  1541. print(f"Connection error: {e}")
  1542. detail = "Pipeline not found"
  1543. if r is not None:
  1544. try:
  1545. res = r.json()
  1546. if "detail" in res:
  1547. detail = res["detail"]
  1548. except Exception:
  1549. pass
  1550. raise HTTPException(
  1551. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1552. detail=detail,
  1553. )
  1554. @app.get("/api/pipelines")
  1555. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1556. r = None
  1557. try:
  1558. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1559. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1560. headers = {"Authorization": f"Bearer {key}"}
  1561. r = requests.get(f"{url}/pipelines", headers=headers)
  1562. r.raise_for_status()
  1563. data = r.json()
  1564. return {**data}
  1565. except Exception as e:
  1566. # Handle connection error here
  1567. print(f"Connection error: {e}")
  1568. detail = "Pipeline not found"
  1569. if r is not None:
  1570. try:
  1571. res = r.json()
  1572. if "detail" in res:
  1573. detail = res["detail"]
  1574. except Exception:
  1575. pass
  1576. raise HTTPException(
  1577. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1578. detail=detail,
  1579. )
  1580. @app.get("/api/pipelines/{pipeline_id}/valves")
  1581. async def get_pipeline_valves(
  1582. urlIdx: Optional[int],
  1583. pipeline_id: str,
  1584. user=Depends(get_admin_user),
  1585. ):
  1586. r = None
  1587. try:
  1588. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1589. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1590. headers = {"Authorization": f"Bearer {key}"}
  1591. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1592. r.raise_for_status()
  1593. data = r.json()
  1594. return {**data}
  1595. except Exception as e:
  1596. # Handle connection error here
  1597. print(f"Connection error: {e}")
  1598. detail = "Pipeline not found"
  1599. if r is not None:
  1600. try:
  1601. res = r.json()
  1602. if "detail" in res:
  1603. detail = res["detail"]
  1604. except Exception:
  1605. pass
  1606. raise HTTPException(
  1607. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1608. detail=detail,
  1609. )
  1610. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1611. async def get_pipeline_valves_spec(
  1612. urlIdx: Optional[int],
  1613. pipeline_id: str,
  1614. user=Depends(get_admin_user),
  1615. ):
  1616. r = None
  1617. try:
  1618. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1619. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1620. headers = {"Authorization": f"Bearer {key}"}
  1621. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1622. r.raise_for_status()
  1623. data = r.json()
  1624. return {**data}
  1625. except Exception as e:
  1626. # Handle connection error here
  1627. print(f"Connection error: {e}")
  1628. detail = "Pipeline not found"
  1629. if r is not None:
  1630. try:
  1631. res = r.json()
  1632. if "detail" in res:
  1633. detail = res["detail"]
  1634. except Exception:
  1635. pass
  1636. raise HTTPException(
  1637. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1638. detail=detail,
  1639. )
  1640. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1641. async def update_pipeline_valves(
  1642. urlIdx: Optional[int],
  1643. pipeline_id: str,
  1644. form_data: dict,
  1645. user=Depends(get_admin_user),
  1646. ):
  1647. r = None
  1648. try:
  1649. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1650. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1651. headers = {"Authorization": f"Bearer {key}"}
  1652. r = requests.post(
  1653. f"{url}/{pipeline_id}/valves/update",
  1654. headers=headers,
  1655. json={**form_data},
  1656. )
  1657. r.raise_for_status()
  1658. data = r.json()
  1659. return {**data}
  1660. except Exception as e:
  1661. # Handle connection error here
  1662. print(f"Connection error: {e}")
  1663. detail = "Pipeline not found"
  1664. if r is not None:
  1665. try:
  1666. res = r.json()
  1667. if "detail" in res:
  1668. detail = res["detail"]
  1669. except Exception:
  1670. pass
  1671. raise HTTPException(
  1672. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1673. detail=detail,
  1674. )
  1675. ##################################
  1676. #
  1677. # Config Endpoints
  1678. #
  1679. ##################################
  1680. @app.get("/api/config")
  1681. async def get_app_config(request: Request):
  1682. user = None
  1683. if "token" in request.cookies:
  1684. token = request.cookies.get("token")
  1685. data = decode_token(token)
  1686. if data is not None and "id" in data:
  1687. user = Users.get_user_by_id(data["id"])
  1688. return {
  1689. "status": True,
  1690. "name": WEBUI_NAME,
  1691. "version": VERSION,
  1692. "default_locale": str(DEFAULT_LOCALE),
  1693. "oauth": {
  1694. "providers": {
  1695. name: config.get("name", name)
  1696. for name, config in OAUTH_PROVIDERS.items()
  1697. }
  1698. },
  1699. "features": {
  1700. "auth": WEBUI_AUTH,
  1701. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1702. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1703. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1704. **(
  1705. {
  1706. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1707. "enable_image_generation": images_app.state.config.ENABLED,
  1708. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1709. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1710. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1711. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1712. }
  1713. if user is not None
  1714. else {}
  1715. ),
  1716. },
  1717. **(
  1718. {
  1719. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1720. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1721. "audio": {
  1722. "tts": {
  1723. "engine": audio_app.state.config.TTS_ENGINE,
  1724. "voice": audio_app.state.config.TTS_VOICE,
  1725. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  1726. },
  1727. "stt": {
  1728. "engine": audio_app.state.config.STT_ENGINE,
  1729. },
  1730. },
  1731. "file": {
  1732. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  1733. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  1734. },
  1735. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  1736. }
  1737. if user is not None
  1738. else {}
  1739. ),
  1740. }
  1741. @app.get("/api/config/model/filter")
  1742. async def get_model_filter_config(user=Depends(get_admin_user)):
  1743. return {
  1744. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1745. "models": app.state.config.MODEL_FILTER_LIST,
  1746. }
  1747. class ModelFilterConfigForm(BaseModel):
  1748. enabled: bool
  1749. models: list[str]
  1750. @app.post("/api/config/model/filter")
  1751. async def update_model_filter_config(
  1752. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1753. ):
  1754. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1755. app.state.config.MODEL_FILTER_LIST = form_data.models
  1756. return {
  1757. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1758. "models": app.state.config.MODEL_FILTER_LIST,
  1759. }
  1760. # TODO: webhook endpoint should be under config endpoints
  1761. @app.get("/api/webhook")
  1762. async def get_webhook_url(user=Depends(get_admin_user)):
  1763. return {
  1764. "url": app.state.config.WEBHOOK_URL,
  1765. }
  1766. class UrlForm(BaseModel):
  1767. url: str
  1768. @app.post("/api/webhook")
  1769. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1770. app.state.config.WEBHOOK_URL = form_data.url
  1771. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1772. return {"url": app.state.config.WEBHOOK_URL}
  1773. @app.get("/api/version")
  1774. async def get_app_version():
  1775. return {
  1776. "version": VERSION,
  1777. }
  1778. @app.get("/api/changelog")
  1779. async def get_app_changelog():
  1780. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1781. @app.get("/api/version/updates")
  1782. async def get_app_latest_release_version():
  1783. try:
  1784. timeout = aiohttp.ClientTimeout(total=1)
  1785. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  1786. async with session.get(
  1787. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1788. ) as response:
  1789. response.raise_for_status()
  1790. data = await response.json()
  1791. latest_version = data["tag_name"]
  1792. return {"current": VERSION, "latest": latest_version[1:]}
  1793. except Exception as e:
  1794. log.debug(e)
  1795. return {"current": VERSION, "latest": VERSION}
  1796. ############################
  1797. # OAuth Login & Callback
  1798. ############################
  1799. oauth = OAuth()
  1800. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1801. oauth.register(
  1802. name=provider_name,
  1803. client_id=provider_config["client_id"],
  1804. client_secret=provider_config["client_secret"],
  1805. server_metadata_url=provider_config["server_metadata_url"],
  1806. client_kwargs={
  1807. "scope": provider_config["scope"],
  1808. },
  1809. redirect_uri=provider_config["redirect_uri"],
  1810. )
  1811. # SessionMiddleware is used by authlib for oauth
  1812. if len(OAUTH_PROVIDERS) > 0:
  1813. app.add_middleware(
  1814. SessionMiddleware,
  1815. secret_key=WEBUI_SECRET_KEY,
  1816. session_cookie="oui-session",
  1817. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1818. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1819. )
  1820. @app.get("/oauth/{provider}/login")
  1821. async def oauth_login(provider: str, request: Request):
  1822. if provider not in OAUTH_PROVIDERS:
  1823. raise HTTPException(404)
  1824. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  1825. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  1826. "oauth_callback", provider=provider
  1827. )
  1828. client = oauth.create_client(provider)
  1829. if client is None:
  1830. raise HTTPException(404)
  1831. return await client.authorize_redirect(request, redirect_uri)
  1832. # OAuth login logic is as follows:
  1833. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1834. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1835. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1836. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1837. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1838. @app.get("/oauth/{provider}/callback")
  1839. async def oauth_callback(provider: str, request: Request, response: Response):
  1840. if provider not in OAUTH_PROVIDERS:
  1841. raise HTTPException(404)
  1842. client = oauth.create_client(provider)
  1843. try:
  1844. token = await client.authorize_access_token(request)
  1845. except Exception as e:
  1846. log.warning(f"OAuth callback error: {e}")
  1847. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1848. user_data: UserInfo = token["userinfo"]
  1849. sub = user_data.get("sub")
  1850. if not sub:
  1851. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1852. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1853. provider_sub = f"{provider}@{sub}"
  1854. email_claim = webui_app.state.config.OAUTH_EMAIL_CLAIM
  1855. email = user_data.get(email_claim, "").lower()
  1856. # We currently mandate that email addresses are provided
  1857. if not email:
  1858. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1859. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1860. # Check if the user exists
  1861. user = Users.get_user_by_oauth_sub(provider_sub)
  1862. if not user:
  1863. # If the user does not exist, check if merging is enabled
  1864. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1865. # Check if the user exists by email
  1866. user = Users.get_user_by_email(email)
  1867. if user:
  1868. # Update the user with the new oauth sub
  1869. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1870. if not user:
  1871. # If the user does not exist, check if signups are enabled
  1872. if ENABLE_OAUTH_SIGNUP.value:
  1873. # Check if an existing user with the same email already exists
  1874. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1875. if existing_user:
  1876. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1877. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1878. picture_url = user_data.get(picture_claim, "")
  1879. if picture_url:
  1880. # Download the profile image into a base64 string
  1881. try:
  1882. async with aiohttp.ClientSession() as session:
  1883. async with session.get(picture_url) as resp:
  1884. picture = await resp.read()
  1885. base64_encoded_picture = base64.b64encode(picture).decode(
  1886. "utf-8"
  1887. )
  1888. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1889. if guessed_mime_type is None:
  1890. # assume JPG, browsers are tolerant enough of image formats
  1891. guessed_mime_type = "image/jpeg"
  1892. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1893. except Exception as e:
  1894. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1895. picture_url = ""
  1896. if not picture_url:
  1897. picture_url = "/user.png"
  1898. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1899. role = (
  1900. "admin"
  1901. if Users.get_num_users() == 0
  1902. else webui_app.state.config.DEFAULT_USER_ROLE
  1903. )
  1904. user = Auths.insert_new_auth(
  1905. email=email,
  1906. password=get_password_hash(
  1907. str(uuid.uuid4())
  1908. ), # Random password, not used
  1909. name=user_data.get(username_claim, "User"),
  1910. profile_image_url=picture_url,
  1911. role=role,
  1912. oauth_sub=provider_sub,
  1913. )
  1914. if webui_app.state.config.WEBHOOK_URL:
  1915. post_webhook(
  1916. webui_app.state.config.WEBHOOK_URL,
  1917. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1918. {
  1919. "action": "signup",
  1920. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1921. "user": user.model_dump_json(exclude_none=True),
  1922. },
  1923. )
  1924. else:
  1925. raise HTTPException(
  1926. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1927. )
  1928. jwt_token = create_token(
  1929. data={"id": user.id},
  1930. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1931. )
  1932. # Set the cookie token
  1933. response.set_cookie(
  1934. key="token",
  1935. value=jwt_token,
  1936. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1937. )
  1938. # Redirect back to the frontend with the JWT token
  1939. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1940. return RedirectResponse(url=redirect_url)
  1941. @app.get("/manifest.json")
  1942. async def get_manifest_json():
  1943. return {
  1944. "name": WEBUI_NAME,
  1945. "short_name": WEBUI_NAME,
  1946. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  1947. "start_url": "/",
  1948. "display": "standalone",
  1949. "background_color": "#343541",
  1950. "orientation": "any",
  1951. "icons": [
  1952. {
  1953. "src": "/static/logo.png",
  1954. "type": "image/png",
  1955. "sizes": "500x500",
  1956. "purpose": "any",
  1957. },
  1958. {
  1959. "src": "/static/logo.png",
  1960. "type": "image/png",
  1961. "sizes": "500x500",
  1962. "purpose": "maskable",
  1963. },
  1964. ],
  1965. }
  1966. @app.get("/opensearch.xml")
  1967. async def get_opensearch_xml():
  1968. xml_content = rf"""
  1969. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1970. <ShortName>{WEBUI_NAME}</ShortName>
  1971. <Description>Search {WEBUI_NAME}</Description>
  1972. <InputEncoding>UTF-8</InputEncoding>
  1973. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1974. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1975. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1976. </OpenSearchDescription>
  1977. """
  1978. return Response(content=xml_content, media_type="application/xml")
  1979. @app.get("/health")
  1980. async def healthcheck():
  1981. return {"status": True}
  1982. @app.get("/health/db")
  1983. async def healthcheck_with_db():
  1984. Session.execute(text("SELECT 1;")).all()
  1985. return {"status": True}
  1986. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1987. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1988. if os.path.exists(FRONTEND_BUILD_DIR):
  1989. mimetypes.add_type("text/javascript", ".js")
  1990. app.mount(
  1991. "/",
  1992. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1993. name="spa-static-files",
  1994. )
  1995. else:
  1996. log.warning(
  1997. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1998. )