main.py 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596
  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 model.get("arena"):
  467. if not has_access(
  468. user.id,
  469. type="read",
  470. access_control=model.get("info", {})
  471. .get("meta", {})
  472. .get("access_control", {}),
  473. ):
  474. raise HTTPException(
  475. status_code=403,
  476. detail="Model not found",
  477. )
  478. else:
  479. if not model_info:
  480. return JSONResponse(
  481. status_code=status.HTTP_404_NOT_FOUND,
  482. content={"detail": "Model not found"},
  483. )
  484. elif not (
  485. user.id == model_info.user_id
  486. or has_access(
  487. user.id, type="read", access_control=model_info.access_control
  488. )
  489. ):
  490. return JSONResponse(
  491. status_code=status.HTTP_403_FORBIDDEN,
  492. content={"detail": "User does not have access to the model"},
  493. )
  494. metadata = {
  495. "chat_id": body.pop("chat_id", None),
  496. "message_id": body.pop("id", None),
  497. "session_id": body.pop("session_id", None),
  498. "tool_ids": body.get("tool_ids", None),
  499. "files": body.get("files", None),
  500. }
  501. body["metadata"] = metadata
  502. extra_params = {
  503. "__event_emitter__": get_event_emitter(metadata),
  504. "__event_call__": get_event_call(metadata),
  505. "__user__": {
  506. "id": user.id,
  507. "email": user.email,
  508. "name": user.name,
  509. "role": user.role,
  510. },
  511. "__metadata__": metadata,
  512. }
  513. # Initialize data_items to store additional data to be sent to the client
  514. # Initialize contexts and citation
  515. data_items = []
  516. contexts = []
  517. citations = []
  518. try:
  519. body, flags = await chat_completion_filter_functions_handler(
  520. body, model, extra_params
  521. )
  522. except Exception as e:
  523. return JSONResponse(
  524. status_code=status.HTTP_400_BAD_REQUEST,
  525. content={"detail": str(e)},
  526. )
  527. tool_ids = body.pop("tool_ids", None)
  528. files = body.pop("files", None)
  529. metadata = {
  530. **metadata,
  531. "tool_ids": tool_ids,
  532. "files": files,
  533. }
  534. body["metadata"] = metadata
  535. try:
  536. body, flags = await chat_completion_tools_handler(
  537. body, user, models, extra_params
  538. )
  539. contexts.extend(flags.get("contexts", []))
  540. citations.extend(flags.get("citations", []))
  541. except Exception as e:
  542. log.exception(e)
  543. try:
  544. body, flags = await chat_completion_files_handler(body)
  545. contexts.extend(flags.get("contexts", []))
  546. citations.extend(flags.get("citations", []))
  547. except Exception as e:
  548. log.exception(e)
  549. # If context is not empty, insert it into the messages
  550. if len(contexts) > 0:
  551. context_string = "/n".join(contexts).strip()
  552. prompt = get_last_user_message(body["messages"])
  553. if prompt is None:
  554. raise Exception("No user message found")
  555. if (
  556. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  557. and context_string.strip() == ""
  558. ):
  559. log.debug(
  560. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  561. )
  562. # Workaround for Ollama 2.0+ system prompt issue
  563. # TODO: replace with add_or_update_system_message
  564. if model["owned_by"] == "ollama":
  565. body["messages"] = prepend_to_first_user_message_content(
  566. rag_template(
  567. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  568. ),
  569. body["messages"],
  570. )
  571. else:
  572. body["messages"] = add_or_update_system_message(
  573. rag_template(
  574. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  575. ),
  576. body["messages"],
  577. )
  578. # If there are citations, add them to the data_items
  579. if len(citations) > 0:
  580. data_items.append({"citations": citations})
  581. modified_body_bytes = json.dumps(body).encode("utf-8")
  582. # Replace the request body with the modified one
  583. request._body = modified_body_bytes
  584. # Set custom header to ensure content-length matches new body length
  585. request.headers.__dict__["_list"] = [
  586. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  587. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  588. ]
  589. response = await call_next(request)
  590. if not isinstance(response, StreamingResponse):
  591. return response
  592. content_type = response.headers["Content-Type"]
  593. is_openai = "text/event-stream" in content_type
  594. is_ollama = "application/x-ndjson" in content_type
  595. if not is_openai and not is_ollama:
  596. return response
  597. def wrap_item(item):
  598. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  599. async def stream_wrapper(original_generator, data_items):
  600. for item in data_items:
  601. yield wrap_item(json.dumps(item))
  602. async for data in original_generator:
  603. yield data
  604. return StreamingResponse(
  605. stream_wrapper(response.body_iterator, data_items),
  606. headers=dict(response.headers),
  607. )
  608. async def _receive(self, body: bytes):
  609. return {"type": "http.request", "body": body, "more_body": False}
  610. app.add_middleware(ChatCompletionMiddleware)
  611. ##################################
  612. #
  613. # Pipeline Middleware
  614. #
  615. ##################################
  616. def get_sorted_filters(model_id, models):
  617. filters = [
  618. model
  619. for model in models.values()
  620. if "pipeline" in model
  621. and "type" in model["pipeline"]
  622. and model["pipeline"]["type"] == "filter"
  623. and (
  624. model["pipeline"]["pipelines"] == ["*"]
  625. or any(
  626. model_id == target_model_id
  627. for target_model_id in model["pipeline"]["pipelines"]
  628. )
  629. )
  630. ]
  631. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  632. return sorted_filters
  633. def filter_pipeline(payload, user, models):
  634. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  635. model_id = payload["model"]
  636. sorted_filters = get_sorted_filters(model_id, models)
  637. model = models[model_id]
  638. if "pipeline" in model:
  639. sorted_filters.append(model)
  640. for filter in sorted_filters:
  641. r = None
  642. try:
  643. urlIdx = filter["urlIdx"]
  644. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  645. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  646. if key == "":
  647. continue
  648. headers = {"Authorization": f"Bearer {key}"}
  649. r = requests.post(
  650. f"{url}/{filter['id']}/filter/inlet",
  651. headers=headers,
  652. json={
  653. "user": user,
  654. "body": payload,
  655. },
  656. )
  657. r.raise_for_status()
  658. payload = r.json()
  659. except Exception as e:
  660. # Handle connection error here
  661. print(f"Connection error: {e}")
  662. if r is not None:
  663. res = r.json()
  664. if "detail" in res:
  665. raise Exception(r.status_code, res["detail"])
  666. return payload
  667. class PipelineMiddleware(BaseHTTPMiddleware):
  668. async def dispatch(self, request: Request, call_next):
  669. if not is_chat_completion_request(request):
  670. return await call_next(request)
  671. log.debug(f"request.url.path: {request.url.path}")
  672. # Read the original request body
  673. body = await request.body()
  674. # Decode body to string
  675. body_str = body.decode("utf-8")
  676. # Parse string to JSON
  677. data = json.loads(body_str) if body_str else {}
  678. try:
  679. user = get_current_user(
  680. request,
  681. get_http_authorization_cred(request.headers["Authorization"]),
  682. )
  683. except KeyError as e:
  684. if len(e.args) > 1:
  685. return JSONResponse(
  686. status_code=e.args[0],
  687. content={"detail": e.args[1]},
  688. )
  689. else:
  690. return JSONResponse(
  691. status_code=status.HTTP_401_UNAUTHORIZED,
  692. content={"detail": "Not authenticated"},
  693. )
  694. model_list = await get_all_models()
  695. models = {model["id"]: model for model in model_list}
  696. try:
  697. data = filter_pipeline(data, user, models)
  698. except Exception as e:
  699. if len(e.args) > 1:
  700. return JSONResponse(
  701. status_code=e.args[0],
  702. content={"detail": e.args[1]},
  703. )
  704. else:
  705. return JSONResponse(
  706. status_code=status.HTTP_400_BAD_REQUEST,
  707. content={"detail": str(e)},
  708. )
  709. modified_body_bytes = json.dumps(data).encode("utf-8")
  710. # Replace the request body with the modified one
  711. request._body = modified_body_bytes
  712. # Set custom header to ensure content-length matches new body length
  713. request.headers.__dict__["_list"] = [
  714. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  715. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  716. ]
  717. response = await call_next(request)
  718. return response
  719. async def _receive(self, body: bytes):
  720. return {"type": "http.request", "body": body, "more_body": False}
  721. app.add_middleware(PipelineMiddleware)
  722. from urllib.parse import urlencode, parse_qs, urlparse
  723. class RedirectMiddleware(BaseHTTPMiddleware):
  724. async def dispatch(self, request: Request, call_next):
  725. # Check if the request is a GET request
  726. if request.method == "GET":
  727. path = request.url.path
  728. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  729. # Check for the specific watch path and the presence of 'v' parameter
  730. if path.endswith("/watch") and "v" in query_params:
  731. video_id = query_params["v"][0] # Extract the first 'v' parameter
  732. encoded_video_id = urlencode({"youtube": video_id})
  733. redirect_url = f"/?{encoded_video_id}"
  734. return RedirectResponse(url=redirect_url)
  735. # Proceed with the normal flow of other requests
  736. response = await call_next(request)
  737. return response
  738. # Add the middleware to the app
  739. app.add_middleware(RedirectMiddleware)
  740. app.add_middleware(
  741. CORSMiddleware,
  742. allow_origins=CORS_ALLOW_ORIGIN,
  743. allow_credentials=True,
  744. allow_methods=["*"],
  745. allow_headers=["*"],
  746. )
  747. app.add_middleware(SecurityHeadersMiddleware)
  748. @app.middleware("http")
  749. async def commit_session_after_request(request: Request, call_next):
  750. response = await call_next(request)
  751. log.debug("Commit session after request")
  752. Session.commit()
  753. return response
  754. @app.middleware("http")
  755. async def check_url(request: Request, call_next):
  756. start_time = int(time.time())
  757. response = await call_next(request)
  758. process_time = int(time.time()) - start_time
  759. response.headers["X-Process-Time"] = str(process_time)
  760. return response
  761. @app.middleware("http")
  762. async def update_embedding_function(request: Request, call_next):
  763. response = await call_next(request)
  764. if "/embedding/update" in request.url.path:
  765. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  766. return response
  767. @app.middleware("http")
  768. async def inspect_websocket(request: Request, call_next):
  769. if (
  770. "/ws/socket.io" in request.url.path
  771. and request.query_params.get("transport") == "websocket"
  772. ):
  773. upgrade = (request.headers.get("Upgrade") or "").lower()
  774. connection = (request.headers.get("Connection") or "").lower().split(",")
  775. # Check that there's the correct headers for an upgrade, else reject the connection
  776. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  777. if upgrade != "websocket" or "upgrade" not in connection:
  778. return JSONResponse(
  779. status_code=status.HTTP_400_BAD_REQUEST,
  780. content={"detail": "Invalid WebSocket upgrade request"},
  781. )
  782. return await call_next(request)
  783. app.mount("/ws", socket_app)
  784. app.mount("/ollama", ollama_app)
  785. app.mount("/openai", openai_app)
  786. app.mount("/images/api/v1", images_app)
  787. app.mount("/audio/api/v1", audio_app)
  788. app.mount("/retrieval/api/v1", retrieval_app)
  789. app.mount("/api/v1", webui_app)
  790. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  791. async def get_all_base_models():
  792. open_webui_models = []
  793. openai_models = []
  794. ollama_models = []
  795. if app.state.config.ENABLE_OPENAI_API:
  796. openai_models = await get_openai_models()
  797. openai_models = openai_models["data"]
  798. if app.state.config.ENABLE_OLLAMA_API:
  799. ollama_models = await get_ollama_models()
  800. ollama_models = [
  801. {
  802. "id": model["model"],
  803. "name": model["name"],
  804. "object": "model",
  805. "created": int(time.time()),
  806. "owned_by": "ollama",
  807. "ollama": model,
  808. }
  809. for model in ollama_models["models"]
  810. ]
  811. open_webui_models = await get_open_webui_models()
  812. models = open_webui_models + openai_models + ollama_models
  813. return models
  814. @cached(ttl=1)
  815. async def get_all_models():
  816. models = await get_all_base_models()
  817. # If there are no models, return an empty list
  818. if len([model for model in models if not model.get("arena", False)]) == 0:
  819. return []
  820. global_action_ids = [
  821. function.id for function in Functions.get_global_action_functions()
  822. ]
  823. enabled_action_ids = [
  824. function.id
  825. for function in Functions.get_functions_by_type("action", active_only=True)
  826. ]
  827. custom_models = Models.get_all_models()
  828. for custom_model in custom_models:
  829. if custom_model.base_model_id is None:
  830. for model in models:
  831. if (
  832. custom_model.id == model["id"]
  833. or custom_model.id == model["id"].split(":")[0]
  834. ):
  835. if custom_model.is_active:
  836. model["name"] = custom_model.name
  837. model["info"] = custom_model.model_dump()
  838. action_ids = []
  839. if "info" in model and "meta" in model["info"]:
  840. action_ids.extend(
  841. model["info"]["meta"].get("actionIds", [])
  842. )
  843. model["action_ids"] = action_ids
  844. else:
  845. models.remove(model)
  846. elif custom_model.is_active and (
  847. custom_model.id not in [model["id"] for model in models]
  848. ):
  849. owned_by = "openai"
  850. pipe = None
  851. action_ids = []
  852. for model in models:
  853. if (
  854. custom_model.base_model_id == model["id"]
  855. or custom_model.base_model_id == model["id"].split(":")[0]
  856. ):
  857. owned_by = model["owned_by"]
  858. if "pipe" in model:
  859. pipe = model["pipe"]
  860. break
  861. if custom_model.meta:
  862. meta = custom_model.meta.model_dump()
  863. if "actionIds" in meta:
  864. action_ids.extend(meta["actionIds"])
  865. models.append(
  866. {
  867. "id": f"{custom_model.id}",
  868. "name": custom_model.name,
  869. "object": "model",
  870. "created": custom_model.created_at,
  871. "owned_by": owned_by,
  872. "info": custom_model.model_dump(),
  873. "preset": True,
  874. **({"pipe": pipe} if pipe is not None else {}),
  875. "action_ids": action_ids,
  876. }
  877. )
  878. # Process action_ids to get the actions
  879. def get_action_items_from_module(function, module):
  880. actions = []
  881. if hasattr(module, "actions"):
  882. actions = module.actions
  883. return [
  884. {
  885. "id": f"{function.id}.{action['id']}",
  886. "name": action.get("name", f"{function.name} ({action['id']})"),
  887. "description": function.meta.description,
  888. "icon_url": action.get(
  889. "icon_url", function.meta.manifest.get("icon_url", None)
  890. ),
  891. }
  892. for action in actions
  893. ]
  894. else:
  895. return [
  896. {
  897. "id": function.id,
  898. "name": function.name,
  899. "description": function.meta.description,
  900. "icon_url": function.meta.manifest.get("icon_url", None),
  901. }
  902. ]
  903. def get_function_module_by_id(function_id):
  904. if function_id in webui_app.state.FUNCTIONS:
  905. function_module = webui_app.state.FUNCTIONS[function_id]
  906. else:
  907. function_module, _, _ = load_function_module_by_id(function_id)
  908. webui_app.state.FUNCTIONS[function_id] = function_module
  909. for model in models:
  910. action_ids = [
  911. action_id
  912. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  913. if action_id in enabled_action_ids
  914. ]
  915. model["actions"] = []
  916. for action_id in action_ids:
  917. action_function = Functions.get_function_by_id(action_id)
  918. if action_function is None:
  919. raise Exception(f"Action not found: {action_id}")
  920. function_module = get_function_module_by_id(action_id)
  921. model["actions"].extend(
  922. get_action_items_from_module(action_function, function_module)
  923. )
  924. return models
  925. @app.get("/api/models")
  926. async def get_models(user=Depends(get_verified_user)):
  927. models = await get_all_models()
  928. # Filter out filter pipelines
  929. models = [
  930. model
  931. for model in models
  932. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  933. ]
  934. # Filter out models that the user does not have access to
  935. if user.role == "user":
  936. filtered_models = []
  937. for model in models:
  938. if model.get("arena"):
  939. if has_access(
  940. user.id,
  941. type="read",
  942. access_control=model.get("info", {})
  943. .get("meta", {})
  944. .get("access_control", {}),
  945. ):
  946. filtered_models.append(model)
  947. continue
  948. model_info = Models.get_model_by_id(model["id"])
  949. if model_info:
  950. if user.id == model_info.user_id or has_access(
  951. user.id, type="read", access_control=model_info.access_control
  952. ):
  953. filtered_models.append(model)
  954. models = filtered_models
  955. return {"data": models}
  956. @app.get("/api/models/base")
  957. async def get_base_models(user=Depends(get_admin_user)):
  958. models = await get_all_base_models()
  959. # Filter out arena models
  960. models = [model for model in models if not model.get("arena", False)]
  961. return {"data": models}
  962. @app.post("/api/chat/completions")
  963. async def generate_chat_completions(
  964. form_data: dict, user=Depends(get_verified_user), bypass_filter: bool = False
  965. ):
  966. model_list = await get_all_models()
  967. models = {model["id"]: model for model in model_list}
  968. model_id = form_data["model"]
  969. if model_id not in models:
  970. raise HTTPException(
  971. status_code=status.HTTP_404_NOT_FOUND,
  972. detail="Model not found",
  973. )
  974. model = models[model_id]
  975. # Check if user has access to the model
  976. if not bypass_filter and user.role == "user":
  977. if model.get("arena"):
  978. if not has_access(
  979. user.id,
  980. type="read",
  981. access_control=model.get("info", {})
  982. .get("meta", {})
  983. .get("access_control", {}),
  984. ):
  985. raise HTTPException(
  986. status_code=403,
  987. detail="Model not found",
  988. )
  989. else:
  990. model_info = Models.get_model_by_id(model_id)
  991. if not model_info:
  992. raise HTTPException(
  993. status_code=404,
  994. detail="Model not found",
  995. )
  996. elif not (
  997. user.id == model_info.user_id
  998. or has_access(
  999. user.id, type="read", access_control=model_info.access_control
  1000. )
  1001. ):
  1002. raise HTTPException(
  1003. status_code=403,
  1004. detail="Model not found",
  1005. )
  1006. if model["owned_by"] == "arena":
  1007. model_ids = model.get("info", {}).get("meta", {}).get("model_ids")
  1008. filter_mode = model.get("info", {}).get("meta", {}).get("filter_mode")
  1009. if model_ids and filter_mode == "exclude":
  1010. model_ids = [
  1011. model["id"]
  1012. for model in await get_all_models()
  1013. if model.get("owned_by") != "arena" and model["id"] not in model_ids
  1014. ]
  1015. selected_model_id = None
  1016. if isinstance(model_ids, list) and model_ids:
  1017. selected_model_id = random.choice(model_ids)
  1018. else:
  1019. model_ids = [
  1020. model["id"]
  1021. for model in await get_all_models()
  1022. if model.get("owned_by") != "arena"
  1023. ]
  1024. selected_model_id = random.choice(model_ids)
  1025. form_data["model"] = selected_model_id
  1026. if form_data.get("stream") == True:
  1027. async def stream_wrapper(stream):
  1028. yield f"data: {json.dumps({'selected_model_id': selected_model_id})}\n\n"
  1029. async for chunk in stream:
  1030. yield chunk
  1031. response = await generate_chat_completions(
  1032. form_data, user, bypass_filter=True
  1033. )
  1034. return StreamingResponse(
  1035. stream_wrapper(response.body_iterator), media_type="text/event-stream"
  1036. )
  1037. else:
  1038. return {
  1039. **(
  1040. await generate_chat_completions(form_data, user, bypass_filter=True)
  1041. ),
  1042. "selected_model_id": selected_model_id,
  1043. }
  1044. if model.get("pipe"):
  1045. # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
  1046. return await generate_function_chat_completion(
  1047. form_data, user=user, models=models
  1048. )
  1049. if model["owned_by"] == "ollama":
  1050. # Using /ollama/api/chat endpoint
  1051. form_data = convert_payload_openai_to_ollama(form_data)
  1052. form_data = GenerateChatCompletionForm(**form_data)
  1053. response = await generate_ollama_chat_completion(
  1054. form_data=form_data, user=user, bypass_filter=bypass_filter
  1055. )
  1056. if form_data.stream:
  1057. response.headers["content-type"] = "text/event-stream"
  1058. return StreamingResponse(
  1059. convert_streaming_response_ollama_to_openai(response),
  1060. headers=dict(response.headers),
  1061. )
  1062. else:
  1063. return convert_response_ollama_to_openai(response)
  1064. else:
  1065. return await generate_openai_chat_completion(
  1066. form_data, user=user, bypass_filter=bypass_filter
  1067. )
  1068. @app.post("/api/chat/completed")
  1069. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  1070. model_list = await get_all_models()
  1071. models = {model["id"]: model for model in model_list}
  1072. data = form_data
  1073. model_id = data["model"]
  1074. if model_id not in models:
  1075. raise HTTPException(
  1076. status_code=status.HTTP_404_NOT_FOUND,
  1077. detail="Model not found",
  1078. )
  1079. model = models[model_id]
  1080. sorted_filters = get_sorted_filters(model_id, models)
  1081. if "pipeline" in model:
  1082. sorted_filters = [model] + sorted_filters
  1083. for filter in sorted_filters:
  1084. r = None
  1085. try:
  1086. urlIdx = filter["urlIdx"]
  1087. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1088. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1089. if key != "":
  1090. headers = {"Authorization": f"Bearer {key}"}
  1091. r = requests.post(
  1092. f"{url}/{filter['id']}/filter/outlet",
  1093. headers=headers,
  1094. json={
  1095. "user": {
  1096. "id": user.id,
  1097. "name": user.name,
  1098. "email": user.email,
  1099. "role": user.role,
  1100. },
  1101. "body": data,
  1102. },
  1103. )
  1104. r.raise_for_status()
  1105. data = r.json()
  1106. except Exception as e:
  1107. # Handle connection error here
  1108. print(f"Connection error: {e}")
  1109. if r is not None:
  1110. try:
  1111. res = r.json()
  1112. if "detail" in res:
  1113. return JSONResponse(
  1114. status_code=r.status_code,
  1115. content=res,
  1116. )
  1117. except Exception:
  1118. pass
  1119. else:
  1120. pass
  1121. __event_emitter__ = get_event_emitter(
  1122. {
  1123. "chat_id": data["chat_id"],
  1124. "message_id": data["id"],
  1125. "session_id": data["session_id"],
  1126. }
  1127. )
  1128. __event_call__ = get_event_call(
  1129. {
  1130. "chat_id": data["chat_id"],
  1131. "message_id": data["id"],
  1132. "session_id": data["session_id"],
  1133. }
  1134. )
  1135. def get_priority(function_id):
  1136. function = Functions.get_function_by_id(function_id)
  1137. if function is not None and hasattr(function, "valves"):
  1138. # TODO: Fix FunctionModel to include vavles
  1139. return (function.valves if function.valves else {}).get("priority", 0)
  1140. return 0
  1141. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  1142. if "info" in model and "meta" in model["info"]:
  1143. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  1144. filter_ids = list(set(filter_ids))
  1145. enabled_filter_ids = [
  1146. function.id
  1147. for function in Functions.get_functions_by_type("filter", active_only=True)
  1148. ]
  1149. filter_ids = [
  1150. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  1151. ]
  1152. # Sort filter_ids by priority, using the get_priority function
  1153. filter_ids.sort(key=get_priority)
  1154. for filter_id in filter_ids:
  1155. filter = Functions.get_function_by_id(filter_id)
  1156. if not filter:
  1157. continue
  1158. if filter_id in webui_app.state.FUNCTIONS:
  1159. function_module = webui_app.state.FUNCTIONS[filter_id]
  1160. else:
  1161. function_module, _, _ = load_function_module_by_id(filter_id)
  1162. webui_app.state.FUNCTIONS[filter_id] = function_module
  1163. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1164. valves = Functions.get_function_valves_by_id(filter_id)
  1165. function_module.valves = function_module.Valves(
  1166. **(valves if valves else {})
  1167. )
  1168. if not hasattr(function_module, "outlet"):
  1169. continue
  1170. try:
  1171. outlet = function_module.outlet
  1172. # Get the signature of the function
  1173. sig = inspect.signature(outlet)
  1174. params = {"body": data}
  1175. # Extra parameters to be passed to the function
  1176. extra_params = {
  1177. "__model__": model,
  1178. "__id__": filter_id,
  1179. "__event_emitter__": __event_emitter__,
  1180. "__event_call__": __event_call__,
  1181. }
  1182. # Add extra params in contained in function signature
  1183. for key, value in extra_params.items():
  1184. if key in sig.parameters:
  1185. params[key] = value
  1186. if "__user__" in sig.parameters:
  1187. __user__ = {
  1188. "id": user.id,
  1189. "email": user.email,
  1190. "name": user.name,
  1191. "role": user.role,
  1192. }
  1193. try:
  1194. if hasattr(function_module, "UserValves"):
  1195. __user__["valves"] = function_module.UserValves(
  1196. **Functions.get_user_valves_by_id_and_user_id(
  1197. filter_id, user.id
  1198. )
  1199. )
  1200. except Exception as e:
  1201. print(e)
  1202. params = {**params, "__user__": __user__}
  1203. if inspect.iscoroutinefunction(outlet):
  1204. data = await outlet(**params)
  1205. else:
  1206. data = outlet(**params)
  1207. except Exception as e:
  1208. print(f"Error: {e}")
  1209. return JSONResponse(
  1210. status_code=status.HTTP_400_BAD_REQUEST,
  1211. content={"detail": str(e)},
  1212. )
  1213. return data
  1214. @app.post("/api/chat/actions/{action_id}")
  1215. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1216. if "." in action_id:
  1217. action_id, sub_action_id = action_id.split(".")
  1218. else:
  1219. sub_action_id = None
  1220. action = Functions.get_function_by_id(action_id)
  1221. if not action:
  1222. raise HTTPException(
  1223. status_code=status.HTTP_404_NOT_FOUND,
  1224. detail="Action not found",
  1225. )
  1226. model_list = await get_all_models()
  1227. models = {model["id"]: model for model in model_list}
  1228. data = form_data
  1229. model_id = data["model"]
  1230. if model_id not in models:
  1231. raise HTTPException(
  1232. status_code=status.HTTP_404_NOT_FOUND,
  1233. detail="Model not found",
  1234. )
  1235. model = models[model_id]
  1236. __event_emitter__ = get_event_emitter(
  1237. {
  1238. "chat_id": data["chat_id"],
  1239. "message_id": data["id"],
  1240. "session_id": data["session_id"],
  1241. }
  1242. )
  1243. __event_call__ = get_event_call(
  1244. {
  1245. "chat_id": data["chat_id"],
  1246. "message_id": data["id"],
  1247. "session_id": data["session_id"],
  1248. }
  1249. )
  1250. if action_id in webui_app.state.FUNCTIONS:
  1251. function_module = webui_app.state.FUNCTIONS[action_id]
  1252. else:
  1253. function_module, _, _ = load_function_module_by_id(action_id)
  1254. webui_app.state.FUNCTIONS[action_id] = function_module
  1255. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1256. valves = Functions.get_function_valves_by_id(action_id)
  1257. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1258. if hasattr(function_module, "action"):
  1259. try:
  1260. action = function_module.action
  1261. # Get the signature of the function
  1262. sig = inspect.signature(action)
  1263. params = {"body": data}
  1264. # Extra parameters to be passed to the function
  1265. extra_params = {
  1266. "__model__": model,
  1267. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1268. "__event_emitter__": __event_emitter__,
  1269. "__event_call__": __event_call__,
  1270. }
  1271. # Add extra params in contained in function signature
  1272. for key, value in extra_params.items():
  1273. if key in sig.parameters:
  1274. params[key] = value
  1275. if "__user__" in sig.parameters:
  1276. __user__ = {
  1277. "id": user.id,
  1278. "email": user.email,
  1279. "name": user.name,
  1280. "role": user.role,
  1281. }
  1282. try:
  1283. if hasattr(function_module, "UserValves"):
  1284. __user__["valves"] = function_module.UserValves(
  1285. **Functions.get_user_valves_by_id_and_user_id(
  1286. action_id, user.id
  1287. )
  1288. )
  1289. except Exception as e:
  1290. print(e)
  1291. params = {**params, "__user__": __user__}
  1292. if inspect.iscoroutinefunction(action):
  1293. data = await action(**params)
  1294. else:
  1295. data = action(**params)
  1296. except Exception as e:
  1297. print(f"Error: {e}")
  1298. return JSONResponse(
  1299. status_code=status.HTTP_400_BAD_REQUEST,
  1300. content={"detail": str(e)},
  1301. )
  1302. return data
  1303. ##################################
  1304. #
  1305. # Task Endpoints
  1306. #
  1307. ##################################
  1308. # TODO: Refactor task API endpoints below into a separate file
  1309. @app.get("/api/task/config")
  1310. async def get_task_config(user=Depends(get_verified_user)):
  1311. return {
  1312. "TASK_MODEL": app.state.config.TASK_MODEL,
  1313. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1314. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1315. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1316. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1317. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1318. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1319. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1320. }
  1321. class TaskConfigForm(BaseModel):
  1322. TASK_MODEL: Optional[str]
  1323. TASK_MODEL_EXTERNAL: Optional[str]
  1324. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1325. TAGS_GENERATION_PROMPT_TEMPLATE: str
  1326. ENABLE_TAGS_GENERATION: bool
  1327. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1328. ENABLE_SEARCH_QUERY: bool
  1329. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1330. @app.post("/api/task/config/update")
  1331. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1332. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1333. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1334. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1335. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1336. )
  1337. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = (
  1338. form_data.TAGS_GENERATION_PROMPT_TEMPLATE
  1339. )
  1340. app.state.config.ENABLE_TAGS_GENERATION = form_data.ENABLE_TAGS_GENERATION
  1341. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1342. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1343. )
  1344. app.state.config.ENABLE_SEARCH_QUERY = form_data.ENABLE_SEARCH_QUERY
  1345. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1346. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1347. )
  1348. return {
  1349. "TASK_MODEL": app.state.config.TASK_MODEL,
  1350. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1351. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1352. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1353. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1354. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1355. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1356. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1357. }
  1358. @app.post("/api/task/title/completions")
  1359. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1360. print("generate_title")
  1361. model_list = await get_all_models()
  1362. models = {model["id"]: model for model in model_list}
  1363. model_id = form_data["model"]
  1364. if model_id not in models:
  1365. raise HTTPException(
  1366. status_code=status.HTTP_404_NOT_FOUND,
  1367. detail="Model not found",
  1368. )
  1369. # Check if the user has a custom task model
  1370. # If the user has a custom task model, use that model
  1371. task_model_id = get_task_model_id(
  1372. model_id,
  1373. app.state.config.TASK_MODEL,
  1374. app.state.config.TASK_MODEL_EXTERNAL,
  1375. models,
  1376. )
  1377. print(task_model_id)
  1378. model = models[task_model_id]
  1379. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1380. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1381. else:
  1382. 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.
  1383. Examples of titles:
  1384. 📉 Stock Market Trends
  1385. 🍪 Perfect Chocolate Chip Recipe
  1386. Evolution of Music Streaming
  1387. Remote Work Productivity Tips
  1388. Artificial Intelligence in Healthcare
  1389. 🎮 Video Game Development Insights
  1390. <chat_history>
  1391. {{MESSAGES:END:2}}
  1392. </chat_history>"""
  1393. content = title_generation_template(
  1394. template,
  1395. form_data["messages"],
  1396. {
  1397. "name": user.name,
  1398. "location": user.info.get("location") if user.info else None,
  1399. },
  1400. )
  1401. payload = {
  1402. "model": task_model_id,
  1403. "messages": [{"role": "user", "content": content}],
  1404. "stream": False,
  1405. **(
  1406. {"max_tokens": 50}
  1407. if models[task_model_id]["owned_by"] == "ollama"
  1408. else {
  1409. "max_completion_tokens": 50,
  1410. }
  1411. ),
  1412. "chat_id": form_data.get("chat_id", None),
  1413. "metadata": {"task": str(TASKS.TITLE_GENERATION), "task_body": form_data},
  1414. }
  1415. log.debug(payload)
  1416. # Handle pipeline filters
  1417. try:
  1418. payload = filter_pipeline(payload, user, models)
  1419. except Exception as e:
  1420. if len(e.args) > 1:
  1421. return JSONResponse(
  1422. status_code=e.args[0],
  1423. content={"detail": e.args[1]},
  1424. )
  1425. else:
  1426. return JSONResponse(
  1427. status_code=status.HTTP_400_BAD_REQUEST,
  1428. content={"detail": str(e)},
  1429. )
  1430. if "chat_id" in payload:
  1431. del payload["chat_id"]
  1432. return await generate_chat_completions(form_data=payload, user=user)
  1433. @app.post("/api/task/tags/completions")
  1434. async def generate_chat_tags(form_data: dict, user=Depends(get_verified_user)):
  1435. print("generate_chat_tags")
  1436. if not app.state.config.ENABLE_TAGS_GENERATION:
  1437. return JSONResponse(
  1438. status_code=status.HTTP_200_OK,
  1439. content={"detail": "Tags generation is disabled"},
  1440. )
  1441. model_list = await get_all_models()
  1442. models = {model["id"]: model for model in model_list}
  1443. model_id = form_data["model"]
  1444. if model_id not in models:
  1445. raise HTTPException(
  1446. status_code=status.HTTP_404_NOT_FOUND,
  1447. detail="Model not found",
  1448. )
  1449. # Check if the user has a custom task model
  1450. # If the user has a custom task model, use that model
  1451. task_model_id = get_task_model_id(
  1452. model_id,
  1453. app.state.config.TASK_MODEL,
  1454. app.state.config.TASK_MODEL_EXTERNAL,
  1455. models,
  1456. )
  1457. print(task_model_id)
  1458. if app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE != "":
  1459. template = app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE
  1460. else:
  1461. template = """### Task:
  1462. Generate 1-3 broad tags categorizing the main themes of the chat history, along with 1-3 more specific subtopic tags.
  1463. ### Guidelines:
  1464. - Start with high-level domains (e.g. Science, Technology, Philosophy, Arts, Politics, Business, Health, Sports, Entertainment, Education)
  1465. - Consider including relevant subfields/subdomains if they are strongly represented throughout the conversation
  1466. - If content is too short (less than 3 messages) or too diverse, use only ["General"]
  1467. - Use the chat's primary language; default to English if multilingual
  1468. - Prioritize accuracy over specificity
  1469. ### Output:
  1470. JSON format: { "tags": ["tag1", "tag2", "tag3"] }
  1471. ### Chat History:
  1472. <chat_history>
  1473. {{MESSAGES:END:6}}
  1474. </chat_history>"""
  1475. content = tags_generation_template(
  1476. template, form_data["messages"], {"name": user.name}
  1477. )
  1478. payload = {
  1479. "model": task_model_id,
  1480. "messages": [{"role": "user", "content": content}],
  1481. "stream": False,
  1482. "metadata": {"task": str(TASKS.TAGS_GENERATION), "task_body": form_data},
  1483. }
  1484. log.debug(payload)
  1485. # Handle pipeline filters
  1486. try:
  1487. payload = filter_pipeline(payload, user, models)
  1488. except Exception as e:
  1489. if len(e.args) > 1:
  1490. return JSONResponse(
  1491. status_code=e.args[0],
  1492. content={"detail": e.args[1]},
  1493. )
  1494. else:
  1495. return JSONResponse(
  1496. status_code=status.HTTP_400_BAD_REQUEST,
  1497. content={"detail": str(e)},
  1498. )
  1499. if "chat_id" in payload:
  1500. del payload["chat_id"]
  1501. return await generate_chat_completions(form_data=payload, user=user)
  1502. @app.post("/api/task/query/completions")
  1503. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1504. print("generate_search_query")
  1505. if not app.state.config.ENABLE_SEARCH_QUERY:
  1506. raise HTTPException(
  1507. status_code=status.HTTP_400_BAD_REQUEST,
  1508. detail=f"Search query generation is disabled",
  1509. )
  1510. model_list = await get_all_models()
  1511. models = {model["id"]: model for model in model_list}
  1512. model_id = form_data["model"]
  1513. if model_id not in models:
  1514. raise HTTPException(
  1515. status_code=status.HTTP_404_NOT_FOUND,
  1516. detail="Model not found",
  1517. )
  1518. # Check if the user has a custom task model
  1519. # If the user has a custom task model, use that model
  1520. task_model_id = get_task_model_id(
  1521. model_id,
  1522. app.state.config.TASK_MODEL,
  1523. app.state.config.TASK_MODEL_EXTERNAL,
  1524. models,
  1525. )
  1526. print(task_model_id)
  1527. model = models[task_model_id]
  1528. if app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE != "":
  1529. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1530. else:
  1531. 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}}.
  1532. User Message:
  1533. {{prompt:end:4000}}
  1534. Interaction History:
  1535. {{MESSAGES:END:6}}
  1536. Search Query:"""
  1537. content = search_query_generation_template(
  1538. template, form_data["messages"], {"name": user.name}
  1539. )
  1540. payload = {
  1541. "model": task_model_id,
  1542. "messages": [{"role": "user", "content": content}],
  1543. "stream": False,
  1544. **(
  1545. {"max_tokens": 30}
  1546. if models[task_model_id]["owned_by"] == "ollama"
  1547. else {
  1548. "max_completion_tokens": 30,
  1549. }
  1550. ),
  1551. "metadata": {"task": str(TASKS.QUERY_GENERATION), "task_body": form_data},
  1552. }
  1553. log.debug(payload)
  1554. # Handle pipeline filters
  1555. try:
  1556. payload = filter_pipeline(payload, user, models)
  1557. except Exception as e:
  1558. if len(e.args) > 1:
  1559. return JSONResponse(
  1560. status_code=e.args[0],
  1561. content={"detail": e.args[1]},
  1562. )
  1563. else:
  1564. return JSONResponse(
  1565. status_code=status.HTTP_400_BAD_REQUEST,
  1566. content={"detail": str(e)},
  1567. )
  1568. if "chat_id" in payload:
  1569. del payload["chat_id"]
  1570. return await generate_chat_completions(form_data=payload, user=user)
  1571. @app.post("/api/task/emoji/completions")
  1572. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1573. print("generate_emoji")
  1574. model_list = await get_all_models()
  1575. models = {model["id"]: model for model in model_list}
  1576. model_id = form_data["model"]
  1577. if model_id not in models:
  1578. raise HTTPException(
  1579. status_code=status.HTTP_404_NOT_FOUND,
  1580. detail="Model not found",
  1581. )
  1582. # Check if the user has a custom task model
  1583. # If the user has a custom task model, use that model
  1584. task_model_id = get_task_model_id(
  1585. model_id,
  1586. app.state.config.TASK_MODEL,
  1587. app.state.config.TASK_MODEL_EXTERNAL,
  1588. models,
  1589. )
  1590. print(task_model_id)
  1591. model = models[task_model_id]
  1592. template = '''
  1593. 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., 😊, 😢, 😡, 😱).
  1594. Message: """{{prompt}}"""
  1595. '''
  1596. content = emoji_generation_template(
  1597. template,
  1598. form_data["prompt"],
  1599. {
  1600. "name": user.name,
  1601. "location": user.info.get("location") if user.info else None,
  1602. },
  1603. )
  1604. payload = {
  1605. "model": task_model_id,
  1606. "messages": [{"role": "user", "content": content}],
  1607. "stream": False,
  1608. **(
  1609. {"max_tokens": 4}
  1610. if models[task_model_id]["owned_by"] == "ollama"
  1611. else {
  1612. "max_completion_tokens": 4,
  1613. }
  1614. ),
  1615. "chat_id": form_data.get("chat_id", None),
  1616. "metadata": {"task": str(TASKS.EMOJI_GENERATION), "task_body": form_data},
  1617. }
  1618. log.debug(payload)
  1619. # Handle pipeline filters
  1620. try:
  1621. payload = filter_pipeline(payload, user, models)
  1622. except Exception as e:
  1623. if len(e.args) > 1:
  1624. return JSONResponse(
  1625. status_code=e.args[0],
  1626. content={"detail": e.args[1]},
  1627. )
  1628. else:
  1629. return JSONResponse(
  1630. status_code=status.HTTP_400_BAD_REQUEST,
  1631. content={"detail": str(e)},
  1632. )
  1633. if "chat_id" in payload:
  1634. del payload["chat_id"]
  1635. return await generate_chat_completions(form_data=payload, user=user)
  1636. @app.post("/api/task/moa/completions")
  1637. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1638. print("generate_moa_response")
  1639. model_list = await get_all_models()
  1640. models = {model["id"]: model for model in model_list}
  1641. model_id = form_data["model"]
  1642. if model_id not in models:
  1643. raise HTTPException(
  1644. status_code=status.HTTP_404_NOT_FOUND,
  1645. detail="Model not found",
  1646. )
  1647. # Check if the user has a custom task model
  1648. # If the user has a custom task model, use that model
  1649. task_model_id = get_task_model_id(
  1650. model_id,
  1651. app.state.config.TASK_MODEL,
  1652. app.state.config.TASK_MODEL_EXTERNAL,
  1653. models,
  1654. )
  1655. print(task_model_id)
  1656. model = models[task_model_id]
  1657. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1658. 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.
  1659. Responses from models: {{responses}}"""
  1660. content = moa_response_generation_template(
  1661. template,
  1662. form_data["prompt"],
  1663. form_data["responses"],
  1664. )
  1665. payload = {
  1666. "model": task_model_id,
  1667. "messages": [{"role": "user", "content": content}],
  1668. "stream": form_data.get("stream", False),
  1669. "chat_id": form_data.get("chat_id", None),
  1670. "metadata": {
  1671. "task": str(TASKS.MOA_RESPONSE_GENERATION),
  1672. "task_body": form_data,
  1673. },
  1674. }
  1675. log.debug(payload)
  1676. try:
  1677. payload = filter_pipeline(payload, user, models)
  1678. except Exception as e:
  1679. if len(e.args) > 1:
  1680. return JSONResponse(
  1681. status_code=e.args[0],
  1682. content={"detail": e.args[1]},
  1683. )
  1684. else:
  1685. return JSONResponse(
  1686. status_code=status.HTTP_400_BAD_REQUEST,
  1687. content={"detail": str(e)},
  1688. )
  1689. if "chat_id" in payload:
  1690. del payload["chat_id"]
  1691. return await generate_chat_completions(form_data=payload, user=user)
  1692. ##################################
  1693. #
  1694. # Pipelines Endpoints
  1695. #
  1696. ##################################
  1697. # TODO: Refactor pipelines API endpoints below into a separate file
  1698. @app.get("/api/pipelines/list")
  1699. async def get_pipelines_list(user=Depends(get_admin_user)):
  1700. responses = await get_openai_models_responses()
  1701. print(responses)
  1702. urlIdxs = [
  1703. idx
  1704. for idx, response in enumerate(responses)
  1705. if response is not None and "pipelines" in response
  1706. ]
  1707. return {
  1708. "data": [
  1709. {
  1710. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1711. "idx": urlIdx,
  1712. }
  1713. for urlIdx in urlIdxs
  1714. ]
  1715. }
  1716. @app.post("/api/pipelines/upload")
  1717. async def upload_pipeline(
  1718. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1719. ):
  1720. print("upload_pipeline", urlIdx, file.filename)
  1721. # Check if the uploaded file is a python file
  1722. if not (file.filename and file.filename.endswith(".py")):
  1723. raise HTTPException(
  1724. status_code=status.HTTP_400_BAD_REQUEST,
  1725. detail="Only Python (.py) files are allowed.",
  1726. )
  1727. upload_folder = f"{CACHE_DIR}/pipelines"
  1728. os.makedirs(upload_folder, exist_ok=True)
  1729. file_path = os.path.join(upload_folder, file.filename)
  1730. r = None
  1731. try:
  1732. # Save the uploaded file
  1733. with open(file_path, "wb") as buffer:
  1734. shutil.copyfileobj(file.file, buffer)
  1735. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1736. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1737. headers = {"Authorization": f"Bearer {key}"}
  1738. with open(file_path, "rb") as f:
  1739. files = {"file": f}
  1740. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1741. r.raise_for_status()
  1742. data = r.json()
  1743. return {**data}
  1744. except Exception as e:
  1745. # Handle connection error here
  1746. print(f"Connection error: {e}")
  1747. detail = "Pipeline not found"
  1748. status_code = status.HTTP_404_NOT_FOUND
  1749. if r is not None:
  1750. status_code = r.status_code
  1751. try:
  1752. res = r.json()
  1753. if "detail" in res:
  1754. detail = res["detail"]
  1755. except Exception:
  1756. pass
  1757. raise HTTPException(
  1758. status_code=status_code,
  1759. detail=detail,
  1760. )
  1761. finally:
  1762. # Ensure the file is deleted after the upload is completed or on failure
  1763. if os.path.exists(file_path):
  1764. os.remove(file_path)
  1765. class AddPipelineForm(BaseModel):
  1766. url: str
  1767. urlIdx: int
  1768. @app.post("/api/pipelines/add")
  1769. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1770. r = None
  1771. try:
  1772. urlIdx = form_data.urlIdx
  1773. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1774. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1775. headers = {"Authorization": f"Bearer {key}"}
  1776. r = requests.post(
  1777. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1778. )
  1779. r.raise_for_status()
  1780. data = r.json()
  1781. return {**data}
  1782. except Exception as e:
  1783. # Handle connection error here
  1784. print(f"Connection error: {e}")
  1785. detail = "Pipeline not found"
  1786. if r is not None:
  1787. try:
  1788. res = r.json()
  1789. if "detail" in res:
  1790. detail = res["detail"]
  1791. except Exception:
  1792. pass
  1793. raise HTTPException(
  1794. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1795. detail=detail,
  1796. )
  1797. class DeletePipelineForm(BaseModel):
  1798. id: str
  1799. urlIdx: int
  1800. @app.delete("/api/pipelines/delete")
  1801. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1802. r = None
  1803. try:
  1804. urlIdx = form_data.urlIdx
  1805. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1806. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1807. headers = {"Authorization": f"Bearer {key}"}
  1808. r = requests.delete(
  1809. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1810. )
  1811. r.raise_for_status()
  1812. data = r.json()
  1813. return {**data}
  1814. except Exception as e:
  1815. # Handle connection error here
  1816. print(f"Connection error: {e}")
  1817. detail = "Pipeline not found"
  1818. if r is not None:
  1819. try:
  1820. res = r.json()
  1821. if "detail" in res:
  1822. detail = res["detail"]
  1823. except Exception:
  1824. pass
  1825. raise HTTPException(
  1826. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1827. detail=detail,
  1828. )
  1829. @app.get("/api/pipelines")
  1830. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1831. r = None
  1832. try:
  1833. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1834. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1835. headers = {"Authorization": f"Bearer {key}"}
  1836. r = requests.get(f"{url}/pipelines", headers=headers)
  1837. r.raise_for_status()
  1838. data = r.json()
  1839. return {**data}
  1840. except Exception as e:
  1841. # Handle connection error here
  1842. print(f"Connection error: {e}")
  1843. detail = "Pipeline not found"
  1844. if r is not None:
  1845. try:
  1846. res = r.json()
  1847. if "detail" in res:
  1848. detail = res["detail"]
  1849. except Exception:
  1850. pass
  1851. raise HTTPException(
  1852. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1853. detail=detail,
  1854. )
  1855. @app.get("/api/pipelines/{pipeline_id}/valves")
  1856. async def get_pipeline_valves(
  1857. urlIdx: Optional[int],
  1858. pipeline_id: str,
  1859. user=Depends(get_admin_user),
  1860. ):
  1861. r = None
  1862. try:
  1863. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1864. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1865. headers = {"Authorization": f"Bearer {key}"}
  1866. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1867. r.raise_for_status()
  1868. data = r.json()
  1869. return {**data}
  1870. except Exception as e:
  1871. # Handle connection error here
  1872. print(f"Connection error: {e}")
  1873. detail = "Pipeline not found"
  1874. if r is not None:
  1875. try:
  1876. res = r.json()
  1877. if "detail" in res:
  1878. detail = res["detail"]
  1879. except Exception:
  1880. pass
  1881. raise HTTPException(
  1882. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1883. detail=detail,
  1884. )
  1885. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1886. async def get_pipeline_valves_spec(
  1887. urlIdx: Optional[int],
  1888. pipeline_id: str,
  1889. user=Depends(get_admin_user),
  1890. ):
  1891. r = None
  1892. try:
  1893. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1894. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1895. headers = {"Authorization": f"Bearer {key}"}
  1896. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  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. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1916. async def update_pipeline_valves(
  1917. urlIdx: Optional[int],
  1918. pipeline_id: str,
  1919. form_data: dict,
  1920. user=Depends(get_admin_user),
  1921. ):
  1922. r = None
  1923. try:
  1924. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1925. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1926. headers = {"Authorization": f"Bearer {key}"}
  1927. r = requests.post(
  1928. f"{url}/{pipeline_id}/valves/update",
  1929. headers=headers,
  1930. json={**form_data},
  1931. )
  1932. r.raise_for_status()
  1933. data = r.json()
  1934. return {**data}
  1935. except Exception as e:
  1936. # Handle connection error here
  1937. print(f"Connection error: {e}")
  1938. detail = "Pipeline not found"
  1939. if r is not None:
  1940. try:
  1941. res = r.json()
  1942. if "detail" in res:
  1943. detail = res["detail"]
  1944. except Exception:
  1945. pass
  1946. raise HTTPException(
  1947. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1948. detail=detail,
  1949. )
  1950. ##################################
  1951. #
  1952. # Config Endpoints
  1953. #
  1954. ##################################
  1955. @app.get("/api/config")
  1956. async def get_app_config(request: Request):
  1957. user = None
  1958. if "token" in request.cookies:
  1959. token = request.cookies.get("token")
  1960. try:
  1961. data = decode_token(token)
  1962. except Exception as e:
  1963. log.debug(e)
  1964. raise HTTPException(
  1965. status_code=status.HTTP_401_UNAUTHORIZED,
  1966. detail="Invalid token",
  1967. )
  1968. if data is not None and "id" in data:
  1969. user = Users.get_user_by_id(data["id"])
  1970. onboarding = False
  1971. if user is None:
  1972. user_count = Users.get_num_users()
  1973. onboarding = user_count == 0
  1974. return {
  1975. **({"onboarding": True} if onboarding else {}),
  1976. "status": True,
  1977. "name": WEBUI_NAME,
  1978. "version": VERSION,
  1979. "default_locale": str(DEFAULT_LOCALE),
  1980. "oauth": {
  1981. "providers": {
  1982. name: config.get("name", name)
  1983. for name, config in OAUTH_PROVIDERS.items()
  1984. }
  1985. },
  1986. "features": {
  1987. "auth": WEBUI_AUTH,
  1988. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1989. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  1990. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1991. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1992. **(
  1993. {
  1994. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1995. "enable_image_generation": images_app.state.config.ENABLED,
  1996. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1997. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1998. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1999. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  2000. }
  2001. if user is not None
  2002. else {}
  2003. ),
  2004. },
  2005. **(
  2006. {
  2007. "default_models": webui_app.state.config.DEFAULT_MODELS,
  2008. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  2009. "audio": {
  2010. "tts": {
  2011. "engine": audio_app.state.config.TTS_ENGINE,
  2012. "voice": audio_app.state.config.TTS_VOICE,
  2013. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  2014. },
  2015. "stt": {
  2016. "engine": audio_app.state.config.STT_ENGINE,
  2017. },
  2018. },
  2019. "file": {
  2020. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  2021. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  2022. },
  2023. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  2024. }
  2025. if user is not None
  2026. else {}
  2027. ),
  2028. }
  2029. # TODO: webhook endpoint should be under config endpoints
  2030. @app.get("/api/webhook")
  2031. async def get_webhook_url(user=Depends(get_admin_user)):
  2032. return {
  2033. "url": app.state.config.WEBHOOK_URL,
  2034. }
  2035. class UrlForm(BaseModel):
  2036. url: str
  2037. @app.post("/api/webhook")
  2038. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  2039. app.state.config.WEBHOOK_URL = form_data.url
  2040. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  2041. return {"url": app.state.config.WEBHOOK_URL}
  2042. @app.get("/api/version")
  2043. async def get_app_version():
  2044. return {
  2045. "version": VERSION,
  2046. }
  2047. @app.get("/api/changelog")
  2048. async def get_app_changelog():
  2049. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  2050. @app.get("/api/version/updates")
  2051. async def get_app_latest_release_version():
  2052. if OFFLINE_MODE:
  2053. log.debug(
  2054. f"Offline mode is enabled, returning current version as latest version"
  2055. )
  2056. return {"current": VERSION, "latest": VERSION}
  2057. try:
  2058. timeout = aiohttp.ClientTimeout(total=1)
  2059. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  2060. async with session.get(
  2061. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  2062. ) as response:
  2063. response.raise_for_status()
  2064. data = await response.json()
  2065. latest_version = data["tag_name"]
  2066. return {"current": VERSION, "latest": latest_version[1:]}
  2067. except Exception as e:
  2068. log.debug(e)
  2069. return {"current": VERSION, "latest": VERSION}
  2070. ############################
  2071. # OAuth Login & Callback
  2072. ############################
  2073. # SessionMiddleware is used by authlib for oauth
  2074. if len(OAUTH_PROVIDERS) > 0:
  2075. app.add_middleware(
  2076. SessionMiddleware,
  2077. secret_key=WEBUI_SECRET_KEY,
  2078. session_cookie="oui-session",
  2079. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  2080. https_only=WEBUI_SESSION_COOKIE_SECURE,
  2081. )
  2082. @app.get("/oauth/{provider}/login")
  2083. async def oauth_login(provider: str, request: Request):
  2084. return await oauth_manager.handle_login(provider, request)
  2085. # OAuth login logic is as follows:
  2086. # 1. Attempt to find a user with matching subject ID, tied to the provider
  2087. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  2088. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  2089. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  2090. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  2091. @app.get("/oauth/{provider}/callback")
  2092. async def oauth_callback(provider: str, request: Request, response: Response):
  2093. return await oauth_manager.handle_callback(provider, request, response)
  2094. @app.get("/manifest.json")
  2095. async def get_manifest_json():
  2096. return {
  2097. "name": WEBUI_NAME,
  2098. "short_name": WEBUI_NAME,
  2099. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  2100. "start_url": "/",
  2101. "display": "standalone",
  2102. "background_color": "#343541",
  2103. "orientation": "natural",
  2104. "icons": [
  2105. {
  2106. "src": "/static/logo.png",
  2107. "type": "image/png",
  2108. "sizes": "500x500",
  2109. "purpose": "any",
  2110. },
  2111. {
  2112. "src": "/static/logo.png",
  2113. "type": "image/png",
  2114. "sizes": "500x500",
  2115. "purpose": "maskable",
  2116. },
  2117. ],
  2118. }
  2119. @app.get("/opensearch.xml")
  2120. async def get_opensearch_xml():
  2121. xml_content = rf"""
  2122. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  2123. <ShortName>{WEBUI_NAME}</ShortName>
  2124. <Description>Search {WEBUI_NAME}</Description>
  2125. <InputEncoding>UTF-8</InputEncoding>
  2126. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  2127. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  2128. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  2129. </OpenSearchDescription>
  2130. """
  2131. return Response(content=xml_content, media_type="application/xml")
  2132. @app.get("/health")
  2133. async def healthcheck():
  2134. return {"status": True}
  2135. @app.get("/health/db")
  2136. async def healthcheck_with_db():
  2137. Session.execute(text("SELECT 1;")).all()
  2138. return {"status": True}
  2139. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  2140. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  2141. if os.path.exists(FRONTEND_BUILD_DIR):
  2142. mimetypes.add_type("text/javascript", ".js")
  2143. app.mount(
  2144. "/",
  2145. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  2146. name="spa-static-files",
  2147. )
  2148. else:
  2149. log.warning(
  2150. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  2151. )