main.py 82 KB

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