main.py 79 KB

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