main.py 82 KB

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