main.py 86 KB

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