main.py 81 KB

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