Functions.svelte 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import fileSaver from 'file-saver';
  4. const { saveAs } = fileSaver;
  5. import { WEBUI_NAME, config, functions, models, settings } from '$lib/stores';
  6. import { onMount, getContext, tick } from 'svelte';
  7. import { goto } from '$app/navigation';
  8. import {
  9. createNewFunction,
  10. deleteFunctionById,
  11. exportFunctions,
  12. getFunctionById,
  13. getFunctions,
  14. toggleFunctionById,
  15. toggleGlobalById
  16. } from '$lib/apis/functions';
  17. import ArrowDownTray from '../icons/ArrowDownTray.svelte';
  18. import Tooltip from '../common/Tooltip.svelte';
  19. import ConfirmDialog from '../common/ConfirmDialog.svelte';
  20. import { getModels } from '$lib/apis';
  21. import FunctionMenu from './Functions/FunctionMenu.svelte';
  22. import EllipsisHorizontal from '../icons/EllipsisHorizontal.svelte';
  23. import Switch from '../common/Switch.svelte';
  24. import ValvesModal from '../workspace/common/ValvesModal.svelte';
  25. import ManifestModal from '../workspace/common/ManifestModal.svelte';
  26. import Heart from '../icons/Heart.svelte';
  27. import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
  28. import GarbageBin from '../icons/GarbageBin.svelte';
  29. import Search from '../icons/Search.svelte';
  30. import Plus from '../icons/Plus.svelte';
  31. import ChevronRight from '../icons/ChevronRight.svelte';
  32. const i18n = getContext('i18n');
  33. let shiftKey = false;
  34. let functionsImportInputElement: HTMLInputElement;
  35. let importFiles;
  36. let showConfirm = false;
  37. let query = '';
  38. let showManifestModal = false;
  39. let showValvesModal = false;
  40. let selectedFunction = null;
  41. let showDeleteConfirm = false;
  42. let filteredItems = [];
  43. $: filteredItems = $functions
  44. .filter(
  45. (f) =>
  46. query === '' ||
  47. f.name.toLowerCase().includes(query.toLowerCase()) ||
  48. f.id.toLowerCase().includes(query.toLowerCase())
  49. )
  50. .sort((a, b) => a.type.localeCompare(b.type) || a.name.localeCompare(b.name));
  51. const shareHandler = async (func) => {
  52. const item = await getFunctionById(localStorage.token, func.id).catch((error) => {
  53. toast.error(`${error}`);
  54. return null;
  55. });
  56. toast.success($i18n.t('Redirecting you to Open WebUI Community'));
  57. const url = 'https://openwebui.com';
  58. const tab = await window.open(`${url}/functions/create`, '_blank');
  59. // Define the event handler function
  60. const messageHandler = (event) => {
  61. if (event.origin !== url) return;
  62. if (event.data === 'loaded') {
  63. tab.postMessage(JSON.stringify(item), '*');
  64. // Remove the event listener after handling the message
  65. window.removeEventListener('message', messageHandler);
  66. }
  67. };
  68. window.addEventListener('message', messageHandler, false);
  69. console.log(item);
  70. };
  71. const cloneHandler = async (func) => {
  72. const _function = await getFunctionById(localStorage.token, func.id).catch((error) => {
  73. toast.error(`${error}`);
  74. return null;
  75. });
  76. if (_function) {
  77. sessionStorage.function = JSON.stringify({
  78. ..._function,
  79. id: `${_function.id}_clone`,
  80. name: `${_function.name} (Clone)`
  81. });
  82. goto('/admin/functions/create');
  83. }
  84. };
  85. const exportHandler = async (func) => {
  86. const _function = await getFunctionById(localStorage.token, func.id).catch((error) => {
  87. toast.error(`${error}`);
  88. return null;
  89. });
  90. if (_function) {
  91. let blob = new Blob([JSON.stringify([_function])], {
  92. type: 'application/json'
  93. });
  94. saveAs(blob, `function-${_function.id}-export-${Date.now()}.json`);
  95. }
  96. };
  97. const deleteHandler = async (func) => {
  98. const res = await deleteFunctionById(localStorage.token, func.id).catch((error) => {
  99. toast.error(`${error}`);
  100. return null;
  101. });
  102. if (res) {
  103. toast.success($i18n.t('Function deleted successfully'));
  104. functions.set(await getFunctions(localStorage.token));
  105. models.set(
  106. await getModels(
  107. localStorage.token,
  108. $config?.features?.enable_direct_connections && ($settings?.directConnections ?? null)
  109. )
  110. );
  111. }
  112. };
  113. const toggleGlobalHandler = async (func) => {
  114. const res = await toggleGlobalById(localStorage.token, func.id).catch((error) => {
  115. toast.error(`${error}`);
  116. });
  117. if (res) {
  118. if (func.is_global) {
  119. func.type === 'filter'
  120. ? toast.success($i18n.t('Filter is now globally enabled'))
  121. : toast.success($i18n.t('Function is now globally enabled'));
  122. } else {
  123. func.type === 'filter'
  124. ? toast.success($i18n.t('Filter is now globally disabled'))
  125. : toast.success($i18n.t('Function is now globally disabled'));
  126. }
  127. functions.set(await getFunctions(localStorage.token));
  128. models.set(
  129. await getModels(
  130. localStorage.token,
  131. $config?.features?.enable_direct_connections && ($settings?.directConnections ?? null)
  132. )
  133. );
  134. }
  135. };
  136. onMount(() => {
  137. const onKeyDown = (event) => {
  138. if (event.key === 'Shift') {
  139. shiftKey = true;
  140. }
  141. };
  142. const onKeyUp = (event) => {
  143. if (event.key === 'Shift') {
  144. shiftKey = false;
  145. }
  146. };
  147. const onBlur = () => {
  148. shiftKey = false;
  149. };
  150. window.addEventListener('keydown', onKeyDown);
  151. window.addEventListener('keyup', onKeyUp);
  152. window.addEventListener('blur', onBlur);
  153. return () => {
  154. window.removeEventListener('keydown', onKeyDown);
  155. window.removeEventListener('keyup', onKeyUp);
  156. window.removeEventListener('blur', onBlur);
  157. };
  158. });
  159. </script>
  160. <svelte:head>
  161. <title>
  162. {$i18n.t('Functions')} | {$WEBUI_NAME}
  163. </title>
  164. </svelte:head>
  165. <div class="flex flex-col gap-1 mt-1.5 mb-2">
  166. <div class="flex justify-between items-center">
  167. <div class="flex md:self-center text-xl items-center font-medium px-0.5">
  168. {$i18n.t('Functions')}
  169. <div class="flex self-center w-[1px] h-6 mx-2.5 bg-gray-50 dark:bg-gray-850" />
  170. <span class="text-base font-lg text-gray-500 dark:text-gray-300">{filteredItems.length}</span>
  171. </div>
  172. </div>
  173. <div class=" flex w-full space-x-2">
  174. <div class="flex flex-1">
  175. <div class=" self-center ml-1 mr-3">
  176. <Search className="size-3.5" />
  177. </div>
  178. <input
  179. class=" w-full text-sm pr-4 py-1 rounded-r-xl outline-none bg-transparent"
  180. bind:value={query}
  181. placeholder={$i18n.t('Search Functions')}
  182. />
  183. </div>
  184. <div>
  185. <a
  186. class=" px-2 py-2 rounded-xl hover:bg-gray-700/10 dark:hover:bg-gray-100/10 dark:text-gray-300 dark:hover:text-white transition font-medium text-sm flex items-center space-x-1"
  187. href="/admin/functions/create"
  188. >
  189. <Plus className="size-3.5" />
  190. </a>
  191. </div>
  192. </div>
  193. </div>
  194. <div class="mb-5">
  195. {#each filteredItems as func (func.id)}
  196. <div
  197. class=" flex space-x-4 cursor-pointer w-full px-3 py-2 dark:hover:bg-white/5 hover:bg-black/5 rounded-xl"
  198. >
  199. <a
  200. class=" flex flex-1 space-x-3.5 cursor-pointer w-full"
  201. href={`/admin/functions/edit?id=${encodeURIComponent(func.id)}`}
  202. >
  203. <div class="flex items-center text-left">
  204. <div class=" flex-1 self-center pl-1">
  205. <div class=" font-semibold flex items-center gap-1.5">
  206. <div
  207. class=" text-xs font-bold px-1 rounded uppercase line-clamp-1 bg-gray-500/20 text-gray-700 dark:text-gray-200"
  208. >
  209. {func.type}
  210. </div>
  211. {#if func?.meta?.manifest?.version}
  212. <div
  213. class="text-xs font-bold px-1 rounded line-clamp-1 bg-gray-500/20 text-gray-700 dark:text-gray-200"
  214. >
  215. v{func?.meta?.manifest?.version ?? ''}
  216. </div>
  217. {/if}
  218. <div class=" line-clamp-1">
  219. {func.name}
  220. </div>
  221. </div>
  222. <div class="flex gap-1.5 px-1">
  223. <div class=" text-gray-500 text-xs font-medium flex-shrink-0">{func.id}</div>
  224. <div class=" text-xs overflow-hidden text-ellipsis line-clamp-1">
  225. {func.meta.description}
  226. </div>
  227. </div>
  228. </div>
  229. </div>
  230. </a>
  231. <div class="flex flex-row gap-0.5 self-center">
  232. {#if shiftKey}
  233. <Tooltip content={$i18n.t('Delete')}>
  234. <button
  235. class="self-center w-fit text-sm px-2 py-2 dark:text-gray-300 dark:hover:text-white hover:bg-black/5 dark:hover:bg-white/5 rounded-xl"
  236. type="button"
  237. on:click={() => {
  238. deleteHandler(func);
  239. }}
  240. >
  241. <GarbageBin />
  242. </button>
  243. </Tooltip>
  244. {:else}
  245. {#if func?.meta?.manifest?.funding_url ?? false}
  246. <Tooltip content={$i18n.t('Support')}>
  247. <button
  248. class="self-center w-fit text-sm px-2 py-2 dark:text-gray-300 dark:hover:text-white hover:bg-black/5 dark:hover:bg-white/5 rounded-xl"
  249. type="button"
  250. on:click={() => {
  251. selectedFunction = func;
  252. showManifestModal = true;
  253. }}
  254. >
  255. <Heart />
  256. </button>
  257. </Tooltip>
  258. {/if}
  259. <Tooltip content={$i18n.t('Valves')}>
  260. <button
  261. class="self-center w-fit text-sm px-2 py-2 dark:text-gray-300 dark:hover:text-white hover:bg-black/5 dark:hover:bg-white/5 rounded-xl"
  262. type="button"
  263. on:click={() => {
  264. selectedFunction = func;
  265. showValvesModal = true;
  266. }}
  267. >
  268. <svg
  269. xmlns="http://www.w3.org/2000/svg"
  270. fill="none"
  271. viewBox="0 0 24 24"
  272. stroke-width="1.5"
  273. stroke="currentColor"
  274. class="size-4"
  275. >
  276. <path
  277. stroke-linecap="round"
  278. stroke-linejoin="round"
  279. d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"
  280. />
  281. <path
  282. stroke-linecap="round"
  283. stroke-linejoin="round"
  284. d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
  285. />
  286. </svg>
  287. </button>
  288. </Tooltip>
  289. <FunctionMenu
  290. {func}
  291. editHandler={() => {
  292. goto(`/admin/functions/edit?id=${encodeURIComponent(func.id)}`);
  293. }}
  294. shareHandler={() => {
  295. shareHandler(func);
  296. }}
  297. cloneHandler={() => {
  298. cloneHandler(func);
  299. }}
  300. exportHandler={() => {
  301. exportHandler(func);
  302. }}
  303. deleteHandler={async () => {
  304. selectedFunction = func;
  305. showDeleteConfirm = true;
  306. }}
  307. toggleGlobalHandler={() => {
  308. if (['filter', 'action'].includes(func.type)) {
  309. toggleGlobalHandler(func);
  310. }
  311. }}
  312. onClose={() => {}}
  313. >
  314. <button
  315. class="self-center w-fit text-sm p-1.5 dark:text-gray-300 dark:hover:text-white hover:bg-black/5 dark:hover:bg-white/5 rounded-xl"
  316. type="button"
  317. >
  318. <EllipsisHorizontal className="size-5" />
  319. </button>
  320. </FunctionMenu>
  321. {/if}
  322. <div class=" self-center mx-1">
  323. <Tooltip content={func.is_active ? $i18n.t('Enabled') : $i18n.t('Disabled')}>
  324. <Switch
  325. bind:state={func.is_active}
  326. on:change={async (e) => {
  327. toggleFunctionById(localStorage.token, func.id);
  328. models.set(
  329. await getModels(
  330. localStorage.token,
  331. $config?.features?.enable_direct_connections &&
  332. ($settings?.directConnections ?? null)
  333. )
  334. );
  335. }}
  336. />
  337. </Tooltip>
  338. </div>
  339. </div>
  340. </div>
  341. {/each}
  342. </div>
  343. <!-- <div class=" text-gray-500 text-xs mt-1 mb-2">
  344. ⓘ {$i18n.t(
  345. 'Admins have access to all tools at all times; users need tools assigned per model in the workspace.'
  346. )}
  347. </div> -->
  348. <div class=" flex justify-end w-full mb-2">
  349. <div class="flex space-x-2">
  350. <input
  351. id="documents-import-input"
  352. bind:this={functionsImportInputElement}
  353. bind:files={importFiles}
  354. type="file"
  355. accept=".json"
  356. hidden
  357. on:change={() => {
  358. console.log(importFiles);
  359. showConfirm = true;
  360. }}
  361. />
  362. <button
  363. class="flex text-xs items-center space-x-1 px-3 py-1.5 rounded-xl bg-gray-50 hover:bg-gray-100 dark:bg-gray-800 dark:hover:bg-gray-700 dark:text-gray-200 transition"
  364. on:click={() => {
  365. functionsImportInputElement.click();
  366. }}
  367. >
  368. <div class=" self-center mr-2 font-medium line-clamp-1">{$i18n.t('Import Functions')}</div>
  369. <div class=" self-center">
  370. <svg
  371. xmlns="http://www.w3.org/2000/svg"
  372. viewBox="0 0 16 16"
  373. fill="currentColor"
  374. class="w-4 h-4"
  375. >
  376. <path
  377. fill-rule="evenodd"
  378. d="M4 2a1.5 1.5 0 0 0-1.5 1.5v9A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5V6.621a1.5 1.5 0 0 0-.44-1.06L9.94 2.439A1.5 1.5 0 0 0 8.878 2H4Zm4 9.5a.75.75 0 0 1-.75-.75V8.06l-.72.72a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06l-.72-.72v2.69a.75.75 0 0 1-.75.75Z"
  379. clip-rule="evenodd"
  380. />
  381. </svg>
  382. </div>
  383. </button>
  384. <button
  385. class="flex text-xs items-center space-x-1 px-3 py-1.5 rounded-xl bg-gray-50 hover:bg-gray-100 dark:bg-gray-800 dark:hover:bg-gray-700 dark:text-gray-200 transition"
  386. on:click={async () => {
  387. const _functions = await exportFunctions(localStorage.token).catch((error) => {
  388. toast.error(`${error}`);
  389. return null;
  390. });
  391. if (_functions) {
  392. let blob = new Blob([JSON.stringify(_functions)], {
  393. type: 'application/json'
  394. });
  395. saveAs(blob, `functions-export-${Date.now()}.json`);
  396. }
  397. }}
  398. >
  399. <div class=" self-center mr-2 font-medium line-clamp-1">{$i18n.t('Export Functions')}</div>
  400. <div class=" self-center">
  401. <svg
  402. xmlns="http://www.w3.org/2000/svg"
  403. viewBox="0 0 16 16"
  404. fill="currentColor"
  405. class="w-4 h-4"
  406. >
  407. <path
  408. fill-rule="evenodd"
  409. d="M4 2a1.5 1.5 0 0 0-1.5 1.5v9A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5V6.621a1.5 1.5 0 0 0-.44-1.06L9.94 2.439A1.5 1.5 0 0 0 8.878 2H4Zm4 3.5a.75.75 0 0 1 .75.75v2.69l.72-.72a.75.75 0 1 1 1.06 1.06l-2 2a.75.75 0 0 1-1.06 0l-2-2a.75.75 0 0 1 1.06-1.06l.72.72V6.25A.75.75 0 0 1 8 5.5Z"
  410. clip-rule="evenodd"
  411. />
  412. </svg>
  413. </div>
  414. </button>
  415. </div>
  416. </div>
  417. {#if $config?.features.enable_community_sharing}
  418. <div class=" my-16">
  419. <div class=" text-xl font-medium mb-1 line-clamp-1">
  420. {$i18n.t('Made by Open WebUI Community')}
  421. </div>
  422. <a
  423. class=" flex cursor-pointer items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-850 w-full mb-2 px-3.5 py-1.5 rounded-xl transition"
  424. href="https://openwebui.com/#open-webui-community"
  425. target="_blank"
  426. >
  427. <div class=" self-center">
  428. <div class=" font-semibold line-clamp-1">{$i18n.t('Discover a function')}</div>
  429. <div class=" text-sm line-clamp-1">
  430. {$i18n.t('Discover, download, and explore custom functions')}
  431. </div>
  432. </div>
  433. <div>
  434. <div>
  435. <ChevronRight />
  436. </div>
  437. </div>
  438. </a>
  439. </div>
  440. {/if}
  441. <DeleteConfirmDialog
  442. bind:show={showDeleteConfirm}
  443. title={$i18n.t('Delete function?')}
  444. on:confirm={() => {
  445. deleteHandler(selectedFunction);
  446. }}
  447. >
  448. <div class=" text-sm text-gray-500">
  449. {$i18n.t('This will delete')} <span class=" font-semibold">{selectedFunction.name}</span>.
  450. </div>
  451. </DeleteConfirmDialog>
  452. <ManifestModal bind:show={showManifestModal} manifest={selectedFunction?.meta?.manifest ?? {}} />
  453. <ValvesModal
  454. bind:show={showValvesModal}
  455. type="function"
  456. id={selectedFunction?.id ?? null}
  457. on:save={async () => {
  458. await tick();
  459. models.set(
  460. await getModels(
  461. localStorage.token,
  462. $config?.features?.enable_direct_connections && ($settings?.directConnections ?? null)
  463. )
  464. );
  465. }}
  466. />
  467. <ConfirmDialog
  468. bind:show={showConfirm}
  469. on:confirm={() => {
  470. const reader = new FileReader();
  471. reader.onload = async (event) => {
  472. const _functions = JSON.parse(event.target.result);
  473. console.log(_functions);
  474. for (const func of _functions) {
  475. const res = await createNewFunction(localStorage.token, func).catch((error) => {
  476. toast.error(`${error}`);
  477. return null;
  478. });
  479. }
  480. toast.success($i18n.t('Functions imported successfully'));
  481. functions.set(await getFunctions(localStorage.token));
  482. models.set(
  483. await getModels(
  484. localStorage.token,
  485. $config?.features?.enable_direct_connections && ($settings?.directConnections ?? null)
  486. )
  487. );
  488. };
  489. reader.readAsText(importFiles[0]);
  490. }}
  491. >
  492. <div class="text-sm text-gray-500">
  493. <div class=" bg-yellow-500/20 text-yellow-700 dark:text-yellow-200 rounded-lg px-4 py-3">
  494. <div>Please carefully review the following warnings:</div>
  495. <ul class=" mt-1 list-disc pl-4 text-xs">
  496. <li>{$i18n.t('Functions allow arbitrary code execution.')}</li>
  497. <li>{$i18n.t('Do not install functions from sources you do not fully trust.')}</li>
  498. </ul>
  499. </div>
  500. <div class="my-3">
  501. {$i18n.t(
  502. 'I acknowledge that I have read and I understand the implications of my action. I am aware of the risks associated with executing arbitrary code and I have verified the trustworthiness of the source.'
  503. )}
  504. </div>
  505. </div>
  506. </ConfirmDialog>