ModelEditor.svelte 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <script lang="ts">
  2. import { v4 as uuidv4 } from 'uuid';
  3. import { toast } from 'svelte-sonner';
  4. import { goto } from '$app/navigation';
  5. import { onMount, getContext, tick } from 'svelte';
  6. import { models, tools, functions, knowledge as knowledgeCollections } from '$lib/stores';
  7. import AdvancedParams from '$lib/components/chat/Settings/Advanced/AdvancedParams.svelte';
  8. import Tags from '$lib/components/common/Tags.svelte';
  9. import Knowledge from '$lib/components/workspace/Models/Knowledge.svelte';
  10. import ToolsSelector from '$lib/components/workspace/Models/ToolsSelector.svelte';
  11. import FiltersSelector from '$lib/components/workspace/Models/FiltersSelector.svelte';
  12. import ActionsSelector from '$lib/components/workspace/Models/ActionsSelector.svelte';
  13. import Capabilities from '$lib/components/workspace/Models/Capabilities.svelte';
  14. import Textarea from '$lib/components/common/Textarea.svelte';
  15. const i18n = getContext('i18n');
  16. export let onSubmit: Function;
  17. export let model = null;
  18. export let edit = false;
  19. let loading = false;
  20. let success = false;
  21. let filesInputElement;
  22. let inputFiles;
  23. let showAdvanced = false;
  24. let showPreview = false;
  25. // ///////////
  26. // model
  27. // ///////////
  28. let id = '';
  29. let name = '';
  30. $: if (!edit) {
  31. if (name) {
  32. id = name
  33. .replace(/\s+/g, '-')
  34. .replace(/[^a-zA-Z0-9-]/g, '')
  35. .toLowerCase();
  36. }
  37. }
  38. let info = {
  39. id: '',
  40. base_model_id: null,
  41. name: '',
  42. meta: {
  43. profile_image_url: '/static/favicon.png',
  44. description: '',
  45. suggestion_prompts: null,
  46. tags: []
  47. },
  48. params: {
  49. system: ''
  50. }
  51. };
  52. let params = {};
  53. let capabilities = {
  54. vision: true,
  55. usage: undefined
  56. };
  57. let knowledge = [];
  58. let toolIds = [];
  59. let filterIds = [];
  60. let actionIds = [];
  61. const addUsage = (base_model_id) => {
  62. const baseModel = $models.find((m) => m.id === base_model_id);
  63. if (baseModel) {
  64. if (baseModel.owned_by === 'openai') {
  65. capabilities.usage = baseModel.info?.meta?.capabilities?.usage ?? false;
  66. } else {
  67. delete capabilities.usage;
  68. }
  69. capabilities = capabilities;
  70. }
  71. };
  72. const submitHandler = async () => {
  73. loading = true;
  74. info.id = id;
  75. info.name = name;
  76. info.meta.capabilities = capabilities;
  77. if (knowledge.length > 0) {
  78. info.meta.knowledge = knowledge;
  79. } else {
  80. if (info.meta.knowledge) {
  81. delete info.meta.knowledge;
  82. }
  83. }
  84. if (toolIds.length > 0) {
  85. info.meta.toolIds = toolIds;
  86. } else {
  87. if (info.meta.toolIds) {
  88. delete info.meta.toolIds;
  89. }
  90. }
  91. if (filterIds.length > 0) {
  92. info.meta.filterIds = filterIds;
  93. } else {
  94. if (info.meta.filterIds) {
  95. delete info.meta.filterIds;
  96. }
  97. }
  98. if (actionIds.length > 0) {
  99. info.meta.actionIds = actionIds;
  100. } else {
  101. if (info.meta.actionIds) {
  102. delete info.meta.actionIds;
  103. }
  104. }
  105. info.params.stop = params.stop ? params.stop.split(',').filter((s) => s.trim()) : null;
  106. Object.keys(info.params).forEach((key) => {
  107. if (info.params[key] === '' || info.params[key] === null) {
  108. delete info.params[key];
  109. }
  110. });
  111. await onSubmit(info);
  112. loading = false;
  113. success = false;
  114. };
  115. onMount(async () => {
  116. // Scroll to top 'workspace-container' element
  117. const workspaceContainer = document.getElementById('workspace-container');
  118. if (workspaceContainer) {
  119. workspaceContainer.scrollTop = 0;
  120. }
  121. if (model) {
  122. name = model.name;
  123. await tick();
  124. id = model.id;
  125. if (model.info.base_model_id) {
  126. const base_model = $models
  127. .filter((m) => !m?.preset && m?.owned_by !== 'arena')
  128. .find((m) =>
  129. [model.info.base_model_id, `${model.info.base_model_id}:latest`].includes(m.id)
  130. );
  131. console.log('base_model', base_model);
  132. if (base_model) {
  133. model.info.base_model_id = base_model.id;
  134. } else {
  135. model.info.base_model_id = null;
  136. }
  137. }
  138. params = { ...params, ...model?.info?.params };
  139. params.stop = params?.stop
  140. ? (typeof params.stop === 'string' ? params.stop.split(',') : (params?.stop ?? [])).join(
  141. ','
  142. )
  143. : null;
  144. toolIds = model?.info?.meta?.toolIds ?? [];
  145. filterIds = model?.info?.meta?.filterIds ?? [];
  146. actionIds = model?.info?.meta?.actionIds ?? [];
  147. knowledge = (model?.info?.meta?.knowledge ?? []).map((item) => {
  148. if (item?.collection_name) {
  149. return {
  150. id: item.collection_name,
  151. name: item.name,
  152. legacy: true
  153. };
  154. } else if (item?.collection_names) {
  155. return {
  156. name: item.name,
  157. type: 'collection',
  158. collection_names: item.collection_names,
  159. legacy: true
  160. };
  161. } else {
  162. return item;
  163. }
  164. });
  165. capabilities = { ...capabilities, ...(model?.info?.meta?.capabilities ?? {}) };
  166. if (model?.owned_by === 'openai') {
  167. capabilities.usage = false;
  168. }
  169. info = {
  170. ...info,
  171. ...JSON.parse(
  172. JSON.stringify(
  173. model?.info
  174. ? model?.info
  175. : {
  176. id: model.id,
  177. name: model.name
  178. }
  179. )
  180. )
  181. };
  182. console.log(model);
  183. }
  184. });
  185. </script>
  186. <div class="w-full max-h-full">
  187. <input
  188. bind:this={filesInputElement}
  189. bind:files={inputFiles}
  190. type="file"
  191. hidden
  192. accept="image/*"
  193. on:change={() => {
  194. let reader = new FileReader();
  195. reader.onload = (event) => {
  196. let originalImageUrl = `${event.target.result}`;
  197. const img = new Image();
  198. img.src = originalImageUrl;
  199. img.onload = function () {
  200. const canvas = document.createElement('canvas');
  201. const ctx = canvas.getContext('2d');
  202. // Calculate the aspect ratio of the image
  203. const aspectRatio = img.width / img.height;
  204. // Calculate the new width and height to fit within 100x100
  205. let newWidth, newHeight;
  206. if (aspectRatio > 1) {
  207. newWidth = 250 * aspectRatio;
  208. newHeight = 250;
  209. } else {
  210. newWidth = 250;
  211. newHeight = 250 / aspectRatio;
  212. }
  213. // Set the canvas size
  214. canvas.width = 250;
  215. canvas.height = 250;
  216. // Calculate the position to center the image
  217. const offsetX = (250 - newWidth) / 2;
  218. const offsetY = (250 - newHeight) / 2;
  219. // Draw the image on the canvas
  220. ctx.drawImage(img, offsetX, offsetY, newWidth, newHeight);
  221. // Get the base64 representation of the compressed image
  222. const compressedSrc = canvas.toDataURL();
  223. // Display the compressed image
  224. info.meta.profile_image_url = compressedSrc;
  225. inputFiles = null;
  226. };
  227. };
  228. if (
  229. inputFiles &&
  230. inputFiles.length > 0 &&
  231. ['image/gif', 'image/webp', 'image/jpeg', 'image/png', 'image/svg+xml'].includes(
  232. inputFiles[0]['type']
  233. )
  234. ) {
  235. reader.readAsDataURL(inputFiles[0]);
  236. } else {
  237. console.log(`Unsupported File Type '${inputFiles[0]['type']}'.`);
  238. inputFiles = null;
  239. }
  240. }}
  241. />
  242. {#if !edit || model}
  243. <form
  244. class="flex flex-col md:flex-row mx-auto gap-3 md:gap-6"
  245. on:submit|preventDefault={() => {
  246. submitHandler();
  247. }}
  248. >
  249. <div class="self-center md:self-start flex justify-center my-2 flex-shrink-0">
  250. <div class="self-center">
  251. <button
  252. class="rounded-2xl flex flex-shrink-0 items-center bg-white"
  253. type="button"
  254. on:click={() => {
  255. filesInputElement.click();
  256. }}
  257. >
  258. {#if info.meta.profile_image_url}
  259. <img
  260. src={info.meta.profile_image_url}
  261. alt="model profile"
  262. class="rounded-lg size-64 object-cover shrink-0"
  263. />
  264. {:else}
  265. <img
  266. src="/static/favicon.png"
  267. alt="model profile"
  268. class=" rounded-lg size-64 object-cover shrink-0"
  269. />
  270. {/if}
  271. </button>
  272. </div>
  273. </div>
  274. <div>
  275. <div class="mt-2 my-2 flex flex-col">
  276. <div class="flex-1">
  277. <div>
  278. <input
  279. class="text-3xl font-semibold w-full bg-transparent outline-none"
  280. placeholder={$i18n.t('Model Name')}
  281. bind:value={name}
  282. required
  283. />
  284. </div>
  285. </div>
  286. <div class="flex-1">
  287. <!-- <div class=" text-sm font-semibold">{$i18n.t('Model ID')}*</div> -->
  288. <div>
  289. <input
  290. class="text-xs w-full bg-transparent text-gray-500 outline-none rounded-lg"
  291. placeholder={$i18n.t('Model ID')}
  292. value={id}
  293. disabled={edit}
  294. required
  295. />
  296. </div>
  297. </div>
  298. </div>
  299. {#if !edit || model.preset}
  300. <div class="my-1">
  301. <div class=" text-sm font-semibold mb-1">{$i18n.t('Base Model (From)')}</div>
  302. <div>
  303. <select
  304. class="text-sm w-full bg-transparent outline-none rounded-lg"
  305. placeholder="Select a base model (e.g. llama3, gpt-4o)"
  306. bind:value={info.base_model_id}
  307. on:change={(e) => {
  308. addUsage(e.target.value);
  309. }}
  310. required
  311. >
  312. <option value={null} class=" text-gray-900">{$i18n.t('Select a base model')}</option
  313. >
  314. {#each $models.filter((m) => (model ? m.id !== model.id : true) && !m?.preset && m?.owned_by !== 'arena') as model}
  315. <option value={model.id} class=" text-gray-900">{model.name}</option>
  316. {/each}
  317. </select>
  318. </div>
  319. </div>
  320. {/if}
  321. <div class="my-1">
  322. <div class="mb-1 flex w-full justify-between items-center">
  323. <div class=" self-center text-sm font-semibold">{$i18n.t('Description')}</div>
  324. <button
  325. class="p-1 text-xs flex rounded transition"
  326. type="button"
  327. on:click={() => {
  328. if (info.meta.description === null) {
  329. info.meta.description = '';
  330. } else {
  331. info.meta.description = null;
  332. }
  333. }}
  334. >
  335. {#if info.meta.description === null}
  336. <span class="ml-2 self-center">{$i18n.t('Default')}</span>
  337. {:else}
  338. <span class="ml-2 self-center">{$i18n.t('Custom')}</span>
  339. {/if}
  340. </button>
  341. </div>
  342. {#if info.meta.description !== null}
  343. <Textarea
  344. className=" text-sm w-full bg-transparent outline-none resize-none overflow-y-hidden "
  345. placeholder={$i18n.t('Add a short description about what this model does')}
  346. rows={3}
  347. bind:value={info.meta.description}
  348. />
  349. {/if}
  350. </div>
  351. <hr class=" dark:border-gray-850 my-1.5" />
  352. <div class="my-2">
  353. <div class="flex w-full justify-between">
  354. <div class=" self-center text-sm font-semibold">{$i18n.t('Model Params')}</div>
  355. </div>
  356. <!-- <div class=" text-sm font-semibold mb-2"></div> -->
  357. <div class="mt-2">
  358. <div class="my-1">
  359. <div class=" text-xs font-semibold mb-2">{$i18n.t('System Prompt')}</div>
  360. <div>
  361. <Textarea
  362. className=" text-sm w-full bg-transparent outline-none resize-none overflow-y-hidden "
  363. placeholder={`Write your model system prompt content here\ne.g.) You are Mario from Super Mario Bros, acting as an assistant.`}
  364. rows={4}
  365. bind:value={info.params.system}
  366. />
  367. </div>
  368. </div>
  369. <div class="flex w-full justify-between">
  370. <div class=" self-center text-xs font-semibold">
  371. {$i18n.t('Advanced Params')}
  372. </div>
  373. <button
  374. class="p-1 px-3 text-xs flex rounded transition"
  375. type="button"
  376. on:click={() => {
  377. showAdvanced = !showAdvanced;
  378. }}
  379. >
  380. {#if showAdvanced}
  381. <span class="ml-2 self-center">{$i18n.t('Hide')}</span>
  382. {:else}
  383. <span class="ml-2 self-center">{$i18n.t('Show')}</span>
  384. {/if}
  385. </button>
  386. </div>
  387. {#if showAdvanced}
  388. <div class="my-2">
  389. <AdvancedParams
  390. admin={true}
  391. bind:params
  392. on:change={(e) => {
  393. info.params = { ...info.params, ...params };
  394. }}
  395. />
  396. </div>
  397. {/if}
  398. </div>
  399. </div>
  400. <hr class=" dark:border-gray-850 my-1" />
  401. <div class="my-2">
  402. <div class="flex w-full justify-between items-center">
  403. <div class="flex w-full justify-between items-center">
  404. <div class=" self-center text-sm font-semibold">{$i18n.t('Prompt suggestions')}</div>
  405. <button
  406. class="p-1 text-xs flex rounded transition"
  407. type="button"
  408. on:click={() => {
  409. if ((info?.meta?.suggestion_prompts ?? null) === null) {
  410. info.meta.suggestion_prompts = [{ content: '' }];
  411. } else {
  412. info.meta.suggestion_prompts = null;
  413. }
  414. }}
  415. >
  416. {#if (info?.meta?.suggestion_prompts ?? null) === null}
  417. <span class="ml-2 self-center">{$i18n.t('Default')}</span>
  418. {:else}
  419. <span class="ml-2 self-center">{$i18n.t('Custom')}</span>
  420. {/if}
  421. </button>
  422. </div>
  423. {#if (info?.meta?.suggestion_prompts ?? null) !== null}
  424. <button
  425. class="p-1 px-2 text-xs flex rounded transition"
  426. type="button"
  427. on:click={() => {
  428. if (
  429. info.meta.suggestion_prompts.length === 0 ||
  430. info.meta.suggestion_prompts.at(-1).content !== ''
  431. ) {
  432. info.meta.suggestion_prompts = [
  433. ...info.meta.suggestion_prompts,
  434. { content: '' }
  435. ];
  436. }
  437. }}
  438. >
  439. <svg
  440. xmlns="http://www.w3.org/2000/svg"
  441. viewBox="0 0 20 20"
  442. fill="currentColor"
  443. class="w-4 h-4"
  444. >
  445. <path
  446. d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
  447. />
  448. </svg>
  449. </button>
  450. {/if}
  451. </div>
  452. {#if info?.meta?.suggestion_prompts}
  453. <div class="flex flex-col space-y-1 mt-2">
  454. {#if info.meta.suggestion_prompts.length > 0}
  455. {#each info.meta.suggestion_prompts as prompt, promptIdx}
  456. <div class=" flex border dark:border-gray-600 rounded-lg">
  457. <input
  458. class="px-3 py-1.5 text-sm w-full bg-transparent outline-none border-r dark:border-gray-600"
  459. placeholder={$i18n.t('Write a prompt suggestion (e.g. Who are you?)')}
  460. bind:value={prompt.content}
  461. />
  462. <button
  463. class="px-2"
  464. type="button"
  465. on:click={() => {
  466. info.meta.suggestion_prompts.splice(promptIdx, 1);
  467. info.meta.suggestion_prompts = info.meta.suggestion_prompts;
  468. }}
  469. >
  470. <svg
  471. xmlns="http://www.w3.org/2000/svg"
  472. viewBox="0 0 20 20"
  473. fill="currentColor"
  474. class="w-4 h-4"
  475. >
  476. <path
  477. d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
  478. />
  479. </svg>
  480. </button>
  481. </div>
  482. {/each}
  483. {:else}
  484. <div class="text-xs text-center">No suggestion prompts</div>
  485. {/if}
  486. </div>
  487. {/if}
  488. </div>
  489. <hr class=" dark:border-gray-850 my-1.5" />
  490. <div class="my-2">
  491. <Knowledge bind:selectedKnowledge={knowledge} collections={$knowledgeCollections} />
  492. </div>
  493. <div class="my-2">
  494. <ToolsSelector bind:selectedToolIds={toolIds} tools={$tools} />
  495. </div>
  496. <div class="my-2">
  497. <FiltersSelector
  498. bind:selectedFilterIds={filterIds}
  499. filters={$functions.filter((func) => func.type === 'filter')}
  500. />
  501. </div>
  502. <div class="my-2">
  503. <ActionsSelector
  504. bind:selectedActionIds={actionIds}
  505. actions={$functions.filter((func) => func.type === 'action')}
  506. />
  507. </div>
  508. <div class="my-2">
  509. <Capabilities bind:capabilities />
  510. </div>
  511. <div class="my-1">
  512. <div class="flex w-full justify-between items-center">
  513. <div class=" self-center text-sm font-semibold">{$i18n.t('Tags')}</div>
  514. </div>
  515. <div class="mt-2">
  516. <Tags
  517. tags={info?.meta?.tags ?? []}
  518. on:delete={(e) => {
  519. const tagName = e.detail;
  520. info.meta.tags = info.meta.tags.filter((tag) => tag.name !== tagName);
  521. }}
  522. on:add={(e) => {
  523. const tagName = e.detail;
  524. if (!(info?.meta?.tags ?? null)) {
  525. info.meta.tags = [{ name: tagName }];
  526. } else {
  527. info.meta.tags = [...info.meta.tags, { name: tagName }];
  528. }
  529. }}
  530. />
  531. </div>
  532. </div>
  533. <div class="my-2 text-gray-300 dark:text-gray-700">
  534. <div class="flex w-full justify-between mb-2">
  535. <div class=" self-center text-sm font-semibold">{$i18n.t('JSON Preview')}</div>
  536. <button
  537. class="p-1 px-3 text-xs flex rounded transition"
  538. type="button"
  539. on:click={() => {
  540. showPreview = !showPreview;
  541. }}
  542. >
  543. {#if showPreview}
  544. <span class="ml-2 self-center">{$i18n.t('Hide')}</span>
  545. {:else}
  546. <span class="ml-2 self-center">{$i18n.t('Show')}</span>
  547. {/if}
  548. </button>
  549. </div>
  550. {#if showPreview}
  551. <div>
  552. <textarea
  553. class="text-sm w-full bg-transparent outline-none resize-none"
  554. rows="10"
  555. value={JSON.stringify(info, null, 2)}
  556. disabled
  557. readonly
  558. />
  559. </div>
  560. {/if}
  561. </div>
  562. <div class="my-2 flex justify-end mb-20">
  563. <button
  564. class=" text-sm px-3 py-2 transition rounded-xl {loading
  565. ? ' cursor-not-allowed bg-gray-100 dark:bg-gray-800'
  566. : ' bg-gray-50 hover:bg-gray-100 dark:bg-white dark:hover:bg-gray-100 dark:text-black'} flex w-full justify-center"
  567. type="submit"
  568. disabled={loading}
  569. >
  570. <div class=" self-center font-medium">
  571. {#if edit}
  572. {$i18n.t('Save & Update')}
  573. {:else}
  574. {$i18n.t('Save & Create')}
  575. {/if}
  576. </div>
  577. {#if loading}
  578. <div class="ml-1.5 self-center">
  579. <svg
  580. class=" w-4 h-4"
  581. viewBox="0 0 24 24"
  582. fill="currentColor"
  583. xmlns="http://www.w3.org/2000/svg"
  584. ><style>
  585. .spinner_ajPY {
  586. transform-origin: center;
  587. animation: spinner_AtaB 0.75s infinite linear;
  588. }
  589. @keyframes spinner_AtaB {
  590. 100% {
  591. transform: rotate(360deg);
  592. }
  593. }
  594. </style><path
  595. d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
  596. opacity=".25"
  597. /><path
  598. d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
  599. class="spinner_ajPY"
  600. /></svg
  601. >
  602. </div>
  603. {/if}
  604. </button>
  605. </div>
  606. </div>
  607. </form>
  608. {/if}
  609. </div>